| 1 | import Parser from "web-tree-sitter"; |
| 2 | |
| 3 | export function findInAst( |
| 4 | node: Parser.SyntaxNode, |
| 5 | criterion: (node: Parser.SyntaxNode) => boolean, |
| 6 | shouldRecurse: (node: Parser.SyntaxNode) => boolean = () => true, |
| 7 | ): Parser.SyntaxNode | null { |
| 8 | const stack = [node]; |
| 9 | while (stack.length > 0) { |
| 10 | let node = stack.pop()!; |
| 11 | if (criterion(node)) { |
| 12 | return node; |
| 13 | } |
| 14 | |
| 15 | if (shouldRecurse(node)) { |
| 16 | stack.push(...node.children); |
| 17 | } |
| 18 | } |
| 19 | return null; |
| 20 | } |