Skip to content

Add a Rust port of vscode-textmate under rust/ - #315

Merged
Alexandru Dima (alexdima) merged 16 commits into
mainfrom
agents/rust-port
Nov 29, 2026
Merged

Alexandru Dima (alexdima) merged 16 commits into
mainfrom
agents/rust-port

Conversation

@alexdima

@alexdima Alexandru Dima (alexdima) commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Fixes #314

This adds a Rust port of vscode-textmate, the crate vscode-textmate in rust/. It gives the same tokens as vscode-textmate on every file it was compared on, and it tokenizes 3.05× faster than vscode-textmate built from main on the bench's 9 files and 3.94× faster than the 9.3.2 release on TypeScript's checker.ts and SQLite's sqlite3.c. It also makes the npm package ready for 9.4.0, which ships that port's WebAssembly build as vscode-textmate/wasm; npm publish builds it from a clean clone (see Publishing 9.4.0).

It builds to WebAssembly (rust/wasm), with vscode-textmate's JavaScript API, published as vscode-textmate/wasm, so that VS Code can use it in place of vscode-textmate and vscode-oniguruma (microsoft/vscode#351000 tries it out): in Node, that build gives the same tokens and is 2.11× faster than vscode-textmate 9.3.2 with vscode-oniguruma 1.7.0 on the 9 files and 2.76× faster on checker.ts and sqlite3.c. See Using it from VS Code.

The change is +14,442 lines in 85 files: 13,932 in rust/ and 510 outside it, for the package. Oniguruma's source is not copied into it: rust/vendor/oniguruma is a git submodule of kkos/oniguruma at v6.9.8 (08d36110), the commit vscode-oniguruma's deps/oniguruma points at too, and rust/build.rs applies the eight patch files in rust/vendor/patches to a copy of it and compiles it. The lines in rust/ are about 7,900 of Rust in rust/src (the port 6,138, its check binaries 1,756), 645 of tests, 1,065 of patches, 322 in build.rs, about 2,340 of docs, check data and manifests (rust/oracle-js, rust/probe, rust/examples), and 1,666 in rust/wasm: 624 of Rust (src/main.rs, build.rs), 976 of JavaScript and types (the API, its types and its checks) and 66 of manifests (Cargo.toml, Cargo.lock, .gitignore). Outside rust/, the 510 lines in 10 files are .gitmodules and the package's: package.json and its lock, the scripts scripts/build-wasm.js and scripts/wasm-smoke.js, CHANGELOG.md, ThirdPartyNotices.txt, README.md, .npmignore and tsconfig.json.

Results

Measured on an arm64 Mac with Rust 1.100.0 and Node 24.

  • Same tokens: 0 differences on all 238 files compared. Against vscode-textmate built from main: the bench's 9 files in 7 languages (98,998 lines, 481,930 tokens) and VS Code's 109 colorize fixtures. Against the 9.3.2 release: the 9 files in slightly different versions, the 109 fixtures, checker.ts and sqlite3.c (388,338 lines, 1,664,289 tokens). Compared: the binary tokens of tokenize_line2, the scopes of tokenize_line, states rebuilt with diff_state_stacks_ref_eq and apply_state_stack_diff, and tokenizing on from those states; against main, also the font ranges under two themes with font rules.
  • Faster: on the 9 files against main, 2,197 vs 6,690 ms warm (3.05×) and 2,377 vs 9,217 ms cold (3.88×); on checker.ts and sqlite3.c against 9.3.2, 5,844 vs 23,041 ms warm (3.94×) and 5,875 vs 24,286 ms cold (4.13×). Cold is the first pass after the grammar loads and warm the best of the later passes. The JS cold pass also copies each line's tokens into a new array (Array.from in rust/oracle-js/dump.js), which the port's cold passes don't, so the cold ratios count that copy against JS; the warm passes do the same work on both sides. The port's times are means of 3 runs, and the table below gives each file from one run.
  • Tests: all 95 of this repository's test cases pass (test-cases/: first-mate 64, suite1 22, whileTests 9), and the 30 tests of cargo test pass on Rust 1.85.0 and 1.100.0. cargo fmt --check and cargo clippy --release --all-targets report nothing.
  • Regex engine: C Oniguruma 6.9.8, the version vscode-oniguruma 1.7.0 (which VS Code ships) compiles to WebAssembly. 82 engine probes, 103 searches with invalid patterns and 9 tokenizations of a grammar with invalid patterns give the same output as vscode-oniguruma, and all 23,171 regexes the 84 built-in grammars can produce compile.
  • One finding: the skipped test "Shadowed rules are resolved correctly" expects outer, but vscode-textmate returns inner; the ported test asserts inner.
file language lines tokens Rust warm ms JS warm ms faster
textModel.ts TypeScript 2,748 18,084 42.9 195.9 4.57×
agentService.ts TypeScript 17,185 117,495 330.9 1,579.1 4.77×
react-dom.development.js JavaScript 26,263 95,304 297.1 1,376.1 4.63×
koffi's base.cc C++ 11,199 52,235 497.8 1,213.9 2.44×
napi-inl.h C++ 7,251 32,666 294.0 732.9 2.49×
a 1 MB stylesheet CSS 29,666 135,730 678.4 1,338.9 1.97×
axios's CHANGELOG.md Markdown 1,935 11,679 31.9 170.7 5.35×
bignumber.js's API.html HTML 2,250 16,136 15.2 53.1 3.49×
example.py Python 501 2,601 7.0 29.2 4.17×
the 9 files 98,998 481,930 2,195.2 6,689.8 3.05×
checker.ts TypeScript 146,621 796,508 3,503.1 14,444.4 4.12×
sqlite3.c C 241,717 867,781 2,319.2 8,596.7 3.71×
checker.ts and sqlite3.c 388,338 1,664,289 5,822.3 23,041.1 3.96×

One run of the bench binary with --reps 3, next to vscode-textmate with vscode-oniguruma 1.7.0 timed the same way: built from main for the 9 files, and the 9.3.2 release for checker.ts and sqlite3.c. On the 9 files, the two JS builds take about the same time (6,690 and 6,701 ms warm, on slightly different versions of the files). rust/README.md has the table of the 9 files against 9.3.2.

Using it from VS Code: the WebAssembly build

rust/wasm compiles the port and the patched Oniguruma with Emscripten, the toolchain vscode-oniguruma uses, into one .wasm file of 743 KB, and rust/wasm/js/api.js puts vscode-textmate's JavaScript API on it; the package ships them as vscode-textmate/wasm. It replaces both packages: VS Code would load this module instead of vscode-textmate and vscode-oniguruma.

Measured in Node 24, in the same process as vscode-textmate 9.3.2 with vscode-oniguruma 1.7.0, the versions VS Code ships (node js/bench.js; warm is the best of 5 passes for the 9 files and of 3 for the two big ones):

vscode-textmate + vscode-oniguruma WebAssembly build faster
the 9 files, warm 6,787 ms 3,217 ms 2.11×
the 9 files, cold 8,564 ms 3,407 ms 2.51×
checker.ts, warm 14,638 ms 5,197 ms 2.82×
sqlite3.c, warm 8,674 ms 3,262 ms 2.66×
checker.ts and sqlite3.c, warm 23,312 ms 8,458 ms 2.76×
loading the module 20.8 ms 3.1 ms
size 527 KB (onig.wasm 456 KB) 767 KB (the .wasm 743 KB, main.js 24 KB)
  • Same tokens: node js/oracle.js finds 0 differences on the 9 files against vscode-textmate built from main, fonts under the two themes included, and on checker.ts and sqlite3.c against 9.3.2. It compares the same things as the native oracle: the binary tokens of tokenizeLine2, the scopes of tokenizeLine, a diffStateStacksRefEq and applyStateStackDiff round trip on every line, and tokenizing on from the rebuilt states. It exits with 2 when its arguments select no corpus, and, like oracle, it reports whether a 1 ms time limit stops a long line early without failing on it, since that depends on the machine's speed. node js/bench.js also compares every line's tokens from both sides after the timed passes, and finds no difference.
  • Slower than native: about 1.46× (3,217 against 2,197 ms on the 9 files). It gains least on C, C++ and CSS (1.5× to 1.6×), whose time goes to Oniguruma, which vscode-oniguruma already runs as WebAssembly, and most on TypeScript, JavaScript and Markdown (3.2× to 4×).
const { loadWASM } = require('vscode-textmate/wasm');
const tm = await loadWASM(fs.readFileSync(require.resolve('vscode-textmate/release/wasm/vscode-textmate.wasm')));
const registry = new tm.Registry({
	loadGrammar: async scopeName => tm.parseRawGrammar(content, filePath),
	getInjections: scopeName => injectedScopeNames,
});
registry.setTheme(theme);
const grammar = await registry.loadGrammarWithConfiguration('source.ts', languageId, { embeddedLanguages, tokenTypes, balancedBracketSelectors, unbalancedBracketSelectors });
const { tokens, ruleStack, stoppedEarly, fonts } = grammar.tokenizeLine2(line, tm.INITIAL, 500);

loadWASM takes the bytes of the .wasm (an ArrayBuffer, a typed array, or anything with arrayBuffer(), such as a Response), or { data, print, printErr }, much as vscode-oniguruma's loadWASM does, and fetches nothing itself; each call makes a new instance of the module. It returns { Registry, INITIAL, parseRawGrammar, diffStateStacksRefEq, applyStateStackDiff }, typed with vscode-textmate's own types. What differs from vscode-textmate: the Registry ignores onigLib, since Oniguruma is in the module, and has no addGrammar; states live in the module and are freed by a FinalizationRegistry once JavaScript drops them, and grammars and registries also have dispose() to free theirs at once; the raw grammars of parseRawGrammar can only be passed back to the module, and each loadGrammar returns a new grammar object; the diffs of diffStateStacksRefEq are plain objects of vscode-textmate's shape, so another instance can apply them, but, as with vscode-textmate, they hold rule ids and token attributes, so the instance that applies one must have loaded the same grammar and theme; and a Rust panic aborts the module, after which every call throws.

To use it in VS Code, the tokenization worker and the renderer would load vscode-textmate/wasm and pass loadWASM the bytes of vscode-textmate/release/wasm/vscode-textmate.wasm, as they pass vscode-oniguruma's onig.wasm today, and build their Registry, diffStateStacksRefEq and applyStateStackDiff from what it returns; tokenizeLine2(line, state, 500) stays as it is. A diff made by the worker's instance applies in the renderer's: of two instances in Node with the same grammar, the second rebuilds the first's states from its diffs. microsoft/vscode#351000 tries it out behind a setting.

Publishing 9.4.0

npm publish from a clean clone builds the whole package, the WebAssembly module included: prepublishOnly is now tsc && webpack --progress && npm run api-extractor && npm run build-wasm.

  • npm run build-wasm (scripts/build-wasm.js):
    1. Runs git submodule update --init rust/vendor/oniguruma when the Oniguruma sources are missing or the submodule is checked out, and stops with that command in its message when they are missing outside a git clone or git can't fetch them.
    2. Checks rustc, cargo, emcc and the wasm32-unknown-emscripten target, and stops with what to install or run when one is missing.
    3. Prints the versions it builds with. It was built with Rust 1.100.0 and Emscripten 7.0.1 (rust/README.md documents them); it doesn't enforce them, and the native crate also builds and passes its tests on Rust 1.85.0.
    4. Runs cargo build --release --target wasm32-unknown-emscripten in rust/wasm, with --remap-path-prefix for the checkout and Cargo's home, so that the panic messages in the module don't hold the build machine's paths.
    5. Writes release/wasm/: main.js, a UMD module like release/main.js that holds the Emscripten glue and the API (rust/wasm/js/api.js) and exports loadWASM; main.d.ts, its types (rust/wasm/js/main.d.ts); and vscode-textmate.wasm.
  • package.json: the version is 9.4.0; exports has . (as before), ./wasm, ./release/*, ./types/* and ./package.json, so require.resolve('vscode-textmate/release/wasm/vscode-textmate.wasm') finds the bytes to pass; typesVersions maps vscode-textmate/wasm to its types for TypeScript's node resolution; files adds release/wasm/main.d.ts, release/wasm/vscode-textmate.wasm, CHANGELOG.md and ThirdPartyNotices.txt. The package has 10 files, 319.3 kB packed and 898.2 kB unpacked.
  • npm run wasm-smoke [dir] (scripts/wasm-smoke.js) resolves vscode-textmate and vscode-textmate/wasm from dir (this repository by default) and runs the test cases of first-mate/tests.json, suite1/tests.json and suite1/whileTests.json with both, under the Dark+ theme, comparing the tokens, the binary tokens, the state stacks, the diffs and the color maps.
  • Docs and notices: a 9.4.0 entry in CHANGELOG.md, a section on vscode-textmate/wasm in README.md, and Oniguruma (BSD-2-Clause) and rustc-hash (MIT) in ThirdPartyNotices.txt, which the package now ships (.npmignore excluded it).
  • tsconfig.json compiles only src/ ("include": ["src"]). At the previous head, tsc wrote its output under out/src/ instead of out/, so prepublishOnly stopped at webpack with Can't resolve './out/main.js'.
  • Fixes in the port and the module:
    • A diff from or to INITIAL counts INITIAL as vscode-textmate's depth-1 frame, so diffStateStacksRefEq and applyStateStackDiff give vscode-textmate's diffs and states for the first line, and identical stacks give an empty diff.
    • Registry.setTheme reports a theme whose colors are missing from the color map as an error ("Missing color in color map - …", as vscode-textmate throws) and keeps the previous theme, instead of aborting the module; the color map keeps vscode-textmate's null at id 0, and getColorMap returns it as vscode-textmate does.
    • Frames of the diffs omit an absent enterPos and anchorPos, as vscode-textmate's do, and applyStateStackDiff throws on a diff that isn't valid JSON instead of returning INITIAL.

Tests

On an arm64 Mac with Rust 1.100.0, Emscripten 7.0.1 and Node 24:

  • cargo test --release in rust/: 30 passed, on Rust 1.100.0 and on Rust 1.85.0.
  • cargo run --release --bin upstream_tests -- ../test-cases: 95 passed.
  • cargo run --release --bin oracle: 0 differences on the 9 corpora (98,998 lines, 481,930 tokens), fonts included.
  • node js/oracle.js in rust/wasm: 0 differences, on the same corpora (run before build-wasm remapped the paths in the module's panic messages).
  • cargo fmt --check and cargo clippy --release --all-targets: clean.
  • npm test: 267 passed, 1 skipped, as before.
  • npm run wasm-smoke: 95 tests, 166 lines, 703 tokens, the same as vscode-textmate's.
  • Two instances of the module in one Node process, with the same grammar: the second applies the first's diffs line by line and gets the states it tokenizes itself.

From a clean clone of this change (shown under After; only rust/README.md changed since): npm ci; npm run build-wasm, which ran git submodule update --init rust/vendor/oniguruma, couldn't fetch it on that machine and stopped with its message, so the submodule's files at 08d36110 were copied in from a local copy; npm run prepublishOnly, which exits 0; npm pack, which gives vscode-textmate-9.4.0.tgz (10 files, 319.3 kB). In a new project with that tarball and vscode-oniguruma 1.7.0, the exports resolve, node scripts/wasm-smoke.js <project> passes (95 tests, 166 lines, 703 tokens) and the README's example prints the scopes. The .wasm has no path of the build machine, and building in two different folders gives the same bytes. At the previous head, 997b465 (shown under Before), npm run prepublishOnly stops at webpack with Can't resolve './out/main.js'.

Where the speed comes from

Most of the time goes to Oniguruma's search, so most of the gain comes from eight patches (0003 to 0010) that the build applies to Oniguruma and that make it faster without changing what it finds. From 0004 on, each change below was measured in runs alternated with and without it, and every change was checked like the port itself: 0 differences against vscode-textmate, all test cases passing, the engine probes unchanged. Details are at the end.

change warm, 9 files (ms) warm, checker.ts and sqlite3.c (ms)
0003: the regset search reuses its memory 4,720 → 4,059 (−14%)
0004: a UTF-8 character's length is looked up inline 4,063 → 3,932 (−3.2%)
0005: forward_search results are reused within a line 3,930 → 3,517 (−10.5%)
scanners share compiled regexes 3,517 → 3,457 (−1.7%); cold about 5,000 → 3,640 (−27%)
0006: a regex is set up only when the search tries it 3,460 → 3,184 (−8.0%) 10,839 → 9,672 (−10.8%)
fewer allocations per token 3,178.5 → 3,091.1 (−2.8%) 9,649 → 9,371 (−2.9%)
0007: the first byte is tested before a regex is tried 3,090 → 2,752 (−11.0%) 9,360 → 7,473 (−20.2%)
0008: the first-byte test also covers anchored regexes 2,768 → 2,521 (−8.9%) 7,450 → 6,492 (−12.9%)
0009: alternatives whose first byte is absent are skipped 2,524 → 2,332 (−7.6%) 6,490 → 6,304 (−2.9%)
0010: the first-byte map search steps over UTF-8 bytes 2,330 → 2,197 (−5.7%) 6,278 → 5,844 (−6.9%)

The release profile also uses LTO and one codegen unit. Before the patches, the shared regexes and the allocation trims (3d077ae), the port was 1.41× faster than 9.3.2 warm and 1.48× cold.

What's in it

  • The port (rust/src): a file-by-file port of src/ that keeps the TypeScript's types, functions and order, so the two read side by side. rust/README.md maps each module to its TypeScript files, and rust/PORT-SPEC.md records the details. It follows main: 9.3.2 plus Empty end match immediately #252, Creating TokenHandler class #261 and fix: mirror TextMate2.0 backreference escaping #276.
  • The API is vscode-textmate's, in snake_case: Registry, Grammar (tokenize_line, tokenize_line2), StateStack, diff_state_stacks_ref_eq, apply_state_stack_diff and the token attribute getters. Loading is synchronous, INITIAL is None, and dropping replaces dispose. A Registry stays on one thread; each thread can have its own.
  • Oniguruma (rust/vendor): vendor/oniguruma is a git submodule of kkos/oniguruma at v6.9.8, and vendor/patches holds the eight patches. rust/build.rs copies the submodule's sources to Cargo's OUT_DIR, applies the patches strictly (a hunk that no longer matches stops the build, naming the patch, the file and the hunk) and compiles them with the cc crate; rust/src/onig_ffi.rs declares the 12 functions of Oniguruma's C API that the port calls, and onig_lib.rs declares the search that patch 0005 adds. vendor/README.md explains each patch and how to update. The only other dependency is rustc-hash; building needs a C compiler, but no libclang.
  • Checks: the upstream_tests binary runs test-cases/, rust/tests holds the unit tests, rust/oracle-js dumps what vscode-textmate does, the oracle binary compares the port with that dump and bench times it, and the engine checks are binaries such as engine_probe and pattern_sweep, with their JS side and recorded output in rust/probe.
  • Outside rust/: .gitmodules, and the package files that build and ship the WebAssembly build as vscode-textmate/wasm (see Publishing 9.4.0). tsc, webpack and vitest still see only src/.
  • The WebAssembly build (rust/wasm), a crate of its own that depends on the port: src/main.rs exports 17 tm_* functions over handles (registries, grammars, states) and JSON, build.rs passes the Emscripten link flags (MODULARIZE, Node, web and worker), js/api.js is the JavaScript API and js/main.d.ts its types, which npm run build-wasm ships in release/wasm/ (the API with the glue in main.js), and js/textmate-wasm.js loads the cargo output for the checks js/smoke.js, js/oracle.js and js/bench.js.

Try it

From rust/ (the build needs Oniguruma's source: clone with --recurse-submodules or run the first command; without it, the build stops and says what to run):

git submodule update --init vendor/oniguruma
cargo build --release
cargo test --release
cargo run --release --example tokenize
cargo run --release --bin upstream_tests -- ../test-cases
cargo fmt --check
cargo clippy --release --all-targets

The comparison with vscode-textmate needs a VS Code checkout after pnpm install, and Node (it was run with Node 24); build this repository with npm install && npm run compile to compare with main:

VSCODE_ROOT=/path/to/vscode VSCODE_TEXTMATE_JS=/path/to/vscode-textmate/out/main.js node oracle-js/dump.js /path/to/data
VSCODE_ROOT=/path/to/vscode VSCODE_TEXTMATE_JS=/path/to/vscode-textmate/out/main.js node oracle-js/fonts.js /path/to/data
cargo run --release --bin oracle -- /path/to/data
cargo run --release --bin bench -- /path/to/data --reps 3

rust/README.md gives the commands for the colorize fixtures and the engine checks.

The WebAssembly build needs emsdk (it was built with 7.0.1) and Rust's wasm32-unknown-emscripten target; from rust/wasm, with the same data:

rustup target add wasm32-unknown-emscripten
source /path/to/emsdk/emsdk_env.sh
cargo build --release --target wasm32-unknown-emscripten
node js/smoke.js /path/to/data/grammars.json /path/to/data/theme.json
node js/oracle.js /path/to/data
VSCODE_ROOT=/path/to/vscode node js/bench.js /path/to/data

The package, from the repository's root, with the same tools (npm run build-wasm stops and says what to install or run when one is missing):

git submodule update --init rust/vendor/oniguruma
npm ci
npm run prepublishOnly
npm run wasm-smoke
npm pack

To check the tarball as a dependency, install it with vscode-oniguruma in a new project and run node scripts/wasm-smoke.js /path/to/project from the repository.

Not included yet

  • VS Code doesn't use it yet: TextMate: try the WebAssembly build of the Rust vscode-textmate port behind a setting vscode#351000 tries it out, and measuring it in VS Code's tokenization worker comes next. There is no Node binding; the WebAssembly build runs in Node.
  • Built and tested on an arm64 Mac only so far. CI gets its change to .github/workflows/ci.yml in a commit of its own: the checkout fetches the submodule, and it installs Rust 1.100.0 and Emscripten 7.0.1 and runs cargo test, upstream_tests, npm run prepublishOnly, npm run wasm-smoke and the same smoke test on the packed tarball, on ubuntu-latest.
  • Not ported: debug logging, parseJSON's debug locations, the theme tests (themes.test.ts) and the UseOnigurumaFindOptions path, which is off in vscode-textmate.
  • Publishing to crates.io was not tried. cargo package builds and verifies the crate with Oniguruma's sources and the patches in it (237 files, 722 KiB compressed); the manifest has no repository or documentation link yet.
  • A system Oniguruma: the build always compiles the patched submodule and has no option to link an installed Oniguruma, which would lack onig_regset_search_keyed (the patches add it).
  • The time limit is checked between scans, as in vscode-textmate. Whether a line stops early depends on the machine's speed, so it is the one result that is not compared automatically.

Details

How the port is built: API, regex engine, threads, dependencies

A direct, file-by-file port of this repository's TypeScript to Rust, as the crate vscode-textmate (0.1.0, edition 2024, Rust 1.85 or later, MIT) in rust/. It was written from this repository's TypeScript sources and the 9.3.2 npm bundle, with no code or design taken from other Rust TextMate implementations, and it keeps the TypeScript's structure (the same types, functions and order), so the two read side by side. rust/README.md maps each Rust module to its TypeScript files, and rust/PORT-SPEC.md records the details part by part.

It follows main: the 9.3.2 release plus #252 (a missing or empty end, and a back-referencing while whose source is empty, become the empty pattern instead of U+FFFF, so they match at once), #261 (the TokenHandler refactor) and #276 (fewer characters escaped in escapeRegExpCharacters).

  • API. vscode-textmate's, in snake_case: Registry (load_grammar, load_grammar_with_embedded_languages, load_grammar_with_configuration, add_grammar, set_theme, get_color_map), Grammar (tokenize_line, tokenize_line2 and their _with_time_limit variants), StateStack, diff_state_stacks_ref_eq, apply_state_stack_diff and the encoded token attribute getters. Loading is synchronous, INITIAL is None, and dropping replaces dispose.
  • Regex engine. The IOnigLib seam is kept as the OnigLib and OnigScanner traits. NativeOnigLib implements them on C Oniguruma 6.9.8, the sources that vscode-oniguruma 1.7.0 (the version VS Code ships) compiles to WebAssembly, built by rust/build.rs from the submodule rust/vendor/oniguruma and the patches in rust/vendor/patches (see Speed: the Oniguruma patches), and called through rust/src/onig_ffi.rs; Oniguruma 6.9.10 gives different results on 16 of the 82 engine probe cases. It searches the way vscode-oniguruma's onig.cc does: all of a scanner's regexes at once with a regset on lines shorter than 1,000 UTF-8 bytes, and each regex on its own, caching its last result, on longer ones. vscode-oniguruma doesn't report a pattern that fails to compile (createOnigScanner succeeds), and the port reproduces what such a scanner then finds.
  • Threads. A Registry uses Rc, so each thread needs its own. Oniguruma initializes its global tables lazily and without a lock, so NativeOnigLib initializes it once under std::sync::Once; tests/threads.rs tokenizes on 8 threads at once.
  • Dependencies: rustc-hash 2.1.3, and at build time cc 1.11.3 (with shlex and find-msvc-tools), which compiles Oniguruma from the submodule; the WebAssembly crate's lock has cc 1.12.0. Building needs a C compiler, but no libclang. JSON and plist parsing is ported, keeping JS key order, which decides rule ids and the order injections are tried in.
  • Outside rust/, .gitmodules is new, and the package gains the WebAssembly build (see Publishing 9.4.0): npm run build-wasm builds rust/wasm and writes release/wasm/, which files publishes with release/main.js and types/. tsc and webpack build only src/, and vitest runs only src/tests. CI's change comes in a commit of its own (see Not included yet).
  • Comparison tools. rust/oracle-js/ dumps what vscode-textmate does (from a VS Code checkout, or from this repository's build with VSCODE_TEXTMATE_JS), the oracle binary compares the port with it, and the bench binary times the same files without comparing. rust/probe/ holds the JS side of the engine checks.
All results in full: tests, comparisons, engine and speed

Measured on an arm64 Mac with Rust 1.100.0, except where noted.

  • This repository's test cases: upstream_tests runs test-cases/ the way src/tests/tokenization.test.ts does, and all 95 pass (first-mate 64, suite1 22, whileTests 9). Three of them (Issue Unexpected highlighting behavior when end is not defined #66, Wrong backreference escaping #239 and Empty end matches \uFFFF #251) cover the changes since 9.3.2, and a port of 9.3.2 alone fails them.
  • Unit tests: cargo test runs 30 tests, 20 ports of the matcher, JSON and grammar tests and 10 of the port's own, and they pass on Rust 1.85.0 and 1.100.0. cargo fmt --check and cargo clippy --release --all-targets report nothing.
  • Against vscode-textmate built from main (npm run compile), with vscode-oniguruma 1.7.0, VS Code's built-in grammars (84 scopes) and its 2026 Dark theme, on 9 files in 7 languages (98,998 lines, 481,930 tokens): 0 differences in the binary tokens of tokenize_line2, in the scopes of tokenize_line, in states rebuilt with diff_state_stacks_ref_eq and apply_state_stack_diff, and when tokenizing on from those states. Under two themes with font rules, 0 differences in 580,433 font ranges.
  • VS Code's colorize test fixtures (109 fixtures with a grammar, 3,424 lines; against main, 14,597 tokens and 26,341 font ranges): 0 differences in the same comparisons, and none against 9.3.2 either.
  • Against the 9.3.2 release: the same comparisons, on files and a theme that differ slightly (99,002 lines, 482,681 tokens), also give 0 differences.
  • Engine: the 82 engine probe cases (POSIX classes, case folding, Unicode properties and newer letters, anchors, look-behind, back-references, long lines, invalid patterns), 103 searches with patterns that don't compile, and 9 tokenizations of a grammar with invalid patterns (118 lines) give the same output as vscode-oniguruma 1.7.0. Every regex the 84 built-in grammars can produce (23,171, of which 6,499 are distinct) compiles.
  • Speed: measured on one machine with Node 24, warm, 3.05× faster than vscode-textmate built from main on the bench's 9 files (2,197 vs 6,690 ms) and 3.94× faster than the 9.3.2 release on TypeScript's checker.ts and SQLite's sqlite3.c (5,844 vs 23,041 ms); against the 9.3.2 release on the 9 files, 3.06× faster warm and 3.93× cold (rust/README.md has that table; the cold ratio includes a copy of the tokens that only JS makes, as Faster says). The release profile uses LTO and one codegen unit, eight patches to Oniguruma make its search faster without changing what it finds (see Speed: the Oniguruma patches), scanners share their compiled regexes, and the port allocates less per token; without the patches and the sharing (3d077ae), the port was 1.41× faster warm and 1.48× cold than 9.3.2.
  • One finding: the skipped grammar test "Shadowed rules are resolved correctly" expects outer ("TODO this should be inner"); vscode-textmate returns inner, and the ported test asserts what it does.
Speed: the Oniguruma patches, and how they are kept and built

The port spends most of its time in Oniguruma, and eight patches to it (0003 to 0010) make the search faster without changing what it finds. Together they take the warm total of the port's bench (the 9 files above) from 4,720 to about 2,197 ms (−53%). Two larger files check them too: TypeScript's checker.ts and SQLite's sqlite3.c. Each patch was checked the same way: 0 differences against vscode-textmate on the 9 files, the 109 colorize fixtures and the 9.3.2 comparison (236 files, and checker.ts and sqlite3.c from 0006 on), 95 of 95 test cases, the probes unchanged, and every built-in pattern compiles. From 0004 on, the numbers are means of runs alternated with and without the patch, three each (two for 0004).

How the patches are kept

rust/vendor/oniguruma is a git submodule of kkos/oniguruma at v6.9.8 (08d36110), the commit vscode-oniguruma's deps/oniguruma points at, and it is never edited. rust/build.rs copies its src to Cargo's OUT_DIR, applies the patches in rust/vendor/patches in the order of their names, writes the config.h that Oniguruma's configure would write, and compiles with the cc crate the 48 files the onig_sys crate compiled, following rust-onig's build script (MIT). It applies the patches more strictly than git apply: each hunk must start at the line its header names, and its context and removed lines must match exactly, so a patch that no longer fits stops the build and names the patch, the file and the hunk. rust/src/onig_ffi.rs declares the functions of Oniguruma's C API that the port calls (onig_lib.rs declares the search that 0005 adds), and links = "onig" in rust/Cargo.toml makes a second Oniguruma in the same build a Cargo error. rust/vendor/README.md explains each patch, why each search finds the same match, and how to update.

  • The numbers start at 0003: 0001 and 0002 changed the build script and the bindings of the onig_sys crate, which the port no longer uses. 0003 to 0010 make the search faster, as below.
  • 0003 to 0008 and 0010 apply to Oniguruma 6.9.10 (checked in onig_sys 69.9.3) with line offsets only, which build.rs doesn't accept, so moving to it means refreshing the patches; 0009's change to compile_tree would have to be redone by hand. The port stays on 6.9.8 all the same, the version vscode-oniguruma 1.7.0 bundles, because 6.9.10 changes 16 of the 82 engine probe cases. Upstream Oniguruma (kkos/oniguruma) is archived, so new versions should be rare.

0003: the regset search reuses its memory

The port runs Oniguruma's regset search once per token, as vscode-oniguruma does. Each search allocated and freed its scratch memory and gave each regex a new match stack at each position it tried; with the patch, the regset keeps this memory between searches and clears a region only when it must.

  • Warm total 4,720 → 4,059 ms (−14%), cold 6,232 → 5,587 ms.

0004: the length of a UTF-8 character is looked up inline

Oniguruma steps through the line with enclen, which called the encoding's length function through a pointer for every character. For UTF-8 it only reads a 256-entry table, which the patch reads directly. Every length, and so every match, is unchanged.

  • Warm total 4,063 → 3,932 ms (−3.2%), cold 5,576 → 5,428 ms (−2.6%).

0005: the regset search reuses forward_search results within a line

Before Oniguruma tries a regex at a position, its search runs forward_search, which uses what the regex must start with to skip to the next position where it could match. The port searches a line once per token, each time from where the last token ended, so each search ran forward_search again for every regex of the rule, over text it had already scanned for that regex.

With the patch, the port calls a new onig_regset_search_keyed with a key for the string, and the regset remembers, per regex, where its last forward_search started and the candidate it found, or that it found none. Over the same text and range, the first candidate at or after any start between the two is that same candidate, and with none found, a later start finds none either, so the regset reuses the result there and runs forward_search everywhere else.

  • A build that also runs forward_search at every reuse and aborts when they differ (-DONIG_REGSET_FS_VERIFY) found 0 mismatches on the 236 files, and a unit test covers searches from many starts.
  • Warm total 3,930 → 3,517 ms (−10.5%), cold 5,423 → 5,013 ms (−7.6%).

0006: the regset search sets up a regex only when it tries it

In position-lead mode, which the port uses as vscode-oniguruma does, the regset search set up every regex of the set before it searched, though a search usually tries only a few of them.

With the patch, the search sets up a regex the first time it tries it and frees only the regexes it set up; a generation number per regex makes starting a search cost nothing per regex.

  • Searches of the empty string, and in ONIG_REGSET_REGEX_LEAD mode, set up every regex as before; the port reads only the region of the regex that matched.
  • Warm total 3,460 → 3,184 ms (−8.0%), cold 3,640 → 3,364 ms (−7.6%); checker.ts and sqlite3.c, warm: 10,839 → 9,672 ms (−10.8%).

0007: the regset search tests the first byte before it tries a regex

The regset search walks the line one position at a time (on lines up to 500 bytes, and on longer ones unless every regex of the set has a bounded search range), and before it tried a regex at a position, it ran forward_search to find the regex's next candidate. Many of a grammar's regexes must start, at distance 0, with one of a known set of bytes or with a fixed string (OPTIMIZE_MAP, OPTIMIZE_STR and its variants), and for them forward_search from a position reports that position exactly when the map has its byte, or the string starts there.

With the patch, the search tests that directly (map[*s], or the first byte and a memcmp) for those of them without an anchor. They are tried in the same order at the same positions, match_at decides every match, and the path for longer lines is unchanged.

  • Warm total 3,090 → 2,752 ms (−11.0%), cold 3,264 → 2,926 ms (−10.4%); checker.ts and sqlite3.c, warm: 9,360 → 7,473 ms (−20.2%).

0008: the first-byte test also covers anchored regexes

0007 tested the first byte only for regexes without an anchor. That condition isn't needed: forward_search never reads the anchor of a regex, so for an anchored regex it reports the same candidates in the same order as the direct test, and match_at still checks \G, \A and look-behind, and the ANCR_ANYCHAR_INF check still runs before each try. Grammars use \G and look-behind a lot (TypeScript's keywords start with (?<![_$[:alnum:]])), so many more regexes now skip forward_search.

  • Warm total 2,768 → 2,521 ms (−8.9%), cold 2,946 → 2,699 ms (−8.4%); checker.ts and sqlite3.c, warm: 7,450 → 6,492 ms (−12.9%).

0009: alternatives whose first byte is absent are skipped

An alternation compiles each branch but the last to OP_PUSH, which saves a backtrack point, so a branch that fails on its first byte costs a push, a compare and a pop. When a branch must start with a known byte (a case-sensitive string, also inside a capture, atomic or option group or a quantifier with a lower bound of at least 1), the patch compiles it to OP_PUSH_OR_JUMP_EXACT1, which Oniguruma already emits for quantifiers: it pushes the same backtrack point when that byte is at the position, and otherwise jumps to the next branch. Matches and captures are the same; only Oniguruma's retry count is lower.

  • Warm total 2,524 → 2,332 ms (−7.6%), cold 2,697 → 2,512 ms (−6.9%); checker.ts and sqlite3.c, warm: 6,490 → 6,304 ms (−2.9%).

0010: the first-byte map search steps over UTF-8 bytes

When a regex can start with one of several bytes, forward_search scans with map_search, which moved from character to character and looked up each one's length. In UTF-8 a byte that starts a character is never a continuation byte (10xxxxxx), so the patch tests every byte and skips continuation bytes: it stops at the same character heads, so it finds the same position. Other encodings are unchanged.

  • Warm total 2,330 → 2,197 ms (−5.7%), cold 2,503 → 2,377 ms (−5.0%); checker.ts and sqlite3.c, warm: 6,278 → 5,844 ms (−6.9%).

Keeping the patches as files, and building from the submodule

Before: the changes were edits made in place in the vendored onig_sys crate, recorded only in prose.

before-oniguruma-edited-in-place.png

After: a script generated the vendored crate from the published one and the patch files, and checked it (captured before 0005 was added).

after-oniguruma-patch-files.png

Now rust/build.rs applies them to the submodule at build time: the patched sources it compiles are byte-identical to the 64 files of the vendored crate they replace, git apply gives the same result, the comparisons give 0 differences on all 238 files, and the bench is unchanged (warm 2,184 vs 2,199 ms on the 9 files; 5,786 vs 5,824 ms on checker.ts and sqlite3.c).

Crates that depend on the port

rust/build.rs builds the patched Oniguruma wherever the crate is built, so a crate that depends on the port gets it with nothing else to set: a scratch crate that depends on it by path builds and tokenizes. Cargo also checks out the submodules of Git dependencies (not tried). links = "onig" keeps a second Oniguruma out of the same build: with onig_sys = "=69.8.1" added, the scratch crate fails to resolve, and Cargo says only one package in the dependency graph may specify the same links value.

Speed: shared compiled regexes and fewer allocations per token

Shared compiled regexes

The same pattern appears in the scanners of many rules, and vscode-oniguruma compiles it again for each scanner, as the port did at first: on the bench's 9 files, the first pass compiled 32,462 regexes of only 2,147 distinct patterns. NativeOnigLib keeps a per-thread cache from pattern to compiled regex, so scanners share them. No change to Oniguruma is needed.

  • The cache holds weak references only, and a pattern that doesn't compile is never cached. A scanner takes its regexes out of its regset before freeing it, and the per-search state belongs to the regset or the scanner, never to the regex, so what a regex finds doesn't depend on who else uses it. A unit test drops and creates scanners that share patterns, including ones that don't compile.
  • The tokens are the same: 0 differences on the 236 files of the comparisons, 95 of 95 test cases, the engine, invalid-pattern and invalid-grammar probes unchanged, every built-in pattern compiles, and cargo test passes on Rust 1.85.0.
  • Run alternately with and without it: cold total about 5,000 → 3,640 ms (−27%), warm about 3,517 → 3,457 ms (−1.7%). The bench builds a new registry for each file, so this counts no sharing between files.

Fewer allocations per token

  • onig_find builds the capture indices once, at their final size, instead of building them twice.
  • For binary tokens, LineTokens refills one buffer of scope names (ScopeStack::fill_segments) to match the token types and bracket selectors, instead of a new vector per token.
  • The tokens are the same: 0 differences on the 238 files of the comparisons (the 236 above, checker.ts and sqlite3.c), 95 of 95 test cases, and the probes unchanged.
  • Run alternately with and without it: warm total 3,178.5 → 3,091.1 ms (−2.8%), cold 3,355.8 → 3,264.9 ms (−2.7%).
Speed at each step, and the bench before and after patch 0010
means of 3 runs cold ms warm ms JS warm ms vs JS
without 0006 3,640.2 3,459.5 6,689.8 1.93×
with 0006 3,364.0 3,183.6 6,689.8 2.10×
with the trims 3,263.6 3,090.3 6,689.8 2.16×
with 0007 2,925.5 2,751.6 6,689.8 2.43×
with 0008 2,699.0 2,521.4 6,689.8 2.65×
with 0009 2,512.3 2,332.4 6,689.8 2.87×
with 0010 2,376.9 2,196.5 6,689.8 3.05×

On checker.ts and sqlite3.c, warm: 10,839 ms without 0006, 9,672 with it, 9,360 with the trims, 7,473 with 0007, 6,492 with 0008, 6,304 with 0009 and 5,844 with 0010 (3.94× faster than vscode-textmate 9.3.2).

Before: with 0009, the bench on the 9 files and on checker.ts and sqlite3.c:

pr-evidence-0014-before.png

After: with 0010, the same, the alternating runs and the checks:

pr-evidence-0014-after.png

Speed at each step: before and after the port (3d077ae, a69253d before it was pushed)

Before

before-main-plus-9.3.2-only-port.png

After

after-rust-port-a69253d-summary.png

after-a69253d-full.png

Before / after

Before

pack-before-997b465.txt

$ git clone <vscode-textmate> vscode-textmate && cd vscode-textmate && git checkout 997b465    # the head of #315

$ git log --oneline -1
997b465 rust/wasm: compare every token in the bench, reject empty selections, report the time limit without failing on it

$ cp -R <kkos/oniguruma at 08d36110>/. rust/vendor/oniguruma/    # the submodule's files, from a local copy
rust/vendor/oniguruma/src/oniguruma.h

$ npm ci

added 230 packages in 2s

$ npm run prepublishOnly

assets by status 47.7 KiB [cached] 30 assets
Entrypoint main =

ERROR in main
Module not found: Error: Can't resolve './out/main.js' in '~/before/vscode-textmate'
resolve './out/main.js' in '~/before/vscode-textmate'
  using description file: ~/before/vscode-textmate/package.json (relative path: .)
    Field 'browser' doesn't contain a valid alias configuration
    using description file: ~/before/vscode-textmate/package.json (relative path: ./out/main.js)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        ~/before/vscode-textmate/out/main.js doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        ~/before/vscode-textmate/out/main.js.js doesn't exist
      as directory
        ~/before/vscode-textmate/out/main.js doesn't exist

webpack 5.105.3 compiled with 1 error in 39 ms
exit code 1

$ npm pack --dry-run
npm notice 1.1kB LICENSE.md
npm notice 5.5kB README.md
npm notice 1.5kB package.json
npm notice version: 9.3.2
npm notice package size: 3.3 kB
npm notice total files: 3

$ mkdir ../consumer && cd ../consumer && npm init -y && npm install vscode-textmate@9.3.2 vscode-oniguruma@1    # what npm has today

added 2 packages in 604ms

$ node <rust-publish>/scripts/wasm-smoke.js .    # the comparison the update adds, against vscode-textmate 9.3.2
Error: Cannot find module 'vscode-textmate/wasm'
Require stack:
- ~/before/consumer/package.json
    at Module._resolveFilename (node:internal/modules/cjs/loader:1564:15)
    at wrapResolveFilename (node:internal/modules/cjs/loader:1118:27)
    at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1169:12)
    at require.resolve (node:internal/modules/helpers:175:31)
    at main (~/rust-publish/scripts/wasm-smoke.js:56:23)
    at Object.<anonymous> (~/rust-publish/scripts/wasm-smoke.js:200:1)
    at Module._compile (node:internal/modules/cjs/loader:1929:14)
    at Object..js (node:internal/modules/cjs/loader:2060:10)
    at Module.load (node:internal/modules/cjs/loader:1651:32)
exit code 1

After

pack-after-clean-clone.txt

$ git clone --branch rust-publish <vscode-textmate> vscode-textmate && cd vscode-textmate

$ git log --oneline -5
a7b9319 wasm: keep the build machine's paths out of vscode-textmate.wasm
d6be9e7 Release 9.4.0: changelog, notices of the WebAssembly build, README section
0567706 wasm: build the WebAssembly module in prepublishOnly
80b6f74 wasm: add the vscode-textmate/wasm export
997b465 rust/wasm: compare every token in the bench, reject empty selections, report the time limit without failing on it

$ git submodule status
-08d36110c5670c815ad6d6f969e578049d209080 rust/vendor/oniguruma

$ npm ci

added 230 packages in 1s

$ npm run build-wasm    # the submodule isn't initialized, and git can't fetch it on this machine

> vscode-textmate@9.4.0 build-wasm
> node scripts/build-wasm.js

build-wasm: git submodule update --init rust/vendor/oniguruma
Submodule 'rust/vendor/oniguruma' (https://github.com/kkos/oniguruma) registered for path 'rust/vendor/oniguruma'
Cloning into '~/after/vscode-textmate/rust/vendor/oniguruma'...
fatal: transport 'https' not allowed
fatal: clone of 'https://github.com/kkos/oniguruma' into submodule path '~/after/vscode-textmate/rust/vendor/oniguruma' failed
Failed to clone 'rust/vendor/oniguruma'. Retry scheduled
Cloning into '~/after/vscode-textmate/rust/vendor/oniguruma'...
fatal: transport 'https' not allowed
fatal: clone of 'https://github.com/kkos/oniguruma' into submodule path '~/after/vscode-textmate/rust/vendor/oniguruma' failed
Failed to clone 'rust/vendor/oniguruma' a second time, aborting
build-wasm: `git submodule update --init rust/vendor/oniguruma` failed: the Oniguruma sources are needed to build the WebAssembly module.
exit code 1

$ cp -R <kkos/oniguruma at 08d36110>/. rust/vendor/oniguruma/    # the submodule's files, from a local copy
rust/vendor/oniguruma/src/oniguruma.h

$ npm run prepublishOnly

> vscode-textmate@9.4.0 prepublishOnly
> tsc && webpack --progress && npm run api-extractor && npm run build-wasm

assets by path *.ts 29.3 KiB
  asset rule.d.ts 8.61 KiB [emitted] [from: out/rule.d.ts] [copied]
  asset main.d.ts 5.61 KiB [emitted] [from: out/main.d.ts] [copied]
  + 12 assets
assets by path tests/*.ts 2.19 KiB
  asset tests/resolver.d.ts 1.15 KiB [emitted] [from: out/tests/resolver.d.ts] [copied]
  asset tests/themeTest.d.ts 507 bytes [emitted] [from: out/tests/themeTest.d.ts] [copied]
  asset tests/themedTokenizer.d.ts 230 bytes [emitted] [from: out/tests/themedTokenizer.d.ts] [copied]
  + 7 assets
assets by path grammar/*.ts 16.2 KiB
  asset grammar/grammar.d.ts 11.5 KiB [emitted] [from: out/grammar/grammar.d.ts] [copied]
  asset grammar/grammarDependencies.d.ts 2.46 KiB [emitted] [from: out/grammar/grammarDependencies.d.ts] [copied]
  asset grammar/basicScopesAttributeProvider.d.ts 1.13 KiB [emitted] [from: out/grammar/basicScopesAttributeProvider.d.ts] [copied]
  + 2 assets
asset main.js 60.1 KiB [emitted] [minimized] (name: main) 1 related asset
modules by path ./out/*.js 102 KiB
  ./out/main.js 5.52 KiB [built] [code generated]
  ./out/onigLib.js 451 bytes [built] [code generated]
  ./out/theme.js 20.1 KiB [built] [code generated]
  ./out/parseRawGrammar.js 1.06 KiB [built] [code generated]
  ./out/registry.js 2.33 KiB [built] [code generated]
  ./out/diffStateStacks.js 1.46 KiB [built] [code generated]
  ./out/debug.js 517 bytes [built] [code generated]
  + 6 modules
modules by path ./out/grammar/*.js 64.1 KiB
  ./out/grammar/index.js 1020 bytes [built] [code generated]
  ./out/grammar/grammarDependencies.js 9.28 KiB [built] [code generated]
  ./out/grammar/grammar.js 29.9 KiB [built] [code generated]
  ./out/grammar/basicScopesAttributeProvider.js 3.6 KiB [built] [code generated]
  ./out/grammar/tokenizeString.js 20.3 KiB [built] [code generated]
webpack 5.105.3 compiled successfully in 503 ms

> vscode-textmate@9.4.0 api-extractor
> mkdirp etc && npx api-extractor run --local

api-extractor 7.52.9  - https://api-extractor.com/

Using configuration from ./api-extractor.json
Analysis will use the bundled TypeScript version 5.8.2
*** The target project appears to use TypeScript 5.9.3 which is newer than the bundled compiler engine; consider upgrading API Extractor.
Warning: The API report file was missing, so a new file was created. Please add this file to Git:
~/after/vscode-textmate/etc/vscode-textmate.api.md
Warning: out/grammar/grammar.d.ts:98:43 - (tsdoc-unnecessary-backslash) A backslash can only be used to escape a punctuation character
Warning: out/main.d.ts:114:26 - (tsdoc-escape-greater-than) The ">" character should be escaped using a backslash to avoid confusion with an HTML tag
Warning: out/main.d.ts:115:30 - (tsdoc-escape-greater-than) The ">" character should be escaped using a backslash to avoid confusion with an HTML tag
Warning: out/onigLib.d.ts:18:102 - (tsdoc-unnecessary-backslash) A backslash can only be used to escape a punctuation character
Warning: out/onigLib.d.ts:22:98 - (tsdoc-unnecessary-backslash) A backslash can only be used to escape a punctuation character
Warning: out/onigLib.d.ts:22:102 - (tsdoc-unnecessary-backslash) A backslash can only be used to escape a punctuation character
Warning: out/onigLib.d.ts:26:115 - (tsdoc-unnecessary-backslash) A backslash can only be used to escape a punctuation character

API Extractor completed successfully

> vscode-textmate@9.4.0 build-wasm
> node scripts/build-wasm.js

build-wasm: rustc 1.100.0 (0ef1bc386 2026-11-09)
build-wasm: cargo 1.100.0 (3acc79c0c 2026-11-05)
build-wasm: emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 7.0.1 (ac0578743420bcbe9a4f77d0b6599c25f8d43702)
   Compiling shlex v2.0.1
   Compiling find-msvc-tools v0.1.16
   Compiling vscode-textmate-wasm v0.1.0 (~/after/vscode-textmate/rust/wasm)
   Compiling rustc-hash v2.1.3
   Compiling cc v1.12.0
   Compiling vscode-textmate v0.1.0 (~/after/vscode-textmate/rust)
warning: linker stderr: emcc: WASM_BIGINT is deprecated (no longer needed. Should only ever be implicitly disabled by -sWASM=0). Please open a bug if you have a continuing need for this setting [-Wdeprecated]
  |
  = note: `#[warn(linker_messages)]` on by default

warning: `vscode-textmate-wasm` (bin "vscode-textmate-wasm") generated 1 warning
    Finished `release` profile [optimized] target(s) in 12.34s
build-wasm: release/wasm/main.js 24263 bytes
build-wasm: release/wasm/main.d.ts 3849 bytes
build-wasm: release/wasm/vscode-textmate.wasm 761160 bytes
exit code 0

$ npm pack
npm notice
npm notice package: vscode-textmate@9.4.0
npm notice Tarball Contents
npm notice 1.6kB CHANGELOG.md
npm notice 1.1kB LICENSE.md
npm notice 7.0kB README.md
npm notice 9.4kB ThirdPartyNotices.txt
npm notice 2.1kB package.json
npm notice 61.6kB release/main.js
npm notice 3.8kB release/wasm/main.d.ts
npm notice 24.3kB release/wasm/main.js
npm notice 761.2kB release/wasm/vscode-textmate.wasm
npm notice 26.1kB types/vscode-textmate.d.ts
npm notice Tarball Details
npm notice name: vscode-textmate
npm notice version: 9.4.0
npm notice filename: vscode-textmate-9.4.0.tgz
npm notice package size: 319.3 kB
npm notice unpacked size: 898.2 kB
npm notice shasum: d2bb7b135800acd299478fc715ee827a95a1a29a
npm notice integrity: sha512-oicbSpv9zknJF[...]qAY1z9riVAbMQ==
npm notice total files: 10
npm notice
vscode-textmate-9.4.0.tgz
exit code 0

$ tar tzvf vscode-textmate-9.4.0.tgz
61561 package/release/main.js
24263 package/release/wasm/main.js
2150 package/package.json
1625 package/CHANGELOG.md
1083 package/LICENSE.md
6977 package/README.md
3849 package/release/wasm/main.d.ts
26138 package/types/vscode-textmate.d.ts
9410 package/ThirdPartyNotices.txt
761160 package/release/wasm/vscode-textmate.wasm

$ mkdir ../consumer && cd ../consumer && npm init -y && npm install ../vscode-textmate/vscode-textmate-9.4.0.tgz vscode-oniguruma@1

added 2 packages in 164ms

$ npm ls
consumer@1.0.0 ~/after/consumer
+-- vscode-oniguruma@1.7.0
`-- vscode-textmate@9.4.0

$ node -p "Object.keys(require('vscode-textmate/package.json').exports)"
[ '.', './wasm', './release/*', './types/*', './package.json' ]

$ node ../vscode-textmate/scripts/wasm-smoke.js .    # resolves vscode-textmate and vscode-textmate/wasm from the installed tarball
vscode-textmate:      ~/after/consumer/node_modules/vscode-textmate/release/main.js (9.4.0)
vscode-textmate/wasm: ~/after/consumer/node_modules/vscode-textmate/release/wasm/main.js
vscode-oniguruma:     ~/after/consumer/node_modules/vscode-oniguruma/release/main.js
vscode-textmate.wasm: 761160 bytes
95 tests, 166 lines, 703 tokens: the wasm build and vscode-textmate agree
exit code 0

$ node -e <the README example, on test-cases' JavaScript grammar>
[
  'source.js meta.function.js storage.type.function.js',
  'source.js meta.function.js',
  'source.js meta.function.js entity.name.function.js',
  'source.js meta.function.js meta.parameters.js punctuation.definition.parameters.begin.js',
  'source.js meta.function.js meta.parameters.js variable.parameter.js',
  'source.js meta.function.js meta.parameters.js punctuation.definition.parameters.end.js',
  'source.js meta.function.js',
  'source.js meta.function.js meta.block.js punctuation.definition.block.js'
]
exit code 0

$ grep -c '/Users/' package/release/wasm/vscode-textmate.wasm    # paths of the machine that built the package
0

$ shasum -a 256 ~/after/vscode-textmate/release/wasm/vscode-textmate.wasm ~/rust-publish/release/wasm/vscode-textmate.wasm    # built in two different folders
935f1493aab7d6ab9a90d5749c0d05929db42916623ae01ae618c17f5a37182c  ~/after/vscode-textmate/release/wasm/vscode-textmate.wasm
935f1493aab7d6ab9a90d5749c0d05929db42916623ae01ae618c17f5a37182c  ~/rust-publish/release/wasm/vscode-textmate.wasm

🤖 Authored with GitHub Copilot on behalf of Alexandru Dima (@alexdima).

A direct, file-by-file port of vscode-textmate's TypeScript sources to
Rust, as the crate `vscode-textmate` in rust/. It follows main: the 9.3.2
release plus #252, #261 and #276.

- Loads the same grammars and themes and gives the same tokens, scopes,
  states, encoded attributes and fonts as vscode-textmate built from main
  (and as 9.3.2), compared line by line on VS Code's built-in grammars.
- Links Oniguruma 6.9.8 through onig_sys =69.8.1, the C sources that
  vscode-oniguruma 1.7.0 compiles to WASM, and reproduces how
  vscode-oniguruma handles patterns that don't compile.
- upstream_tests runs test-cases/ the way tokenization.test.ts does
  (95 pass); cargo test runs ports of the matcher, JSON and grammar tests.
- oracle-js/ and probe/ hold the JS side of the comparisons.

Nothing outside rust/ changes: npm's `files`, tsconfig and vitest don't
include it.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Publicly mutable buffers and unchecked position casts can cause undefined behavior in native searches, while the comparison probe can falsely pass when expected results are missing.

3 open issues
What changed in this PR

Adds a native Rust port of vscode-textmate under rust/, addressing #314 while leaving the existing TypeScript package and CI unchanged. The port targets equivalent grammar loading, tokenization, themes, and state handling.

Changes:

  • Introduces the Rust crate and native Oniguruma backend with UTF-16 offset mapping.
  • Adds ported tests, concurrent initialization coverage, and JavaScript comparison tools.
  • Documents API differences, implementation details, benchmarks, and current limitations.
File Description
rust/​tests/​upstream_matcher.rs Ports scope-selector matcher cases.
rust/​tests/​upstream_json.rs Tests JSON parsing compatibility.
rust/​tests/​upstream_grammar.rs Tests metadata, shadowing, and fonts.
rust/​tests/​threads.rs Exercises concurrent native initialization.
rust/​src/​raw.rs Implements raw grammar parsing and preparation.
rust/​src/​onig_lib.rs Adds scanner traits and native regex backend.
rust/​src/​lib.rs Exports the Rust modules.
rust/​src/​diff_state_stacks.rs Implements state-stack diffing and reconstruction.
rust/​src/​bin/​upstream_tests.rs Runs upstream tokenization fixtures.
rust/​src/​bin/​pattern_sweep.rs Checks grammar regex compilation.
rust/​src/​bin/​parse_check.rs Checks oracle grammar and theme loading.
rust/​src/​bin/​invalid_grammar.rs Dumps tokenization with invalid patterns.
rust/​src/​bin/​garbage_probe.rs Probes invalid-pattern scanner behavior.
rust/​src/​bin/​engine_probe.rs Runs native regex comparison cases.
rust/​rustfmt.toml Configures tab indentation.
rust/​README.md Documents usage, validation, and limitations.
rust/​probe/​rust-698.txt Records strict Oniguruma 6.9.8 results.
rust/​probe/​rust-698-lenient.txt Records lenient Oniguruma 6.9.8 results.
rust/​probe/​rust-6910.txt Records Oniguruma 6.9.10 results.
rust/​probe/​report-698.txt Summarizes strict 6.9.8 comparisons.
rust/​probe/​report-698-lenient.txt Summarizes lenient 6.9.8 comparisons.
rust/​probe/​report-6910.txt Documents 6.9.10 behavior differences.
rust/​probe/​probe.js Runs JavaScript regex probes.
rust/​probe/​js.txt Records JavaScript regex results.
rust/​probe/​invalid-grammar.json Supplies invalid-pattern grammar fixtures.
rust/​probe/​invalid-grammar.js Produces JavaScript invalid-grammar tokens.
rust/​probe/​invalid-grammar-rust.txt Records Rust invalid-grammar output.
rust/​probe/​invalid-grammar-js.txt Records JavaScript invalid-grammar output.
rust/​probe/​garbage.js Probes JavaScript invalid-pattern behavior.
rust/​probe/​garbage-rust.txt Records native invalid-pattern searches.
rust/​probe/​garbage-js.txt Records JavaScript invalid-pattern searches.
rust/​probe/​garbage-history.js Checks effects of prior searches.
rust/​probe/​garbage-history-js.txt Records search-history probe results.
rust/​probe/​compare.js Compares engine probe outputs.
rust/​probe/​cases.json Stores shared regex probe cases.
rust/​probe/​cases.js Generates regex probe cases.
rust/​PORT-SPEC.md Documents ported behavior and design mappings.
rust/​oracle-js/​fonts.js Dumps font and state-replay expectations.
rust/​oracle-js/​env.js Configures oracle grammars, themes, and corpora.
rust/​oracle-js/​dump.js Dumps reference tokens and timings.
rust/​oracle-js/​dump-fixtures.js Uses VS Code colorization fixtures.
rust/​examples/​tokenize.rs Demonstrates both tokenization APIs.
rust/​Cargo.toml Defines crate dependencies and build settings.
rust/​Cargo.lock Locks dependency versions.
rust/​.gitignore Excludes Rust build output.

Review effort: Balanced

Comment thread rust/src/onig_lib.rs Resolved
Comment thread rust/src/onig_lib.rs Resolved
Comment thread rust/probe/compare.js Resolved
…il probe compare on missing results

- OnigString's text is private, with a read-only content() accessor: the
  lengths, offset maps and cache id are computed from it once, so changing
  it afterwards could index past the text or hit a stale cached match.
- find_next_match_sync converts the start position with a saturating
  i64::try_from instead of a cast, which wrapped usize::MAX to -1, and
  onig_find rejects a negative position before it offsets the text pointer.
  A test covers usize::MAX on ASCII and non-ASCII text.
- probe/compare.js reports cases that either output lacks and exits 1 for
  them, so a run that stops early no longer compares as identical. The
  committed reports are regenerated with the new summary line.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The token-range documentation incorrectly guarantees a length + 1 endpoint, which could lead callers to adjust valid ranges; both occurrences should describe it as a possible endpoint.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Low severity Clarify that the final token endpoint may be line length + 1

rust/​README.md:131

The last token can end at the original line length because get_result removes a separate newline-only token. Describe length + 1 as a possible endpoint rather than a guarantee, so callers do not incorrectly adjust valid token ranges. Same issue in rust/examples/tokenize.rs:52.

3 resolved since last review

Review effort: Balanced

Vendor onig_sys 69.8.1 (Oniguruma 6.9.8) in rust/vendor/onig_sys, trimmed to what its build uses. Patch regexec.c so that a regset search keeps its match stack, search ranges and match arguments between calls, and clears only the regions it must (PATCHES.md gives the diff). The tokens are unchanged against vscode-textmate (0 oracle differences), and the bench's warm total drops from 4,720 to 4,059 ms (-14%). Add a bench binary that times the oracle's files without comparing. Say, in the README and the tokenize example, that the last token can end at the line's length + 1, and update the README's speed numbers.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The standalone onigposix.h defines OnigSyntaxType as 16 bytes instead of the engine’s 40 bytes, causing onig_copy_syntax to overrun a destination allocation by 24 bytes.

No open issues 🎉

Review effort: Balanced

- Keep the Oniguruma changes as patch files in rust/vendor/patches: rust/vendor/update-onig-sys.sh generates rust/vendor/onig_sys from the checksummed onig_sys 69.8.1 crate and the patches, and its --check fails when the tree differs.
- 0004: look up the length of a UTF-8 character inline.
- 0005: the regset search reuses forward_search results within a line (onig_regset_search_keyed).
- Scanners share compiled regexes through a per-thread cache of weak references, keyed by pattern.
- Update the READMEs.

On the port's bench, run alternately with d527f79: warm 4,061 -> 3,459 ms (-14.8%), cold 5,568 -> 3,642 ms (-34.6%). 0 differences against vscode-textmate on the 236 comparison files.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The crate-local Cargo patch is ignored by consuming workspaces, leaving consumers with an unpatched backend that lacks a required symbol and causes native tokenization to fail to link.

1 open issue

Review effort: Balanced

Comment thread rust/Cargo.toml Resolved
…atched Oniguruma

Cargo applies [patch.crates-io] only in the root manifest, so a crate that
depended on vscode-textmate by path or Git got the unpatched onig_sys 69.8.1
from crates.io and failed to link on onig_regset_search_keyed. onig_sys is now
a path dependency on vendor/onig_sys, without a version, so cargo publish
refuses instead of packaging against the unpatched crate.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are recorded for the native Rust port.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

…locations, path dependency on the patched onig_sys

- Cargo.toml depends on vendor/onig_sys by path instead of [patch.crates-io], which Cargo applies only in the root manifest, so crates that depend on the port now build the patched Oniguruma.
- 0006: the regset search sets up a regex only when it tries it.
- 0007: the regset search tests a regex's first byte (map or exact string) before it tries it.
- 0008: the first-byte test also covers anchored regexes.
- 0009: alternatives whose required first byte is absent are skipped (OP_PUSH_OR_JUMP_EXACT1).
- 0010: the first-byte map search steps through UTF-8 a byte at a time, skipping continuation bytes.
- onig_find builds capture indices once; binary tokens reuse one scope-name buffer.

0 token differences against vscode-textmate on 238 files and 109 colorize fixtures; warm bench total 3,460 -> 2,197 ms.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The native regex compiler and search optimizations cross unsafe FFI boundaries, requiring specialist semantic and memory-safety review plus independent runtime equivalence and sanitizer checks unavailable in this environment.

No open issues 🎉

Review effort: Balanced

The Performance paragraph gave only per-file speedups against vscode-textmate built from main; it now gives the warm total (3.05×) and the result on checker.ts and sqlite3.c (3.94×). The list of Oniguruma patches under engine parity was missing 0010, and the check command it names is now one that runs as shown (`bash vendor/update-onig-sys.sh --check`, from rust/).

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because supported system-library overrides can bypass the patched dependency and cause link failures from a missing symbol.

No open issues 🎉

Review effort: Balanced

The 3.94x on checker.ts and sqlite3.c was measured against the
vscode-textmate 9.3.2 release, not against main.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@alexdima
Alexandru Dima (alexdima) requested a balanced review from Copilot November 28, 2026 13:20

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Native memory-ownership and regex changes need specialist review with the initialized Oniguruma submodule and sanitizer-backed validation, since the available evidence does not establish memory safety or semantic invariants.

No open issues 🎉

Review effort: Balanced

rust/wasm compiles the port and the patched Oniguruma with Emscripten into one .wasm module, and js/textmate-wasm.js puts vscode-textmate's JavaScript API on it (Registry, INITIAL, parseRawGrammar, diffStateStacksRefEq, applyStateStackDiff), so that VS Code can load it in place of vscode-textmate and vscode-oniguruma.

js/oracle.js finds 0 differences from vscode-textmate on 11 corpora (the bench's 9 files against main, fonts included; checker.ts and sqlite3.c against 9.3.2). In Node 24, js/bench.js measures it 2.11x faster warm on the 9 files and 2.76x on checker.ts and sqlite3.c than vscode-textmate 9.3.2 with vscode-oniguruma 1.7.0.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The benchmark can silently pass mismatched token offsets or metadata when counts match, while the oracle can pass empty selections and reject correct results based on timing.

3 open issues

Review effort: Balanced

Comment thread rust/wasm/js/bench.js Resolved
Comment thread rust/wasm/js/oracle.js Resolved
Comment thread rust/wasm/js/oracle.js Resolved
… report the time limit without failing on it

- js/bench.js compares every line's binary tokens from both sides after the timed passes, instead of only the token counts, and exits 1 on any difference.
- js/oracle.js and js/bench.js exit 2 with a message when their arguments select no corpus: a data directory without corpus-*.json, or a tag that names none.
- js/oracle.js reports whether the 1 ms time limit stops a long line early without failing on it, as the native oracle does, since that depends on the machine's speed.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to evaluate critical grammar-loading race conditions and persistent WebAssembly registry leaks omitted from the published review.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

- Export `vscode-textmate/wasm`: `loadWASM(bytes)` returns vscode-textmate's API on the Rust port compiled with Emscripten, typed in release/wasm/main.d.ts.
- `npm run build-wasm` (scripts/build-wasm.js) initializes the Oniguruma submodule, checks the toolchain, builds rust/wasm with the build paths remapped and writes release/wasm/; prepublishOnly runs it.
- `npm run wasm-smoke` (scripts/wasm-smoke.js) compares vscode-textmate/wasm with vscode-textmate on the test cases.
- 9.4.0: CHANGELOG entry, README section, ThirdPartyNotices (Oniguruma, rustc-hash) shipped; files, exports and typesVersions for ./wasm; tsconfig compiles only src/.
- The port and the module: diffs from or to INITIAL match vscode-textmate's, an invalid theme is an error instead of an abort, getColorMap keeps null at id 0, diffs omit absent enterPos and anchorPos, and applyStateStackDiff throws on invalid JSON.
- rust/README.md documents the toolchain versions and the build.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The build script can read missing or stale WASM artifacts because its hardcoded output path may differ from Cargo’s configured target directory.

1 open issue

Review effort: Balanced

Comment thread scripts/build-wasm.js Resolved
…target-dir can't move the files it packages

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because an unpublished moderate finding identifies broken getColorMap() round trips for JSON-transported maps with a null sentinel.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Checks out the Oniguruma submodule, installs Rust 1.100.0 with the wasm32-unknown-emscripten target and emsdk 7.0.1, runs cargo test and the Rust port on the test cases, builds the package as npm publish does, compares vscode-textmate/wasm with vscode-textmate on the test cases, and smoke-tests the packed tarball.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…builds and tests the Rust port and the wasm

- rust/build.rs compiles Oniguruma as gnu17 except with MSVC, natively and for wasm. CI caught it: the run on fd62de3 (46306996077) failed at "Rust unit tests" on ubuntu-latest, where GCC compiles C as C23, Oniguruma 6.9.8's st.h `int (*)(ANYARGS)` means `int (*)(void)`, and regparse.c:1932 is a type error, so cc-rs failed. emcc gets -std=gnu17 too.
- build/pipeline.yml, which publishes the package, checks out the Oniguruma submodule, installs Rust 1.100.0 (build/setup-rust.sh, rustup checked by SHA-256) and emsdk 7.0.1 (build/setup-emsdk.sh), both run with bash, and runs build-wasm and wasm-smoke; its Linux test job also runs cargo test and upstream_tests.
- prepack runs scripts/check-release.js, so npm pack and npm publish refuse to pack without release/main.js, release/wasm, their types and a .wasm built for this version.
- scripts/build-wasm.js names emcc and emar for the target, so a global CC or AR can't replace them.
- The wasm getColorMap returns a color map given to setTheme as it was given, null or a hole at id 0 included, as vscode-textmate does, instead of '' at id 0.

🤖 Authored with GitHub Copilot on behalf of @alexdima.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The native regex changes, Rust/C ABI, and Emscripten release pipeline require specialist review and native/WASM validation, which remain blocked by unavailable dependencies and toolchains and an uninspected private pipeline template.

No open issues 🎉

Review effort: Balanced

@alexdima
Alexandru Dima (alexdima) marked this pull request as ready for review November 29, 2026 22:27
@alexdima
Alexandru Dima (alexdima) merged commit 8eab856 into main Nov 29, 2026
12 checks passed
@alexdima
Alexandru Dima (alexdima) deleted the agents/rust-port branch November 29, 2026 23:33
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.

Add a Rust port of vscode-textmate

4 participants