tree-sitter是一个开源的语法分析库,使用c语言编写,它有很多语言的绑定,比如go,也可以解析很多语言的语法。这里我们用go-tree-sitter和tree-sitter-go这两个库来分析以下go语言的语法。
实例如下
package main
import (
"fmt"
tree_sitter "github.com/tree-sitter/go-tree-sitter"
tree_sitter_go "github.com/tree-sitter/tree-sitter-go/bindings/go"
)
func main() {
code := []byte(`
package main
import (
"abcd"
"fmt"
)
func main() {
fmt.Println("Hello, world!123")
var a,b,c =3,4,5
}
`)
parser := tree_sitter.NewParser()
defer parser.Close()
parser.SetLanguage(tree_sitter.NewLanguage(tree_sitter_go.Language()))
tree := parser.Parse(code, nil)
defer tree.Close()
var walk func(node *tree_sitter.Node)
walk = func(node *tree_sitter.Node) {
childNum := node.ChildCount()
if childNum == 0 {
// fmt.Println(node.Utf8Text(code), node.Kind(), node.GrammarName())
} else {
fmt.Println(node.Utf8Text(code), node.Kind())
var i uint
for i = 0; i < (childNum); i++ {
walk(node.Child(i))
}
}
}
walk(tree.RootNode())
}
结果
package main
import (
"abcd"
"fmt"
)
func main() {
fmt.Println("Hello, world!123")
var a,b,c =3,4,5
}
source_file
package main package_clause
import (
"abcd"
"fmt"
) import_declaration
(
"abcd"
"fmt"
) import_spec_list
"abcd" import_spec
"abcd" interpreted_string_literal
"fmt" import_spec
"fmt" interpreted_string_literal
func main() {
fmt.Println("Hello, world!123")
var a,b,c =3,4,5
} function_declaration
() parameter_list
{
fmt.Println("Hello, world!123")
var a,b,c =3,4,5
} block
fmt.Println("Hello, world!123") expression_statement
fmt.Println("Hello, world!123") call_expression
fmt.Println selector_expression
("Hello, world!123") argument_list
"Hello, world!123" interpreted_string_literal
var a,b,c =3,4,5 var_declaration
a,b,c =3,4,5 var_spec
3,4,5 expression_list