( filepath: string, contents: string, )
| 225 | ]; |
| 226 | |
| 227 | export async function getSymbolsForFile( |
| 228 | filepath: string, |
| 229 | contents: string, |
| 230 | ): Promise<SymbolWithRange[] | undefined> { |
| 231 | const parser = await getParserForFile(filepath); |
| 232 | if (!parser) { |
| 233 | return; |
| 234 | } |
| 235 | |
| 236 | let tree: Parser.Tree; |
| 237 | try { |
| 238 | tree = parser.parse(contents); |
| 239 | } catch (e) { |
| 240 | console.log(`Error parsing file: ${filepath}`); |
| 241 | return; |
| 242 | } |
| 243 | // console.log(`file: ${filepath}`); |
| 244 | |
| 245 | // Function to recursively find all named nodes (classes and functions) |
| 246 | const symbols: SymbolWithRange[] = []; |
| 247 | function findNamedNodesRecursive(node: Parser.SyntaxNode) { |
| 248 | // console.log(`node: ${node.type}, ${node.text}`); |
| 249 | if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) { |
| 250 | // console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); |
| 251 | // node.children.forEach((child) => { |
| 252 | // console.log(`child: ${child.type}, ${child.text}`); |
| 253 | // }); |
| 254 | |
| 255 | // Empirically, the actual name is the last identifier in the node |
| 256 | // Especially with languages where return type is declared before the name |
| 257 | // TODO use findLast in newer version of node target |
| 258 | let identifier: Parser.SyntaxNode | undefined = undefined; |
| 259 | for (let i = node.children.length - 1; i >= 0; i--) { |
| 260 | if ( |
| 261 | node.children[i].type === "identifier" || |
| 262 | node.children[i].type === "property_identifier" |
| 263 | ) { |
| 264 | identifier = node.children[i]; |
| 265 | break; |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | if (identifier?.text) { |
| 270 | symbols.push({ |
| 271 | filepath, |
| 272 | type: node.type, |
| 273 | name: identifier.text, |
| 274 | range: { |
| 275 | start: { |
| 276 | character: node.startPosition.column, |
| 277 | line: node.startPosition.row, |
| 278 | }, |
| 279 | end: { |
| 280 | character: node.endPosition.column + 1, |
| 281 | line: node.endPosition.row + 1, |
| 282 | }, |
| 283 | }, |
| 284 | content: node.text, |
no test coverage detected