-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.go
78 lines (67 loc) · 1.46 KB
/
lib.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
package treesitter
/*
#include <tree_sitter/api.h>
#include <tree-sitter-go/src/parser.c>
#cgo CFLAGS: -I${SRCDIR}/tree-sitter/lib/include
#cgo LDFLAGS: ${SRCDIR}/tree-sitter/libtree-sitter.a
*/
import "C"
import "unsafe"
type (
TSParser = *C.TSParser
TSTree = *C.TSTree
TSNode = C.TSNode
TSPoint = C.TSPoint
)
type Parser struct {
Parser TSParser
Tree TSTree
}
func ParseGo(src unsafe.Pointer, l int) *Parser {
parser := C.ts_parser_new()
C.ts_parser_set_language(parser, C.tree_sitter_go())
tree := C.ts_parser_parse_string(
parser,
nil,
(*C.char)(src),
C.uint(l),
)
return &Parser{
Parser: parser,
Tree: tree,
}
}
func (p *Parser) Close() {
C.ts_tree_delete(p.Tree)
C.ts_parser_delete(p.Parser)
}
func Walk(node TSNode, fn func(TSNode)) {
fn(node)
count := C.ts_node_child_count(node)
for i := C.uint(0); i < count; i++ {
child := C.ts_node_child(node, i)
Walk(child, fn)
}
}
func NodeType(node TSNode) string {
return C.GoString(C.ts_node_type(node))
}
func NodePosition(node TSNode) (
startRow, startCol int,
endRow, endCol int,
) {
p := C.ts_node_start_point(node)
startRow = int(p.row)
startCol = int(p.column)
p = C.ts_node_end_point(node)
endRow = int(p.row)
endCol = int(p.column)
return
}
func Point(row int, col int) TSPoint {
return TSPoint{C.uint(row), C.uint(col)}
}
func (p *Parser) NodeAt(point TSPoint) TSNode {
root := C.ts_tree_root_node(p.Tree)
return C.ts_node_descendant_for_point_range(root, point, point)
}