| 1 | import Parser from "web-tree-sitter"; |
| 2 | |
| 3 | import { RangeInFileWithContents } from "../../"; |
| 4 | import { getParserForFile } from "../../util/treeSitter"; |
| 5 | |
| 6 | export type AstPath = Parser.SyntaxNode[]; |
| 7 | |
| 8 | export async function getAst( |
| 9 | filepath: string, |
| 10 | fileContents: string, |
| 11 | ): Promise<Parser.Tree | undefined> { |
| 12 | const parser = await getParserForFile(filepath); |
| 13 | |
| 14 | if (!parser) { |
| 15 | return undefined; |
| 16 | } |
| 17 | |
| 18 | try { |
| 19 | const ast = parser.parse(fileContents); |
| 20 | return ast; |
| 21 | } catch (e) { |
| 22 | return undefined; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | export async function getTreePathAtCursor( |
| 27 | ast: Parser.Tree, |
| 28 | cursorIndex: number, |
| 29 | ): Promise<AstPath> { |
| 30 | const path = [ast.rootNode]; |
| 31 | while (path[path.length - 1].childCount > 0) { |
| 32 | let foundChild = false; |
| 33 | for (const child of path[path.length - 1].children) { |
| 34 | if (child.startIndex <= cursorIndex && child.endIndex >= cursorIndex) { |
| 35 | path.push(child); |
| 36 | foundChild = true; |
| 37 | break; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | if (!foundChild) { |
| 42 | break; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | return path; |
| 47 | } |
| 48 | |
| 49 | export async function getScopeAroundRange( |
| 50 | range: RangeInFileWithContents, |
| 51 | ): Promise<RangeInFileWithContents | undefined> { |
| 52 | const ast = await getAst(range.filepath, range.contents); |
| 53 | if (!ast) { |
| 54 | return undefined; |
| 55 | } |
| 56 | |
| 57 | const { start: s, end: e } = range.range; |
| 58 | const lines = range.contents.split("\n"); |
| 59 | const startIndex = |
| 60 | lines.slice(0, s.line).join("\n").length + |
| 61 | (lines[s.line]?.slice(s.character).length ?? 0); |
| 62 | const endIndex = |
| 63 | lines.slice(0, e.line).join("\n").length + |
| 64 | (lines[e.line]?.slice(0, e.character).length ?? 0); |
| 65 | |
| 66 | let node = ast.rootNode; |
| 67 | while (node.childCount > 0) { |
| 68 | let foundChild = false; |
| 69 | for (const child of node.children) { |
| 70 | if (child.startIndex < startIndex && child.endIndex > endIndex) { |
| 71 | node = child; |
| 72 | foundChild = true; |
| 73 | break; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | if (!foundChild) { |
| 78 | break; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | return { |
| 83 | contents: node.text, |
| 84 | filepath: range.filepath, |
| 85 | range: { |
| 86 | start: { |
| 87 | line: node.startPosition.row, |
| 88 | character: node.startPosition.column, |
| 89 | }, |
| 90 | end: { |
| 91 | line: node.endPosition.row, |
| 92 | character: node.endPosition.column, |
| 93 | }, |
| 94 | }, |
| 95 | }; |
| 96 | } |