-
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathTreeSitterQuery.ts
More file actions
190 lines (167 loc) · 5.57 KB
/
TreeSitterQuery.ts
File metadata and controls
190 lines (167 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import type { Position, TextDocument } from "@cursorless/common";
import { type TreeSitter } from "@cursorless/common";
import type * as treeSitter from "web-tree-sitter";
import { ide } from "../../singletons/ide.singleton";
import { getNodeRange } from "./getNodeRange";
import type {
MutableQueryCapture,
MutableQueryMatch,
QueryMatch,
} from "./QueryCapture";
import { checkCaptureStartEnd } from "./checkCaptureStartEnd";
import { isContainedInErrorNode } from "./isContainedInErrorNode";
import { normalizeCaptureName } from "./normalizeCaptureName";
import { parsePredicatesWithErrorHandling } from "./parsePredicatesWithErrorHandling";
import { positionToPoint } from "./positionToPoint";
import {
getStartOfEndOfRange,
rewriteStartOfEndOf,
} from "./rewriteStartOfEndOf";
import { treeSitterQueryCache } from "./treeSitterQueryCache";
/**
* Wrapper around a tree-sitter query that provides a more convenient API, and
* defines our own custom predicate operators
*/
export class TreeSitterQuery {
private shouldCheckCaptures: boolean;
private constructor(
private treeSitter: TreeSitter,
/**
* The raw tree-sitter query as parsed by tree-sitter from the query file
*/
private query: treeSitter.Query,
/**
* The predicates for each pattern in the query. Each element of the outer
* array corresponds to a pattern, and each element of the inner array
* corresponds to a predicate for that pattern.
*/
private patternPredicates: ((match: MutableQueryMatch) => boolean)[][],
) {
this.shouldCheckCaptures = ide().runMode !== "production";
}
static create(
languageId: string,
treeSitter: TreeSitter,
query: treeSitter.Query,
) {
const predicates = parsePredicatesWithErrorHandling(languageId, query);
return new TreeSitterQuery(treeSitter, query, predicates);
}
hasCapture(name: string): boolean {
return this.query.captureNames.some(
(n) => normalizeCaptureName(n) === name,
);
}
matches(
document: TextDocument,
start?: Position,
end?: Position,
): QueryMatch[] {
if (!treeSitterQueryCache.isValid(document, start, end)) {
const matches = this.getAllMatches(document, start, end);
treeSitterQueryCache.update(document, start, end, matches);
}
return treeSitterQueryCache.get();
}
private getAllMatches(
document: TextDocument,
start?: Position,
end?: Position,
): QueryMatch[] {
const matches = this.getTreeMatches(document, start, end);
const results: QueryMatch[] = [];
for (const match of matches) {
const mutableMatch = this.createMutableQueryMatch(document, match);
if (!this.runPredicates(mutableMatch)) {
continue;
}
results.push(this.createQueryMatch(mutableMatch));
}
return results;
}
private getTreeMatches(
document: TextDocument,
start?: Position,
end?: Position,
) {
const { rootNode } = this.treeSitter.getTree(document);
return this.query.matches(rootNode, {
startPosition: start != null ? positionToPoint(start) : undefined,
endPosition: end != null ? positionToPoint(end) : undefined,
});
}
private createMutableQueryMatch(
document: TextDocument,
match: treeSitter.QueryMatch,
): MutableQueryMatch {
return {
patternIdx: match.pattern,
captures: match.captures.map(({ name, node }) => ({
name,
node,
document,
range: getNodeRange(node),
insertionDelimiter: undefined,
allowMultiple: false,
hasError: () => isContainedInErrorNode(node),
})),
};
}
private runPredicates(match: MutableQueryMatch): boolean {
for (const predicate of this.patternPredicates[match.patternIdx]) {
if (!predicate(match)) {
return false;
}
}
return true;
}
private createQueryMatch(match: MutableQueryMatch): QueryMatch {
const result: MutableQueryCapture[] = [];
const map = new Map<
string,
{ acc: MutableQueryCapture; captures: MutableQueryCapture[] }
>();
// Merge the ranges of all captures with the same name into a single
// range and return one capture with that name. We consider captures
// with names `@foo`, `@foo.start`, and `@foo.end` to have the same
// name, for which we'd return a capture with name `foo`.
for (const capture of match.captures) {
const name = normalizeCaptureName(capture.name);
const range = getStartOfEndOfRange(capture);
const existing = map.get(name);
if (existing == null) {
const captures = [capture];
const acc = {
...capture,
name,
range,
hasError: () => captures.some((c) => c.hasError()),
};
result.push(acc);
map.set(name, { acc, captures });
} else {
existing.acc.range = existing.acc.range.union(range);
existing.acc.allowMultiple =
existing.acc.allowMultiple || capture.allowMultiple;
existing.acc.insertionDelimiter =
existing.acc.insertionDelimiter ?? capture.insertionDelimiter;
existing.captures.push(capture);
}
}
if (this.shouldCheckCaptures) {
this.checkCaptures(Array.from(map.values()));
}
return { captures: result };
}
private checkCaptures(matches: { captures: MutableQueryCapture[] }[]) {
for (const match of matches) {
const capturesAreValid = checkCaptureStartEnd(
rewriteStartOfEndOf(match.captures),
ide().messages,
);
if (!capturesAreValid && ide().runMode === "test") {
throw new Error("Invalid captures");
}
}
}
}