Skip to content

Commit 71f7f39

Browse files
Refactoring
1 parent b9a54c1 commit 71f7f39

5 files changed

Lines changed: 194 additions & 167 deletions

File tree

src/Trees.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
}

src/errors.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ export class UnsupportedLanguageError extends Error {
77
}
88
}
99

10-
export class LanguageStillLoadingError extends Error {
10+
export class LanguageFailedToLoad extends Error {
1111
constructor(language: string) {
12-
super(`Language '${language}' is still loading; please wait and try again`);
13-
this.name = "LanguageStillLoadingError";
12+
super(`Language '${language}' failed to load`);
13+
this.name = "LanguageFailedToLoad";
1414
}
1515
}
1616

0 commit comments

Comments
 (0)