Skip to content

Commit

Permalink
docs: add information on using parsers with purego
Browse files Browse the repository at this point in the history
Co-authored-by: Amaan Qureshi <[email protected]>
  • Loading branch information
topi314 and amaanq authored Nov 24, 2024
1 parent 5e5682f commit 2c079a9
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,37 @@ In the example above, to fetch the JavaScript grammar, you can run the following
go get github.com/tree-sitter/tree-sitter-javascript@latest
```

Due to [bugs with `runtime.SetFinalizer` and CGO](https://groups.google.com/g/golang-nuts/c/LIWj6Gl--es), you must always call `Close`
on an object that allocates memory from C. This must be done for the `Parser`, `Tree`, `TreeCursor`, `Query`, `QueryCursor`, and `LookaheadIterator` objects.
Alternatively you can also load grammars at runtime from a shared library via [purego](https://github.com/ebitengine/purego).

The example below shows how to load the JavaScript grammar from a shared library (`libtree-sitter-PARSER_NAME.so`) at runtime on Linux & macOS:

For more information on other platforms, see the [purego documentation](https://github.com/ebitengine/purego#supported-platforms)

```go
package main

import (
tree_sitter "github.com/tree-sitter/go-tree-sitter"
"github.com/ebitengine/purego"
)

func main() {
path := "/path/to/your/parser.so"
lib, err := purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
// handle error
}

var javascriptLanguage func() uintptr
purego.RegisterLibFunc(&javascriptLanguage, lib, "tree_sitter_javascript")

language := tree_sitter.NewLanguage(unsafe.Pointer(javascriptLanguage()))
}
```

> [!NOTE]
> Due to [bugs with `runtime.SetFinalizer` and CGO](https://groups.google.com/g/golang-nuts/c/LIWj6Gl--es), you must always call `Close`
> on an object that allocates memory from C. This must be done for the `Parser`, `Tree`, `TreeCursor`, `Query`, `QueryCursor`, and `LookaheadIterator` objects.
For more information, see the [documentation](https://pkg.go.dev/github.com/tree-sitter/go-tree-sitter).

Expand Down

0 comments on commit 2c079a9

Please sign in to comment.