|
| 1 | +import type { Position, TextDocumentChangeEvent } from "vscode"; |
| 2 | +import { Edit, type Parser, type Point, type Tree } from "web-tree-sitter"; |
| 3 | + |
| 4 | +export class Trees { |
| 5 | + private trees: Map<string, Tree> = new Map(); |
| 6 | + |
| 7 | + get(uri: string): Tree | undefined { |
| 8 | + return this.trees.get(uri); |
| 9 | + } |
| 10 | + |
| 11 | + set(uri: string, tree: Tree): void { |
| 12 | + this.trees.set(uri, tree); |
| 13 | + } |
| 14 | + |
| 15 | + delete(uri: string): void { |
| 16 | + this.trees.delete(uri); |
| 17 | + } |
| 18 | + |
| 19 | + updateTree(parser: Parser, edit: TextDocumentChangeEvent) { |
| 20 | + if (edit.contentChanges.length === 0) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + const uriString = edit.document.uri.toString(); |
| 25 | + const old = this.trees.get(uriString); |
| 26 | + |
| 27 | + if (old == null) { |
| 28 | + throw new Error(`No existing tree for ${uriString}`); |
| 29 | + } |
| 30 | + |
| 31 | + for (const e of edit.contentChanges) { |
| 32 | + const startIndex = e.rangeOffset; |
| 33 | + const oldEndIndex = e.rangeOffset + e.rangeLength; |
| 34 | + const newEndIndex = e.rangeOffset + e.text.length; |
| 35 | + const startPos = edit.document.positionAt(startIndex); |
| 36 | + const oldEndPos = edit.document.positionAt(oldEndIndex); |
| 37 | + const newEndPos = edit.document.positionAt(newEndIndex); |
| 38 | + const startPosition = asPoint(startPos); |
| 39 | + const oldEndPosition = asPoint(oldEndPos); |
| 40 | + const newEndPosition = asPoint(newEndPos); |
| 41 | + const delta = new Edit({ |
| 42 | + startIndex, |
| 43 | + oldEndIndex, |
| 44 | + newEndIndex, |
| 45 | + startPosition, |
| 46 | + oldEndPosition, |
| 47 | + newEndPosition, |
| 48 | + }); |
| 49 | + old.edit(delta); |
| 50 | + } |
| 51 | + |
| 52 | + const tree = parser.parse(edit.document.getText(), old); |
| 53 | + |
| 54 | + if (tree == null) { |
| 55 | + throw Error(`Failed to parse ${uriString}`); |
| 56 | + } |
| 57 | + |
| 58 | + this.trees.set(uriString, tree); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +function asPoint(pos: Position): Point { |
| 63 | + return { row: pos.line, column: pos.character }; |
| 64 | +} |
0 commit comments