项目作者: smacker

项目描述 :
Golang bindings for tree-sitter https://github.com/tree-sitter/tree-sitter
高级语言: C
项目地址: git://github.com/smacker/go-tree-sitter.git
创建时间: 2018-02-05T18:20:00Z
项目社区:https://github.com/smacker/go-tree-sitter

开源协议:MIT License

下载


go tree-sitter

Build Status
GoDoc

Golang bindings for tree-sitter

Usage

Create a parser with a grammar:

  1. import (
  2. "context"
  3. "fmt"
  4. sitter "github.com/smacker/go-tree-sitter"
  5. "github.com/smacker/go-tree-sitter/javascript"
  6. )
  7. parser := sitter.NewParser()
  8. parser.SetLanguage(javascript.GetLanguage())

Parse some code:

  1. sourceCode := []byte("let a = 1")
  2. tree, _ := parser.ParseCtx(context.Background(), nil, sourceCode)

Inspect the syntax tree:

  1. n := tree.RootNode()
  2. fmt.Println(n) // (program (lexical_declaration (variable_declarator (identifier) (number))))
  3. child := n.NamedChild(0)
  4. fmt.Println(child.Type()) // lexical_declaration
  5. fmt.Println(child.StartByte()) // 0
  6. fmt.Println(child.EndByte()) // 9

Custom grammars

This repository provides grammars for many common languages out of the box.

But if you need support for any other language you can keep it inside your own project or publish it as a separate repository to share with the community.

See explanation on how to create a grammar for go-tree-sitter here.

Known external grammars:

Editing

If your source code changes, you can update the syntax tree. This will take less time than the first parse.

  1. // change 1 -> true
  2. newText := []byte("let a = true")
  3. tree.Edit(sitter.EditInput{
  4. StartIndex: 8,
  5. OldEndIndex: 9,
  6. NewEndIndex: 12,
  7. StartPoint: sitter.Point{
  8. Row: 0,
  9. Column: 8,
  10. },
  11. OldEndPoint: sitter.Point{
  12. Row: 0,
  13. Column: 9,
  14. },
  15. NewEndPoint: sitter.Point{
  16. Row: 0,
  17. Column: 12,
  18. },
  19. })
  20. // check that it changed tree
  21. assert.True(n.HasChanges())
  22. assert.True(n.Child(0).HasChanges())
  23. assert.False(n.Child(0).Child(0).HasChanges()) // left side of the tree didn't change
  24. assert.True(n.Child(0).Child(1).HasChanges())
  25. // generate new tree
  26. newTree := parser.Parse(tree, newText)

Predicates

You can filter AST by using predicate S-expressions.

Similar to Rust or WebAssembly bindings we support filtering on a few common predicates:

  • eq?, not-eq?
  • match?, not-match?

Usage example:

  1. func main() {
  2. // Javascript code
  3. sourceCode := []byte(`
  4. const camelCaseConst = 1;
  5. const SCREAMING_SNAKE_CASE_CONST = 2;
  6. const lower_snake_case_const = 3;`)
  7. // Query with predicates
  8. screamingSnakeCasePattern := `(
  9. (identifier) @constant
  10. (#match? @constant "^[A-Z][A-Z_]+")
  11. )`
  12. // Parse source code
  13. lang := javascript.GetLanguage()
  14. n, _ := sitter.ParseCtx(context.Background(), sourceCode, lang)
  15. // Execute the query
  16. q, _ := sitter.NewQuery([]byte(screamingSnakeCasePattern), lang)
  17. qc := sitter.NewQueryCursor()
  18. qc.Exec(q, n)
  19. // Iterate over query results
  20. for {
  21. m, ok := qc.NextMatch()
  22. if !ok {
  23. break
  24. }
  25. // Apply predicates filtering
  26. m = qc.FilterPredicates(m, sourceCode)
  27. for _, c := range m.Captures {
  28. fmt.Println(c.Node.Content(sourceCode))
  29. }
  30. }
  31. }
  32. // Output of this program:
  33. // SCREAMING_SNAKE_CASE_CONST

Development

Updating a grammar

Check if any updates for vendored files are available:

  1. go run _automation/main.go check-updates

Update vendor files:

  • open _automation/grammars.json
  • modify reference (for tagged grammars) or revision (for grammars from a branch)
  • run go run _automation/main.go update <grammar-name>

It is also possible to update all grammars in one go using

  1. go run _automation/main.go update-all