Skip to content

tree-sitter: run it only as wasm, drop cgo - #307

Merged
vito merged 7 commits into
nocgo-wasm-treesitterfrom
wasm-treesitter-everywhere
Nov 12, 2026
Merged

vito merged 7 commits into
nocgo-wasm-treesitterfrom
wasm-treesitter-everywhere

Conversation

@vito

@vito vito commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Dang's tree-sitter now runs only as WebAssembly. The C runtime and the grammar are compiled to wasm (pkg/dang/tswasm) and run by wazero, so Dang has no cgo. Completion, the LSP, analysis.Complete and REPL highlighting now work in builds without cgo, the Dagger engine's included. The docs site's highlighter is off cgo too (tswasm for Dang, chroma for everything else).

Commits

  1. tswasm: queries, lazy trees and reparsing
    • Query: tree-sitter queries through the shim. The #eq?, #match? and #any-of? predicates (with their not- and any- variants) are applied in Go, the way go-tree-sitter applies them.
    • Inspect: hands a callback a tree whose children are read only when asked for.
    • Document: incremental reparsing. The edit is worked out by diffing the two texts, since the LSP syncs whole documents.
    • Deadlines are now checked by an imported dang_interrupted, called from tree-sitter's progress callbacks. This replaces WithCloseOnContextDone, which made every call 3–15× slower.
    • The compiled module is cached on disk, so first use takes about 2 ms instead of about 50 ms.
  2. dang: complete and highlight through wasm: ports complete_ts.go and highlight_ts.go. Both share one Document, so text typed into a file is reparsed incrementally. One walk in completion used to visit every node; it now only descends into nodes around the cursor.
  3. dang: drop cgo tree-sitter
    • Removes the cgo parse-error path and the root module's go-tree-sitter dependency.
    • test/nocgo now runs go vet with CGO_ENABLED=0 over both modules instead of running the tests a second time.
    • CC=clang stays only for the -race dang binary that the LSP tests drive and for the tree-sitter CLI's corpus tests.
    • Follow-up commits move the docs highlighter off cgo as well (see below).
  4. Fixes from self-review:
    • A compilation-cache entry that fails to load no longer disables tree-sitter.
    • The docs now say that incremental error recovery can differ from a fresh parse. Fuzzing found 1 step in about 13k; native tree-sitter behaves the same way.

Benchmarks

BenchmarkCompletionContextAt types an unfinished call (let zz = foo.bar(baz: 1, qu) mid-file, one letter at a time. It compares cgo (#303) with wasm built with CGO_ENABLED=0, using benchstat with n=6, interleaved in one container on an AMD Ryzen AI MAX+ 395:

source cgo wasm, fresh parse wasm, incremental
1 KB 467 µs 872 µs 475 µs
20 KB 11.4 ms 14.6 ms 9.0 ms
100 KB 47.0 ms 55.3 ms 19.4 ms
400 KB 197 ms 226 ms 91 ms
highlighting cgo wasm
REPL line 35 µs 42 µs
20 KB file 8.2 ms 15.7 ms
100 KB file 38.6 ms 73 ms
  • Parsing in wasm takes about 2× as long as native. Completion still comes out ahead with incremental reparsing, because cgo completion paid a cgo call for every node it walked, while the lazy tree only reads the nodes near the cursor.
  • First use costs about 52 ms cold and about 2 ms with the compilation cache (816 KB under $XDG_CACHE_HOME/dang/wazero). wazero runs in compiler mode (wazevo, the default on amd64/arm64).
  • dang.wasm is 378 KB, built with -Oz. -O2 was not measurably faster.

Docs highlighting

docs/go/highlight.go no longer uses cgo.

  • Dang is highlighted through tswasm, with the same highlight and injection queries. A new tswasm.Query.Matches runs the injection query.
  • Shell, TOML, Go, Ruby and YAML go through chroma, which was already a dependency via booklit. Its token types map onto the tok-* classes syntax.css already themes. Small TOML and shell refinements keep the colors the tree-sitter queries gave: TOML keys are properties; in shell, commands are functions, flags take the number color, variable names are properties, and export/unset are keywords.
  • Comparison: I built the site before and after and diffed every page's HTML. It is byte-identical except two snippets embedded in Dang strings. In a Ruby class << self, << is now an operator and self takes the function color instead of the variable color. A Go fragment that tree-sitter had parsed as an error now lexes properly.
  • Removed: go-tree-sitter and the five grammar modules leave the docs module, and docs/go/danglang goes with its parity tests and sources-digest stamp. build-highlight-assets.sh now pins the grammar versions it builds for the browser playground. The playground's editors still use tree-sitter in the browser, unchanged.

The cutover was checked against cgo before the cgo path was removed: 923/923 parse trees with field names, and 134,705 highlight captures, were identical.

vito added 5 commits November 12, 2026 20:37
Give the wasm runtime what completion and highlighting need, so they can
leave cgo too:

- Query compiles a tree-sitter query (ts_query_new through the shim) and
  runs it over a parse, applying #eq?, #match? and #any-of? with their not-
  and any- variants in Go, the way go-tree-sitter does; other predicates and
  directives (#offset!, #trim!, #set!) are the caller's, as they are there.
- Inspect hands a callback a tree whose children are read from the instance
  as it asks for them, so a caller that looks at the nodes around one point
  pays for those, not for decoding the whole tree. Nodes now carry their
  field name and parent; Children is a method.
- Document keeps an instance and its last tree, and reparses each new version
  incrementally (ts_tree_edit, then ts_parser_parse with the old tree), the
  edit worked out by comparing the versions, since the LSP syncs whole texts.

Deadlines no longer use wazero's WithCloseOnContextDone, which made every call
3-15x slower: the shim polls an imported dang_interrupted between parse and
query steps (tree-sitter's progress callbacks), which reports whether the
call's context is done. An interrupted call leaves its instance usable.

The compiled module is cached under the user cache directory
(wazero.NewCompilationCacheWithDir), so first use costs ~2ms instead of
~50ms after the first process. Grammar names are read once per process.

The parity test now compares field names too, and the highlight query's
captures over every input (134,731 captures, identical); new tests check
lazily read trees and incremental reparses against fresh parses.

Signed-off-by: Alex Suraci <[email protected]>
Completion (and so the LSP, the REPL and analysis.Complete) and REPL
highlighting ran on cgo tree-sitter, so builds without cgo, the Dagger
engine's included, had neither. They now run on pkg/dang/tswasm in every
build but GOOS=js and -tags dang_nowasm, which keep the no-op fallbacks.

Completion classifies the cursor over a lazily read tree (tswasm.Inspect),
so it reads only the nodes around the cursor; the one walk that visited
every node (an arg_values ending just before the cursor) now skips subtrees
that can't hold one. Both completion and highlighting parse through one
shared tswasm.Document, so a source typed into is reparsed incrementally;
when it's busy, a pooled instance parses afresh. Highlighting runs the
embedded highlights.scm as a tswasm.Query.

BenchmarkCompletionContextAt (an unfinished call typed mid-file, one letter
at a time) against cgo at the parent commit, n=6 in one container:

  size    cgo      wasm fresh  wasm incremental
  1KB     467µs    872µs       475µs
  20KB    11.4ms   14.6ms      9.0ms
  100KB   47.0ms   55.3ms      19.4ms
  400KB   197ms    226ms       91ms

Highlighting a REPL line takes 42µs (35µs with cgo); whole files take about
twice as long as with cgo, as parsing does.

The completion and highlighting tests run in both builds now; the analysis
completion tests no longer skip without cgo.

Signed-off-by: Alex Suraci <[email protected]>
Error recovery, completion and highlighting all run on tswasm now, so Dang
has no cgo left: remove the cgo parse-error path, and with it Dang's
go-tree-sitter dependency. Every build parses the same way, but GOOS=js and
-tags dang_nowasm, which still name the token the parser failed at.

The docs site's highlighter is the one cgo user left, so the cgo grammar
binding moves to the docs module, as docs/go/danglang, beside the grammars
it highlights with; ./hack/generate stamps its sources digest there. Its
parity tests come along, holding the cgo and wasm runtimes to the same trees
and highlights, so the docs and the REPL color code alike. build.sh takes
the C runtime from the docs module's go-tree-sitter, the same version.

test/nocgo no longer reruns the tests, which would cover the same code twice:
it vets the whole module with CGO_ENABLED=0, so a dependency that needs cgo
can't slip into the engine's build. The toolchain keeps CC=clang for the
docs build and the race-enabled dang binary the LSP tests drive.

Signed-off-by: Alex Suraci <[email protected]>
A compilation cache entry that can't be read (corrupt, say) or written made
CompileModule fail, and loadEngine keeps its error for the process, so one
bad file under the user cache directory switched off tree-sitter in every
process until deleted by hand. The cache only saves time: when compiling
with it fails, compile without it, and clear the cache directory so the
next process caches afresh.

Signed-off-by: Alex Suraci <[email protected]>
Around a syntax error, tree-sitter's incremental reparse can recover into a
different tree than a fresh parse of the same text (about one step in
13,000 when fuzzing edits over the test sources; native tree-sitter does
the same). Say so on Document and on the document completion and
highlighting share, and narrow what the incremental test claims.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito added this pull request to stack #304 November 12, 2026 20:53
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

vito added 2 commits November 12, 2026 21:09
Query.Matches returns a query's matches, each with all its captures, as
ts_query_cursor_next_match gives them (through a new dang_matches_next), with
text predicates applied as for Captures. The docs highlighter needs it for
the Dang injection query, which pairs each template's language tag with its
content.

build.sh now names the go-tree-sitter version it takes the C runtime from,
rather than reading it from a module's requirements: no module requires
go-tree-sitter once the docs highlight without cgo.

Signed-off-by: Alex Suraci <[email protected]>
The docs highlighter was the last cgo tree-sitter user. Dang now
highlights through tswasm, with the same highlight and injection queries as
before, and shell, TOML, Go, Ruby and YAML through chroma (already a
dependency, via booklit). Those only ever appear as static snippets, so a
lexer is enough. Chroma's token types map onto the tok-* classes syntax.css
already themes. Two small refinements for TOML and shell keep the colors the
tree-sitter queries gave: TOML keys are properties; in shell, commands
(after any NAME=value) are functions, flags use the number color, variable
names are properties, and a substitution inside a string stays
string-colored except for its command.

Built before and after, every page's HTML is byte-identical except two
snippets injected into Dang strings: a Ruby `class << self`, where `<<` is
now an operator and `self` a function, and a Go fragment that tree-sitter
had parsed as an error and chroma now lexes properly.

With that, the docs module drops go-tree-sitter and the five grammar
modules, and docs/go/danglang (the cgo binding) goes, along with its
cgo<->wasm parity tests and the sources-digest stamp ./hack/generate wrote
for it. build-highlight-assets.sh now names the grammar versions it builds
for the browser playground, since it can no longer read them from the docs
module.

test/nocgo vets the docs module too. CC=clang stays in the toolchain: the
race-enabled dang binary the LSP tests drive and the tree-sitter CLI's corpus
tests still compile C. Neither Dang nor the docs build does.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito merged commit 1313b09 into main Nov 12, 2026
11 checks passed
vito added a commit that referenced this pull request Nov 13, 2026
Hints for common mistakes get a section, with two errors as printed.
Faster Dagger modules, failed declarations reported once and the GraphQL
object list hint join the smaller changes. Go embedders learn that Dang no
longer needs cgo, and about LoadTreeSitter. The lede and sources cover
them, verified at 2918064.

Signed-off-by: Alex Suraci <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant