Skip to content

Commit cad38cd

Browse files
committed
init
0 parents  commit cad38cd

File tree

6 files changed

+1891
-0
lines changed

6 files changed

+1891
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

README.md

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Tree-Sitter Query Examples
2+
3+
```scheme
4+
(program
5+
(import_statement) @import
6+
) @program
7+
```
8+
9+
```scheme
10+
(switch_case
11+
(string
12+
((string_fragment) @case_name)
13+
)
14+
(#eq? @case_name "executeEditorAction")
15+
) @select
16+
```

index.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const Parser = require('tree-sitter');
2+
const { typescript: TypeScript } = require('tree-sitter-typescript');
3+
const fs = require('fs')
4+
5+
function formatCaptures(tree, captures) {
6+
return captures.map((c) => {
7+
const node = c.node;
8+
// delete c.node;
9+
c.text = tree.getText(node);
10+
return c;
11+
});
12+
}
13+
14+
function formatMatches(tree, matches) {
15+
return matches.map(({ pattern, captures }) => ({
16+
pattern,
17+
captures: formatCaptures(tree, captures),
18+
}));
19+
}
20+
21+
const source = fs.readFileSync('./test.ts').toString()
22+
const parser = new Parser();
23+
parser.setLanguage(TypeScript);
24+
const tree = parser.parse(source)
25+
const query = new Parser.Query(TypeScript, `
26+
(switch_case
27+
(string
28+
((string_fragment) @case_name)
29+
)
30+
(#eq? @case_name "executeEditorAction")
31+
) @select
32+
`);
33+
34+
const matches = query.matches(tree.rootNode)
35+
const formattedMatches = formatMatches(tree, matches)
36+
.map(match => match.captures)
37+
38+
console.log(matches, formattedMatches);

0 commit comments

Comments
 (0)