-
Notifications
You must be signed in to change notification settings - Fork 123
/
example_test.go
80 lines (69 loc) · 2.09 KB
/
example_test.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
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
package sitter_test
// Example usage of sitter Go API.
import (
"context"
"fmt"
"log"
"strings"
sitter "github.com/smacker/go-tree-sitter"
"github.com/smacker/go-tree-sitter/golang"
)
// ExampleCursorTraversal recursively prints the tree using TreeCursor.
//
// The cursor provides each node name.
func ExampleCursorTraversal() {
root := mustParseGo("func f(a, b, c int, d, e int)")
c := sitter.NewTreeCursor(root)
defer c.Close()
var visit func(depth int)
visit = func(depth int) {
printNode(c.CurrentNode(), depth, c.CurrentFieldName())
for ok := c.GoToFirstChild(); ok; ok = c.GoToNextSibling() {
visit(depth + 1)
}
}
visit(0)
// Output:
// source_file [0-29]
// function_declaration [0-29]
// func [0-4]
// name: identifier [5-6]
// parameters: parameter_list [6-29]
// ( [6-7]
// parameter_declaration [7-18]
// name: identifier [7-8]
// , [8-9]
// name: identifier [10-11]
// , [11-12]
// name: identifier [13-14]
// type: type_identifier [15-18]
}
// ExampleChildTraversal recursively prints the tree using Node.Child for traversal.
//
// Node names are supplied by the parent.
// Beware: they are current wrong due to https://github.com/tree-sitter/tree-sitter/issues/1642!
func ExampleChildTraversal() {
root := mustParseGo("func f(a, b, c int, d, e int)")
var visit func(n *sitter.Node, name string, depth int)
visit = func(n *sitter.Node, name string, depth int) {
printNode(n, depth, name)
for i := 0; i < int(n.ChildCount()); i++ {
visit(n.Child(i), n.FieldNameForChild(i), depth+1)
}
}
visit(root, "root", 0)
}
func mustParseGo(src string) *sitter.Node {
root, err := sitter.ParseCtx(context.Background(), []byte(src), golang.GetLanguage())
if err != nil {
log.Fatal(err)
}
return root
}
func printNode(n *sitter.Node, depth int, name string) {
prefix := ""
if name != "" {
prefix = name + ": "
}
fmt.Printf("%s%s%s [%d-%d]\n", strings.Repeat(" ", depth), prefix, n.Type(), n.StartByte(), n.EndByte())
}