| 65 | /** A package's top-level type declarations and the methods declared on each. */ |
| 66 | const packages = new Map(); |
| 67 | function pkg(importPath) { |
| 68 | let found = packages.get(importPath); |
| 69 | if (found) return found; |
| 70 | found = { types: new Map(), methods: new Map() }; |
| 71 | packages.set(importPath, found); |
| 72 | const dir = path.join(goRoot, 'src', importPath); |
| 73 | const files = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith('.go') && !f.endsWith('_test.go')) : []; |
| 74 | for (const file of files) { |
| 75 | const tree = parser.parse(fs.readFileSync(path.join(dir, file), 'utf8')); |
| 76 | const imports = new Map(); |
| 77 | for (const spec of tree.rootNode.descendantsOfType('import_spec')) { |
| 78 | const ip = spec.childForFieldName('path')?.text.replace(/^"|"$/g, ''); |
| 79 | if (ip) imports.set(spec.childForFieldName('name')?.text ?? ip.split('/').pop(), ip); |
| 80 | } |
| 81 | for (const spec of tree.rootNode.descendantsOfType(['type_spec', 'type_alias'])) { |
| 82 | if (spec.parent?.type !== 'type_declaration' || spec.parent.parent?.type !== 'source_file') continue; |
| 83 | const name = spec.childForFieldName('name')?.text; |
| 84 | if (name && !found.types.has(name)) { |
| 85 | found.types.set(name, { type: spec.childForFieldName('type'), imports, alias: spec.type === 'type_alias' }); |
| 86 | } |
| 87 | } |
| 88 | for (const m of tree.rootNode.namedChildren.filter((c) => c.type === 'method_declaration')) { |
| 89 | const receiver = /\(\s*(?:\w+\s+)?\*?\s*(\w+)/.exec(m.childForFieldName('receiver')?.text ?? '')?.[1]; |
| 90 | const name = m.childForFieldName('name')?.text; |
| 91 | if (!receiver || !name) continue; |
| 92 | const methods = found.methods.get(receiver) ?? found.methods.set(receiver, new Map()).get(receiver); |
| 93 | if (!methods.has(name)) methods.set(name, goSignatureArity(signature(m))); |
| 94 | } |
| 95 | } |
| 96 | return found; |
| 97 | } |
| 98 | |
| 99 | /** Method name → `params/results` for the type `name` the package at `importPath` declares. */ |
| 100 | function methodsOf(importPath, name, seen = new Set()) { |