Repository navigation
Expand file tree
/
Copy pathTreeSitterQuery.ts
More file actions
314 lines (280 loc) · 8.63 KB
/
Copy pathTreeSitterQuery.ts
File metadata and controls
314 lines (280 loc) · 8.63 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import type {
Mutable,
Position,
TextDocument,
TreeSitter,
} from "@cursorless/common";
import type * as treeSitter from "web-tree-sitter";
import { ide } from "../../singletons/ide.singleton";
import {
getNormalizedCaptureIndex,
getNormalizedCaptureName,
type ScopeCaptureName,
} from "./captureNames";
import { checkCaptureStartEnd } from "./checkCaptureStartEnd";
import { getNodeRange } from "./getNodeRange";
import { isContainedInErrorNode } from "./isContainedInErrorNode";
import { parsePredicatesWithErrorHandling } from "./parsePredicatesWithErrorHandling";
import { positionToPoint } from "./positionToPoint";
import type {
MutableQueryCapture,
PatternPredicate,
QueryCapture,
QueryMatch,
} from "./QueryCapture";
import {
createTestQueryCapture,
getStartOfEndOfNodeRange,
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: PatternPredicate[][],
) {
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) => getNormalizedCaptureName(n) === name,
);
}
matches(
document: TextDocument,
start: Position,
end: Position,
): QueryMatch[] {
return this.getMatches(document, start, end, undefined);
}
matchesForScopeTypes(
document: TextDocument,
scopeTypes: readonly ScopeCaptureName[],
): QueryMatch[] {
const captureNameFilter = new Set(
scopeTypes.map(getNormalizedCaptureIndex),
);
return this.getMatches(document, undefined, undefined, captureNameFilter);
}
private getMatches(
document: TextDocument,
start: Position | undefined,
end: Position | undefined,
captureNameFilter: Set<number> | undefined,
): QueryMatch[] {
if (
!treeSitterQueryCache.isValid(document, start, end, captureNameFilter)
) {
const matches = this.calculateMatches(
document,
start,
end,
captureNameFilter,
);
treeSitterQueryCache.update(
document,
start,
end,
captureNameFilter,
matches,
);
}
return treeSitterQueryCache.get();
}
private calculateMatches(
document: TextDocument,
start: Position | undefined,
end: Position | undefined,
captureNameFilter: Set<number> | undefined,
): QueryMatch[] {
const matches = this.getTreeMatches(document, start, end);
const results: QueryMatch[] = [];
for (const match of matches) {
if (
captureNameFilter != null &&
!match.captures.some((capture) =>
captureNameFilter.has(getNormalizedCaptureIndex(capture.name)),
)
) {
continue;
}
const patternPredicates = this.patternPredicates[match.patternIndex];
// The split path here is to avoid creating query captures if there are no
// predicates, Solely for performance.
const captures =
patternPredicates.length > 0
? this.createQueryCapturesWithPredicates(
document,
match,
patternPredicates,
captureNameFilter,
)
: this.createQueryCapturesWithoutPredicates(match, captureNameFilter);
if (captures.length > 0) {
results.push({ captures });
}
}
return results;
}
private getTreeMatches(
document: TextDocument,
start: Position | undefined,
end: Position | undefined,
) {
const { rootNode } = this.treeSitter.getTree(document);
return this.query.matches(rootNode, {
startPosition: start != null ? positionToPoint(start) : undefined,
endPosition: end != null ? positionToPoint(end) : undefined,
});
}
private createQueryCapturesWithPredicates(
document: TextDocument,
match: treeSitter.QueryMatch,
predicates: PatternPredicate[],
captureNameFilter: Set<number> | undefined,
): QueryCapture[] {
const captures: MutableQueryCapture[] = [];
for (const capture of match.captures) {
captures.push({
name: capture.name,
node: capture.node,
document,
range: getNodeRange(capture.node),
allowMultiple: false,
insertionDelimiter: undefined,
hasError: () => isContainedInErrorNode(capture.node),
});
}
for (const predicate of predicates) {
if (!predicate({ captures })) {
return [];
}
}
const result: QueryCapture[] = [];
const map = new Map<
string,
{ acc: Mutable<QueryCapture>; captures: QueryCapture[] }
>();
// 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 captures) {
if (
captureNameFilter != null &&
!captureNameFilter.has(getNormalizedCaptureIndex(capture.name))
) {
continue;
}
const name = getNormalizedCaptureName(capture.name);
const range = getStartOfEndOfRange(capture);
const existing = map.get(name);
if (existing == null) {
const captures = [capture];
const acc: QueryCapture = {
name,
range,
allowMultiple: capture.allowMultiple,
insertionDelimiter: capture.insertionDelimiter,
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) {
checkCaptures(Array.from(map.values()));
}
return result;
}
private createQueryCapturesWithoutPredicates(
match: treeSitter.QueryMatch,
captureNameFilter: Set<number> | undefined,
): QueryCapture[] {
const result: QueryCapture[] = [];
const map = new Map<
string,
{
acc: Mutable<QueryCapture>;
captures: treeSitter.QueryCapture[];
}
>();
for (const capture of match.captures) {
if (
captureNameFilter != null &&
!captureNameFilter.has(getNormalizedCaptureIndex(capture.name))
) {
continue;
}
const name = getNormalizedCaptureName(capture.name);
const range = getStartOfEndOfNodeRange(capture.name, capture.node);
const existing = map.get(name);
if (existing == null) {
const captures = [capture];
const acc: QueryCapture = {
name,
range,
allowMultiple: false,
insertionDelimiter: undefined,
hasError: () => captures.some((c) => isContainedInErrorNode(c.node)),
};
result.push(acc);
map.set(name, { acc, captures });
} else {
existing.acc.range = existing.acc.range.union(range);
existing.captures.push(capture);
}
}
if (this.shouldCheckCaptures) {
checkCaptures(
Array.from(map.values(), (v) => ({
captures: v.captures.map((c) =>
createTestQueryCapture(c.name, getNodeRange(c.node)),
),
})),
);
}
return result;
}
}
function checkCaptures(matches: { captures: QueryCapture[] }[]) {
for (const match of matches) {
const capturesAreValid = checkCaptureStartEnd(
rewriteStartOfEndOf(match.captures),
ide().messages,
);
if (!capturesAreValid && ide().runMode === "test") {
throw new Error("Invalid captures");
}
}
}