forked from smacker/go-tree-sitter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
42 lines (38 loc) · 923 Bytes
/
main.go
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
package main
import (
"context"
"fmt"
sitter "github.com/smacker/go-tree-sitter"
"github.com/smacker/go-tree-sitter/javascript"
)
func main() {
// Javascript code
sourceCode := []byte(`
const camelCaseConst = 1;
const SCREAMING_SNAKE_CASE_CONST = 2;
const lower_snake_case_const = 3;`)
// Query with predicates
screamingSnakeCasePattern := `(
(identifier) @constant
(#match? @constant "^[A-Z][A-Z_]+")
)`
// Parse source code
lang := javascript.GetLanguage()
n, _ := sitter.ParseCtx(context.Background(), sourceCode, lang)
// Execute the query
q, _ := sitter.NewQuery([]byte(screamingSnakeCasePattern), lang)
qc := sitter.NewQueryCursor()
qc.Exec(q, n)
// Iterate over query results
for {
m, ok := qc.NextMatch()
if !ok {
break
}
// Apply predicates filtering
m = qc.FilterPredicates(m, sourceCode)
for _, c := range m.Captures {
fmt.Println(c.Node.Content(sourceCode))
}
}
}