go tree-sitter
Golang bindings for tree-sitter
Usage
Create a parser with that grammar:
import (
sitter "github.com/smacker/go-tree-sitter"
"github.com/smacker/go-tree-sitter/javascript"
)
parser := sitter.NewParser()
parser.SetLanguage(javascript.GetLanguage())
Parse some code:
sourceCode = []byte("let a = 1")
tree := parser.ParseString(nil, sourceCode)
Inspect the syntax tree:
n := tree.RootNode()
fmt.Println(n)
child := n.NamedChild(0)
fmt.Println(child.Type())
fmt.Println(child.StartByte())
fmt.Println(child.EndByte())
If your source code changes, you can update the syntax tree. This will take less time than the first parse.
newText := []byte("let a = true")
tree.Edit(sitter.EditInput{
StartIndex: 8,
OldEndIndex: 9,
NewEndIndex: 12,
StartPoint: sitter.Point{
Row: 0,
Column: 8,
},
OldEndPoint: sitter.Point{
Row: 0,
Column: 9,
},
NewEndPoint: sitter.Point{
Row: 0,
Column: 12,
},
})
assert.True(n.HasChanges())
assert.True(n.Child(0).HasChanges())
assert.False(n.Child(0).Child(0).HasChanges())
assert.True(n.Child(0).Child(1).HasChanges())
newTree := parser.ParseString(tree, newText)