Skip to content

Commit 8251e8b

Browse files
Implemented capture group syntax for Tree sitter queries (#3366)
Also did some general clean up of .scm files
1 parent de41090 commit 8251e8b

41 files changed

Lines changed: 760 additions & 786 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/app-web-docs/src/docs/contributing/tree-sitter-query-syntax.md‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,24 +19,21 @@ In addition to the above aspects, you can also use the following inline operator
1919
- `@foo.start` and `@foo.end` to construct the scope using a range between two nodes (inclusive).
2020
- `@foo.startOf` and `@foo.endOf` to refer to the start and end positions of a node. For example, you could use `@foo.start.endOf` to indicate that the scope should start at the end of the node.
2121

22-
## Iteration capture aliases
22+
## Capture groups
2323

24-
Use these aliases when several scopes share an iteration range:
24+
Use `@G_` followed by at least two underscore-separated scope names to give the same capture to multiple scopes. For example, `@G_value_name_namedFunction` expands to `@value`, `@name`, and `@namedFunction`. The `G_` prefix is discarded. Every scope name in the group must be valid.
2525

26-
- `@statementNameValue.iteration` expands to `@statement.iteration`,
27-
`@name.iteration`, and `@value.iteration`.
28-
- `@statementNameValueType.iteration` expands to the same captures plus
29-
`@type.iteration`, for languages and contexts that need type iteration.
30-
31-
Both aliases support `.domain`, `.start.endOf`, `.end.startOf`, and `.end.endOf`. For example, a Java block can share iteration boundaries without repeating the pattern for each scope:
26+
A dot suffix applies to every scope in the group. For example, `@G_value_name_namedFunction.start` expands to `@value.start`, `@name.start`, and `@namedFunction.start`. This also works with relationships and inline operators. A Java block can share iteration boundaries without repeating the capture for each scope:
3227

3328
```scm
3429
(_
35-
"{" @statementNameValueType.iteration.start.endOf
36-
"}" @statementNameValueType.iteration.end.startOf
30+
"{" @G_statement_name_value_type.iteration.start.endOf
31+
"}" @G_statement_name_value_type.iteration.end.startOf
3732
)
3833
```
3934

35+
Predicates refer to the group capture and apply their changes to every expanded capture.
36+
4037
## Query predicate operators
4138

4239
We also support a number of query predicate operators for modifying the scope. See [`queryPredicateOperators.ts`](../../../../../packages/lib-engine/src/languages/TreeSitterQuery/queryPredicateOperators.ts) for a list of available operators.

‎packages/lib-engine/src/languages/TreeSitterQuery/TreeSitterQuery.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type {
66
TextDocument,
77
TreeSitter,
88
} from "@cursorless/lib-common";
9-
import { expandCaptureName, expandCaptures } from "./captureAliases";
9+
import { expandCaptureName, expandCaptures } from "./captureGroup";
1010
import type { ScopeCaptureName } from "./captureNames";
1111
import {
1212
getNormalizedCaptureIndex,

‎packages/lib-engine/src/languages/TreeSitterQuery/captureAliases.test.ts‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,22 @@ import {
66
Position,
77
} from "@cursorless/lib-common";
88
import { TestTreeSitter } from "../../testUtil/TestTreeSitter";
9-
import { expandCaptureName } from "./captureAliases";
9+
import { expandCaptureName } from "./captureGroup";
1010
import { TreeSitterQuery } from "./TreeSitterQuery";
1111
import { treeSitterQueryCache } from "./TreeSitterQueryCache";
1212

1313
for (const alias of [
14-
"statementNameValue.iteration",
15-
"statementNameValueType.iteration",
14+
"G_statement_name_value.iteration",
15+
"G_statement_name_value_type.iteration",
1616
]) {
17-
suite(`${alias} capture alias`, () => {
17+
suite(`${alias} capture group`, () => {
1818
const ide = new FakeIDE();
1919
const treeSitter = new TestTreeSitter();
2020
const names = [
2121
"statement.iteration",
2222
"name.iteration",
2323
"value.iteration",
24-
...(alias === "statementNameValueType.iteration"
24+
...(alias === "G_statement_name_value_type.iteration"
2525
? ["type.iteration"]
2626
: []),
2727
];
@@ -48,7 +48,19 @@ for (const alias of [
4848
);
4949
}
5050
assert.deepEqual(expandCaptureName("interior"), ["interior"]);
51-
assert.deepEqual(expandCaptureName(`${alias}Other`), [`${alias}Other`]);
51+
assert.deepEqual(expandCaptureName("Group_value_name"), [
52+
"Group_value_name",
53+
]);
54+
assert.deepEqual(expandCaptureName("G_value_name_namedFunction.start"), [
55+
"value.start",
56+
"name.start",
57+
"namedFunction.start",
58+
]);
59+
assert.deepEqual(expandCaptureName("G_value_name_namedFunction"), [
60+
"value",
61+
"name",
62+
"namedFunction",
63+
]);
5264
});
5365

5466
for (const withPredicates of [false, true]) {
@@ -87,7 +99,7 @@ for (const alias of [
8799
"statement",
88100
"name",
89101
"value",
90-
...(alias === "statementNameValueType.iteration"
102+
...(alias === "G_statement_name_value_type.iteration"
91103
? ["type" as const]
92104
: []),
93105
] as const) {
@@ -126,6 +138,27 @@ for (const alias of [
126138
}
127139
});
128140

141+
test("expands an arbitrary group", () => {
142+
const { query, document } = createQuery(`
143+
(compound_statement) @G_value_name_namedFunction
144+
`);
145+
const matches = query.matches(
146+
document,
147+
new Position(0, 0),
148+
new Position(0, 15),
149+
);
150+
assert.deepEqual(
151+
matches[0].captures.map((capture) => capture.name),
152+
["value", "name", "namedFunction"],
153+
);
154+
assert.deepEqual(
155+
query
156+
.matchesForScopeTypes(document, ["name"])[0]
157+
.captures.map((capture) => capture.name),
158+
["name"],
159+
);
160+
});
161+
129162
test("shares capture slots with ordinary captures", () => {
130163
const { query, document } = createQuery(`
131164
(compound_statement

‎packages/lib-engine/src/languages/TreeSitterQuery/captureAliases.ts‎

Lines changed: 0 additions & 82 deletions
This file was deleted.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/** Expand shared captures after Tree-sitter has matched the query. */
2+
export function expandCaptureName(name: string): string[] {
3+
if (!captureNameIsGroup(name)) {
4+
return [name];
5+
}
6+
7+
const dotIndex = name.indexOf(".");
8+
const group = dotIndex === -1 ? name.slice(2) : name.slice(2, dotIndex);
9+
const suffix = dotIndex === -1 ? "" : name.slice(dotIndex);
10+
return group.split("_").map((member) => `${member}${suffix}`);
11+
}
12+
13+
/** Preserve predicate changes while giving each expanded capture its own name. */
14+
export function expandCaptures<T extends { name: string }>(
15+
captures: readonly T[],
16+
aliases: ReadonlyMap<string, readonly string[]>,
17+
): readonly T[] {
18+
let result: T[] | undefined;
19+
20+
for (let i = 0; i < captures.length; i++) {
21+
const capture = captures[i];
22+
const names = aliases.get(capture.name);
23+
24+
if (names == null) {
25+
result?.push(capture);
26+
} else {
27+
result ??= captures.slice(0, i);
28+
for (const name of names) {
29+
result.push({ ...capture, name });
30+
}
31+
}
32+
}
33+
34+
return result ?? captures;
35+
}
36+
37+
export function captureNameIsGroup(name: string): boolean {
38+
return name.startsWith("G_");
39+
}

‎packages/lib-engine/src/languages/TreeSitterQuery/captureNames.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import {
22
pseudoScopeTypeTypes,
33
simpleScopeTypeTypes,
44
} from "@cursorless/lib-common";
5-
import { expandCaptureName } from "./captureAliases";
5+
import { captureNameIsGroup, expandCaptureName } from "./captureGroup";
66

77
const scopeCaptureNames = simpleScopeTypeTypes.filter(
88
(s) => !pseudoScopeTypeTypes.has(s),
@@ -98,8 +98,10 @@ function getScopeName(captureName: string): string {
9898
}
9999

100100
export function isCaptureAllowed(captureName: string): boolean {
101-
return expandCaptureName(captureName).some((name) =>
102-
allowedCaptures.has(name),
101+
const names = expandCaptureName(captureName);
102+
return (
103+
(!captureNameIsGroup(captureName) || names.length > 1) &&
104+
names.every((name) => allowedCaptures.has(name))
103105
);
104106
}
105107

‎packages/lib-engine/src/languages/TreeSitterQuery/validateQueryCaptures.test.ts‎

Lines changed: 60 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,41 +4,92 @@ import { validateQueryCaptures } from "./validateQueryCaptures";
44

55
const testCases: { name: string; isOk: boolean; content: string }[] = [
66
{
7-
name: "Statement/name/value iteration alias",
7+
name: "Statement/name/value iteration group",
88
isOk: true,
9-
content: "(compound_statement) @statementNameValue.iteration",
9+
content: "(compound_statement) @G_statement_name_value.iteration",
1010
},
1111
{
1212
name: "Statement/name/value iteration boundaries",
1313
isOk: true,
1414
content:
15-
'(compound_statement "{" @statementNameValue.iteration.start.endOf "}" @statementNameValue.iteration.end.startOf)',
15+
'(compound_statement "{" @G_statement_name_value.iteration.start.endOf "}" @G_statement_name_value.iteration.end.startOf)',
1616
},
1717
{
1818
name: "Statement/name/value iteration domain",
1919
isOk: true,
20-
content: "(compound_statement) @statementNameValue.iteration.domain",
20+
content: "(compound_statement) @G_statement_name_value.iteration.domain",
2121
},
2222
{
2323
name: "Unknown iteration relationship",
2424
isOk: false,
25-
content: "(compound_statement) @statementNameValue.iteration.unknown",
25+
content: "(compound_statement) @G_statement_name_value.iteration.unknown",
2626
},
2727
{
2828
name: "Statement/name/value/type iteration boundaries",
2929
isOk: true,
3030
content:
31-
'(compound_statement "{" @statementNameValueType.iteration.start.endOf "}" @statementNameValueType.iteration.end.startOf)',
31+
'(compound_statement "{" @G_statement_name_value_type.iteration.start.endOf "}" @G_statement_name_value_type.iteration.end.startOf)',
3232
},
3333
{
3434
name: "Unknown type iteration relationship",
3535
isOk: false,
36-
content: "(compound_statement) @statementNameValueType.iteration.unknown",
36+
content:
37+
"(compound_statement) @G_statement_name_value_type.iteration.unknown",
38+
},
39+
{
40+
name: "Old alias",
41+
isOk: false,
42+
content: "(compound_statement) @statementNameValue.iteration",
43+
},
44+
{
45+
name: "Old type alias",
46+
isOk: false,
47+
content: "(compound_statement) @statementNameValueType.iteration",
48+
},
49+
{
50+
name: "Group without suffix",
51+
isOk: true,
52+
content: "(compound_statement) @G_value_name_namedFunction",
53+
},
54+
{
55+
name: "Group with start suffix",
56+
isOk: true,
57+
content: "(compound_statement) @G_value_name_namedFunction.start",
58+
},
59+
{
60+
name: "Single member group",
61+
isOk: false,
62+
content: "(compound_statement) @G_value",
63+
},
64+
{
65+
name: "Single member group with suffix",
66+
isOk: false,
67+
content: "(compound_statement) @G_value.start",
68+
},
69+
{
70+
name: "Unknown first group member",
71+
isOk: false,
72+
content: "(compound_statement) @G_typo_name.iteration",
73+
},
74+
{
75+
name: "Unknown middle group member",
76+
isOk: false,
77+
content: "(compound_statement) @G_statement_typo_value.iteration",
78+
},
79+
{
80+
name: "Unknown last group member",
81+
isOk: false,
82+
content: "(compound_statement) @G_statement_name_typo.iteration",
83+
},
84+
{
85+
name: "Empty group",
86+
isOk: false,
87+
content: "(compound_statement) @G_",
3788
},
3889
{
39-
name: "Alias without iteration",
90+
name: "Empty group member",
4091
isOk: false,
41-
content: "(compound_statement) @statementNameValue",
92+
content: "(compound_statement) @G_statement__value.iteration",
4293
},
4394
{
4495
name: "Scope captures",

0 commit comments

Comments
 (0)