• Stars
    star
    197
  • Rank 197,722 (Top 4 %)
  • Language
    C
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang bindings for tree-sitter https://github.com/tree-sitter/tree-sitter

go tree-sitter

Build Status GoDoc

Golang bindings for tree-sitter

Usage

Create a parser with a 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.Parse(nil, sourceCode)

Inspect the syntax tree:

n := tree.RootNode()

fmt.Println(n) // (program (lexical_declaration (variable_declarator (identifier) (number))))

child := n.NamedChild(0)
fmt.Println(child.Type()) // lexical_declaration
fmt.Println(child.StartByte()) // 0
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:

  • Salesforce grammars - including Apex, SOQL, and SOSL languages.
  • Ruby - Deprecated, grammar is provided by main repo instead

Editing

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

// change 1 -> true
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,
    },
})

// check that it changed tree
assert.True(n.HasChanges())
assert.True(n.Child(0).HasChanges())
assert.False(n.Child(0).Child(0).HasChanges()) // left side of the tree didn't change
assert.True(n.Child(0).Child(1).HasChanges())

// generate new tree
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:

func main() {
	// Javascript code
	sourceCode := []byte(`
		const camelCaseConst = 1;
		const SCREAMING_SNAKE_CASE_CONST = 2;
		const lower_snake_case_const = 3;`)
	// Query with predicates
	screamingSnakeCasePattern := `(
		(identifier) @constant
		(#match? @constant "^[A-Z][A-Z_]+")
	)`

	// Parse source code
	lang := javascript.GetLanguage()
	n, _ := sitter.ParseCtx(context.Background(), sourceCode, lang)
	// Execute the query
	q, _ := sitter.NewQuery([]byte(screamingSnakeCasePattern), lang)
	qc := sitter.NewQueryCursor()
	qc.Exec(q, n)
	// Iterate over query results
	for {
		m, ok := qc.NextMatch()
		if !ok {
			break
		}
		// Apply predicates filtering
		m = qc.FilterPredicates(m, sourceCode)
		for _, c := range m.Captures {
			fmt.Println(c.Node.Content(sourceCode))
		}
	}
}

// Output of this program:
// SCREAMING_SNAKE_CASE_CONST

Development

Updating a grammar

Check if any updates for vendored files are available:

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

go run _automation/main.go update-all

More Repositories

1

opentracing-gorm

OpenTracing instrumentation for GORM.
Go
46
star
2

libgit2.cr

Crystal-lang binding to libgit2 with interface similar to rugged
Crystal
34
star
3

opentracing-go-redis

OpenTracing instrumentation for go-redis.
Go
25
star
4

newrelic-context

Contains different helpers to make life easier with NewRelic and Context.
Go
23
star
5

go-swagger-gen

A tool to parse Golang source files and generate Swagger json.
Go
12
star
6

esbuild-plugin-ts-references

esbuild plugin for typescript references
JavaScript
11
star
7

jasmine-expect-jsx

Adds `toEqualJSX` method to jasmine and jest assertions
JavaScript
9
star
8

non-spa-react-demo

JavaScript
8
star
9

hercules-web

web ui for hercules
Vue
6
star
10

gum

Gum is a library to compute differences between ASTs using gum tree-diff algorithm.
Go
5
star
11

standup-rs

Generate a report for morning standup using GitHub and Google Calendar APIs.
Rust
5
star
12

aspire-budget

TypeScript
5
star
13

gateway-limit

Lua
4
star
14

karma-jasmine-expect-jsx

A Karma plugin. Adds toEqualJSX matcher for the Jasmine BDD JavaScript testing library.
JavaScript
3
star
15

where-we-are

JavaScript
3
star
16

structcsv

Simple deserialization of csv file to slice of structs with struct tags
Go
2
star
17

in-browser-uast

JavaScript
2
star
18

babel-plugin-react-bemed

Bemed react jsx plugin for Babel
JavaScript
1
star
19

bblfsh-benchmark

JavaScript
1
star
20

babel-plugin-bemjson-react

JavaScript
1
star
21

mvsDateRange

jQuery UI Datepicker AngularJS directive that allow to select date range
JavaScript
1
star
22

mvsSoundManager

SoundManager 2 service & directive
JavaScript
1
star
23

travel-map

Generate your interactive travels map
JavaScript
1
star
24

mvsAutocomplete

Yet another jQuery UI Autocomplete directive
JavaScript
1
star
25

mock-autobahnjs

Wrapper around mock-socket to work with autobahnjs
JavaScript
1
star