|
| 1 | +import type Parser from "tree-sitter"; |
| 2 | +import { |
| 3 | + type ExportedNamespace, |
| 4 | + type ExportedSymbol, |
| 5 | + PHP_VARIABLE, |
| 6 | +} from "./types.ts"; |
| 7 | +import { INTERESTING_NODES, PHP_IDNODE_QUERY } from "./queries.ts"; |
| 8 | + |
| 9 | +export class PHPExportResolver { |
| 10 | + #currentNamespace: string = ""; |
| 11 | + #currentFile: string = ""; |
| 12 | + |
| 13 | + resolveFile( |
| 14 | + file: { path: string; rootNode: Parser.SyntaxNode }, |
| 15 | + ): Map<string, ExportedNamespace> { |
| 16 | + const namespaces: Map<string, ExportedNamespace> = new Map(); |
| 17 | + this.#currentNamespace = |
| 18 | + file.rootNode.children.find((c) => |
| 19 | + c.type === "namespace_definition" && !c.childForFieldName("body") |
| 20 | + )?.childForFieldName("name")?.text ?? ""; |
| 21 | + this.#currentFile = file.path; |
| 22 | + const allSymbols = this.#resolveNode(file.rootNode, this.#currentNamespace); |
| 23 | + for (const symbol of allSymbols) { |
| 24 | + if (!namespaces.has(symbol.namespace)) { |
| 25 | + namespaces.set(symbol.namespace, { |
| 26 | + name: symbol.namespace, |
| 27 | + symbols: [], |
| 28 | + }); |
| 29 | + } |
| 30 | + namespaces.get(symbol.namespace)!.symbols.push(symbol); |
| 31 | + } |
| 32 | + return namespaces; |
| 33 | + } |
| 34 | + |
| 35 | + #resolveNode(node: Parser.SyntaxNode, nsname: string): ExportedSymbol[] { |
| 36 | + const exports: ExportedSymbol[] = []; |
| 37 | + for (const child of node.children) { |
| 38 | + if (INTERESTING_NODES.has(child.type)) { |
| 39 | + const idNode = PHP_IDNODE_QUERY.captures(child).at(0); |
| 40 | + if (!idNode) { |
| 41 | + continue; // Root out false positives for variables and constants |
| 42 | + } |
| 43 | + const symType = INTERESTING_NODES.get(child.type)!; |
| 44 | + if ( |
| 45 | + symType === PHP_VARIABLE && |
| 46 | + exports.find((e) => e.name === idNode.node.text) |
| 47 | + ) { |
| 48 | + continue; // No duplicate variables |
| 49 | + } |
| 50 | + exports.push({ |
| 51 | + name: idNode.node.text, |
| 52 | + type: symType, |
| 53 | + filepath: this.#currentFile, |
| 54 | + namespace: nsname, |
| 55 | + node: child, |
| 56 | + idNode: idNode.node, |
| 57 | + }); |
| 58 | + } |
| 59 | + } |
| 60 | + for ( |
| 61 | + const ns of node.children.filter((c) => |
| 62 | + c.type === "namespace_definition" && c.childForFieldName("body") |
| 63 | + ) |
| 64 | + ) { |
| 65 | + const fullnsname = (nsname !== "" ? nsname + "\\" : "") + |
| 66 | + ns.childForFieldName("name")!.text; |
| 67 | + const nsnode = ns.childForFieldName("body")!; |
| 68 | + exports.push(...this.#resolveNode(nsnode, fullnsname)); |
| 69 | + } |
| 70 | + return exports; |
| 71 | + } |
| 72 | +} |
0 commit comments