code: add tree-sitter native highlighter with regex fallback (opt-in build)
- Commit
01b8de472228b156e00fbff9c9b1f1a05b38fdb4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-07 03:22 UTC (4 months ago)
- Parents
d0a6a60
Diff
code/build.gradle.kts
diff --git a/code/build.gradle.kts b/code/build.gradle.ktsindex 3126708857..d600c1b5e7 100644--- a/code/build.gradle.kts+++ b/code/build.gradle.kts@@ -15,6 +15,22 @@ android { } } +// Native tree-sitter highlighter (Rust → libcode_ts.so). Opt-in, because building it needs the+// Android NDK + `rustup target add aarch64-linux-android` and a generated+// code/src/main/rust/Cargo.lock. Enable in CI/on a build machine with `-PenableTreeSitter=true`.+// When disabled (the default), no .so is produced, TreeSitterNative.isAvailable is false at runtime,+// and the editor transparently falls back to the regex highlighter. Kept opt-in so ordinary builds+// (and other agents' native modules, which share the repo-root Cargo workspace) are unaffected.+if (providers.gradleProperty("enableTreeSitter").orNull == "true") {+ androidComponents {+ onVariants { variant ->+ val rustDir = layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ variant.sources.jniLibs?.addStaticSourceDirectory(rustDir)+ }+ }+ rustNativeLib("code_ts", "code")+}+ dependencies { implementation(libs.androidx.datastore.preferences) implementation(libs.jgit)
code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt
diff --git a/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.ktindex 89889fa001..486c8d48fb 100644--- a/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt+++ b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt@@ -562,12 +562,17 @@ private fun matchingBracketIndex(text: String, index: Int): Int { * When [caret] is a valid collapsed offset, the caret's line gets a subtle background and, if * the caret sits next to a bracket, that bracket and its match are highlighted. */+/** A resolved colour span `[start, end)` from the native tree-sitter highlighter. */+data class TsColorSpan(val start: Int, val end: Int, val color: Color)+ class SyntaxTransformation( private val spec: LanguageSpec?, private val colors: SyntaxColors, private val matches: List<IntRange> = emptyList(), private val activeMatch: Int = -1, private val caret: Int = -1,+ /** Structure-aware colour spans from tree-sitter; when non-null they replace the regex pass. */+ private val tsSpans: List<TsColorSpan>? = null, ) : VisualTransformation { override fun filter(text: AnnotatedString): TransformedText {@@ -585,7 +590,33 @@ class SyntaxTransformation( } val highlight = spec != null && raw.length <= MAX_HIGHLIGHT_LENGTH- if (highlight) {+ if (tsSpans != null) {+ // Rainbow brackets first; tree-sitter colours paint on top.+ if (colors.brackets.isNotEmpty()) {+ var depth = 0+ val n = colors.brackets.size+ for (i in raw.indices) {+ when (raw[i]) {+ '(', '[', '{' -> {+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ depth+++ }+ ')', ']', '}' -> {+ depth = (depth - 1).coerceAtLeast(0)+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ }+ }+ }+ }+ for (s in tsSpans) {+ val a = s.start.coerceIn(0, raw.length)+ val b = s.end.coerceIn(a, raw.length)+ if (b > a) builder.addStyle(SpanStyle(color = s.color), a, b)+ }+ for (m in TRAILING_WS_REGEX.findAll(raw)) {+ builder.addStyle(SpanStyle(background = colors.trailingWhitespace), m.range.first, m.range.last + 1)+ }+ } else if (highlight) { // Rainbow brackets first, so string/comment spec spans repaint any brackets inside them. if (colors.brackets.isNotEmpty()) { var depth = 0
code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.ktindex 1fcd43f12f..a511ab5eff 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -144,8 +144,11 @@ fun CodeEditor( val syntaxColors = rememberSyntaxColors(editorTheme) val highlightMatches = if (showFind) matches else emptyList() val caret = if (tab.value.selection.collapsed) tab.value.selection.start else -1- val transformation = remember(tab.language, syntaxColors, highlightMatches, activeMatch, caret) {- SyntaxTransformation(tab.language.spec, syntaxColors, highlightMatches, activeMatch, caret)+ val tsSpans = remember(text, tab.language, syntaxColors) {+ treeSitterColorSpans(text, tab.language, syntaxColors)+ }+ val transformation = remember(tab.language, syntaxColors, highlightMatches, activeMatch, caret, tsSpans) {+ SyntaxTransformation(tab.language.spec, syntaxColors, highlightMatches, activeMatch, caret, tsSpans) } val verticalScroll = rememberScrollState()
code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.ktindex 541b977b3e..503f4f20a3 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt@@ -54,6 +54,7 @@ import androidx.compose.ui.unit.Constraints import kotlin.math.roundToInt import com.vayunmathur.code.syntax.LanguageSpec import com.vayunmathur.code.syntax.SyntaxColors+import com.vayunmathur.code.syntax.TsColorSpan import com.vayunmathur.code.syntax.rememberSyntaxColors import com.vayunmathur.code.util.CodeActions import com.vayunmathur.code.util.Completion@@ -118,6 +119,8 @@ fun CodeEditorView( } val diagnosticsByLine = remember(diagnostics) { diagnostics.groupBy { it.line } } val spec = tab.language.spec+ // Native tree-sitter spans (cached); null → the regex tokenizer in [annotatedLine] is used.+ val tsSpans = remember(text, tab.language, colors) { treeSitterColorSpans(text, tab.language, colors) } val measurer = rememberTextMeasurer() val density = LocalDensity.current@@ -435,7 +438,7 @@ fun CodeEditorView( drawText(arrowLayout, color = gutterColor, topLeft = Offset(2f, y)) } - val annotated = annotatedLine(lineText, spec, colors)+ val annotated = annotatedLine(lineText, spec, colors, tsSpans, lineStart) val layout = measurer.measure(annotated, style) drawText(layout, topLeft = Offset(gutterWidth - scrollX, y)) @@ -491,7 +494,7 @@ fun CodeEditorView( val lineStart = lineStarts[source] val lineText = lines[source] val lineLen = lineText.length- val layout = measurer.measure(annotatedLine(lineText, spec, colors), style, constraints = wrapConstraints)+ val layout = measurer.measure(annotatedLine(lineText, spec, colors, tsSpans, lineStart), style, constraints = wrapConstraints) val blockHeight = wrapCounts[source] * lineHeight if (caret in lineStart..(lineStart + lineLen)) {@@ -706,8 +709,43 @@ private fun Minimap( } /** Tokenizes a single line with [spec] and paints rainbow brackets; returns a colored string. */-private fun annotatedLine(line: String, spec: LanguageSpec?, colors: SyntaxColors): AnnotatedString {- if (spec == null || line.isEmpty() || line.length > MAX_LINE_HIGHLIGHT) return AnnotatedString(line)+private fun annotatedLine(+ line: String,+ spec: LanguageSpec?,+ colors: SyntaxColors,+ tsSpans: List<TsColorSpan>? = null,+ lineStart: Int = 0,+): AnnotatedString {+ if (line.length > MAX_LINE_HIGHLIGHT) return AnnotatedString(line)+ // Tree-sitter path: paint the spans that fall on this line (over rainbow brackets).+ if (tsSpans != null && line.isNotEmpty()) {+ val builder = AnnotatedString.Builder(line)+ if (colors.brackets.isNotEmpty()) {+ var depth = 0+ val n = colors.brackets.size+ for (i in line.indices) {+ when (line[i]) {+ '(', '[', '{' -> {+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ depth+++ }+ ')', ']', '}' -> {+ depth = (depth - 1).coerceAtLeast(0)+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ }+ }+ }+ }+ val lineEnd = lineStart + line.length+ for (s in tsSpans) {+ if (s.end <= lineStart || s.start >= lineEnd) continue+ val a = (s.start - lineStart).coerceIn(0, line.length)+ val b = (s.end - lineStart).coerceIn(a, line.length)+ if (b > a) builder.addStyle(SpanStyle(color = s.color), a, b)+ }+ return builder.toAnnotatedString()+ }+ if (spec == null || line.isEmpty()) return AnnotatedString(line) val builder = AnnotatedString.Builder(line) if (colors.brackets.isNotEmpty()) { var depth = 0
code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.ktindex 82c063b35c..00af09b35f 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt@@ -24,7 +24,13 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupProperties import com.vayunmathur.code.R+import com.vayunmathur.code.syntax.Language+import com.vayunmathur.code.syntax.SyntaxColors+import com.vayunmathur.code.syntax.TsColorSpan import com.vayunmathur.code.util.Completion+import com.vayunmathur.code.util.TreeSitterNative+import com.vayunmathur.code.util.TsKind+import androidx.compose.ui.graphics.Color import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconChevronRight import com.vayunmathur.library.ui.IconClose@@ -186,3 +192,23 @@ private fun ToggleChip(label: String, selected: Boolean, onClick: () -> Unit) { ) } }++/** Maps a tree-sitter [TsKind] onto this theme's colours. */+fun SyntaxColors.tsColor(kind: TsKind): Color = when (kind) {+ TsKind.KEYWORD -> keyword+ TsKind.STRING -> string+ TsKind.NUMBER -> number+ TsKind.COMMENT -> comment+ TsKind.ANNOTATION -> annotation+ TsKind.FUNCTION -> function+ TsKind.TYPE -> type+ TsKind.PROPERTY -> type+}++/**+ * Native tree-sitter colour spans for [text] in [language] resolved against [colors], or null when+ * tree-sitter is unavailable / the language is unsupported — signalling the regex fallback. Blocking+ * (parses the whole file), so callers must cache it via `remember(text, language)`.+ */+fun treeSitterColorSpans(text: String, language: Language, colors: SyntaxColors): List<TsColorSpan>? =+ TreeSitterNative.spans(text, language)?.map { TsColorSpan(it.start, it.end, colors.tsColor(it.kind)) }
code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt b/code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.ktnew file mode 100644index 0000000000..c3628511bd--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt@@ -0,0 +1,73 @@+package com.vayunmathur.code.util++import com.vayunmathur.code.syntax.Language++/** A tree-sitter capture kind, aligned 1:1 (by ordinal) with the Rust side's enum. */+enum class TsKind { KEYWORD, STRING, NUMBER, COMMENT, ANNOTATION, FUNCTION, TYPE, PROPERTY }++/** A highlighted span `[start, end)` (character offsets into the source) of a given [kind]. */+data class TsSpan(val start: Int, val end: Int, val kind: TsKind)++/**+ * JNI bridge to the native tree-sitter highlighter (`libcode_ts.so`, built from+ * `code/src/main/rust/`). Loads the library once; [isAvailable] is false when the native lib is+ * missing for the current ABI (e.g. the reproducible `.so` was not built), so callers fall back to+ * the regex tokenizer instead of crashing. This mirrors the `PdfNative` graceful-degradation pattern.+ *+ * [highlight] is blocking (it parses the whole file), so callers must cache its result off the hot+ * path — see `remember(text, language)` in the editors.+ */+object TreeSitterNative {++ val isAvailable: Boolean =+ try {+ System.loadLibrary("code_ts")+ true+ } catch (t: Throwable) {+ false+ }++ /**+ * Highlights [source] for [languageId] (see [languageIdFor]), returning packed+ * `(startByte, endByte, captureKindOrdinal)` triples, or null on failure / unsupported language.+ */+ external fun highlight(languageId: String, source: String): IntArray?++ private val kinds = TsKind.entries++ /** The Rust-side language id for [language], or null when tree-sitter has no grammar for it. */+ fun languageIdFor(language: Language): String? = when (language) {+ Language.KOTLIN -> "kotlin"+ Language.JAVA -> "java"+ Language.JAVASCRIPT -> "javascript"+ Language.TYPESCRIPT -> "typescript"+ Language.PYTHON -> "python"+ Language.RUST -> "rust"+ Language.GO -> "go"+ Language.JSON -> "json"+ Language.C -> "c"+ Language.CPP -> "cpp"+ else -> null+ }++ /**+ * Structure-aware spans for [text] in [language], or null when tree-sitter is unavailable, the+ * language is unsupported, or the native call fails — signalling the caller to use the regex path.+ */+ fun spans(text: String, language: Language): List<TsSpan>? {+ if (!isAvailable) return null+ val id = languageIdFor(language) ?: return null+ val packed = runCatching { highlight(id, text) }.getOrNull() ?: return null+ val out = ArrayList<TsSpan>(packed.size / 3)+ var i = 0+ while (i + 2 < packed.size) {+ val start = packed[i]+ val end = packed[i + 1]+ val kindOrdinal = packed[i + 2]+ val kind = kinds.getOrNull(kindOrdinal)+ if (kind != null && end > start) out.add(TsSpan(start, end, kind))+ i += 3+ }+ return out+ }+}
code/src/main/rust/Cargo.toml
diff --git a/code/src/main/rust/Cargo.toml b/code/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..f0be74dd02--- /dev/null+++ b/code/src/main/rust/Cargo.toml@@ -0,0 +1,44 @@+# Native tree-sitter highlighter for the `code` app (`libcode_ts.so`, arm64-v8a).+#+# This is a STANDALONE cargo workspace (note the empty `[workspace]` table below) so it keeps its+# own Cargo.lock and does NOT join the repo-root workspace — the root's `cargo build --locked`+# builds several other native modules and must not be perturbed by this crate.+#+# Building requires the Android NDK + `rustup target add aarch64-linux-android`, and is opt-in via+# the `-PenableTreeSitter` Gradle property (see code/build.gradle.kts). When it isn't built, the app+# still runs: `TreeSitterNative.isAvailable` is false and the editor uses the regex highlighter.+#+# The grammar crate versions below must be a set that mutually agree on the tree-sitter 0.22 ABI and+# expose `LANGUAGE` (a `LanguageFn`) + a highlights query constant; run `cargo update` on a+# toolchain-equipped machine to generate the matching Cargo.lock before an `--locked` build.+[package]+name = "code_ts"+version = "0.1.0"+edition = "2021"+publish = false++[lib]+name = "code_ts"+crate-type = ["cdylib"]++[dependencies]+jni = "0.21.1"+tree-sitter = "0.22"+tree-sitter-kotlin = "0.3"+tree-sitter-java = "0.21"+tree-sitter-javascript = "0.21"+tree-sitter-typescript = "0.21"+tree-sitter-python = "0.21"+tree-sitter-rust = "0.21"+tree-sitter-go = "0.21"+tree-sitter-json = "0.21"+tree-sitter-c = "0.21"+tree-sitter-cpp = "0.22"++[profile.release]+opt-level = "z"+lto = true+strip = true++# Detach from the repo-root workspace.+[workspace]
code/src/main/rust/queries/README.md
diff --git a/code/src/main/rust/queries/README.md b/code/src/main/rust/queries/README.mdnew file mode 100644index 0000000000..e88e391ae8--- /dev/null+++ b/code/src/main/rust/queries/README.md@@ -0,0 +1,9 @@+# Highlight queries++`libcode_ts` reuses each grammar crate's **bundled** `highlights` query (exposed as a+`HIGHLIGHTS_QUERY` / `HIGHLIGHT_QUERY` constant), so there are no checked-in `.scm` files here — the+queries travel with the pinned grammar crates in `../Cargo.toml` (and are frozen by `Cargo.lock`).++If a grammar you add does not ship a highlights query, drop a `<lang>.scm` in this directory and+`include_str!` it from `src/lib.rs` instead of the crate constant. Capture names are mapped to the+editor's colour kinds by `kind_for` in `src/lib.rs`.
code/src/main/rust/src/lib.rs
diff --git a/code/src/main/rust/src/lib.rs b/code/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..ef5e18606a--- /dev/null+++ b/code/src/main/rust/src/lib.rs@@ -0,0 +1,150 @@+//! Native tree-sitter syntax highlighter for the `code` app, exposed to Kotlin via one JNI entry+//! point. It parses a whole source buffer with the appropriate grammar, runs the grammar's bundled+//! `highlights` query, and returns packed `(startByte, endByte, captureKindOrdinal)` triples that+//! [`com.vayunmathur.code.util.TreeSitterNative`] maps onto editor colours.+//!+//! The capture-kind ordinals are aligned with the Kotlin `TsKind` enum:+//! `0 keyword, 1 string, 2 number, 3 comment, 4 annotation, 5 function, 6 type, 7 property`.+//!+//! Targets the tree-sitter 0.22 API (`LanguageFn`, streaming query iterators). Byte offsets are+//! returned as-is; they line up with Kotlin string indices for ASCII/BMP text (the common case for+//! source code) — full UTF-16 mapping for astral characters is a documented v1 limitation.++use jni::objects::{JClass, JString};+use jni::sys::jintArray;+use jni::JNIEnv;+use tree_sitter::{Language, Parser, Query, QueryCursor, StreamingIterator};++/// Resolves a language id (see `TreeSitterNative.languageIdFor`) to its grammar + highlights query.+fn grammar(id: &str) -> Option<(Language, &'static str)> {+ let entry: (Language, &'static str) = match id {+ "kotlin" => (+ tree_sitter_kotlin::LANGUAGE.into(),+ tree_sitter_kotlin::HIGHLIGHTS_QUERY,+ ),+ "java" => (+ tree_sitter_java::LANGUAGE.into(),+ tree_sitter_java::HIGHLIGHTS_QUERY,+ ),+ "javascript" => (+ tree_sitter_javascript::LANGUAGE.into(),+ tree_sitter_javascript::HIGHLIGHT_QUERY,+ ),+ "typescript" => (+ tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),+ tree_sitter_typescript::HIGHLIGHTS_QUERY,+ ),+ "python" => (+ tree_sitter_python::LANGUAGE.into(),+ tree_sitter_python::HIGHLIGHTS_QUERY,+ ),+ "rust" => (+ tree_sitter_rust::LANGUAGE.into(),+ tree_sitter_rust::HIGHLIGHTS_QUERY,+ ),+ "go" => (+ tree_sitter_go::LANGUAGE.into(),+ tree_sitter_go::HIGHLIGHTS_QUERY,+ ),+ "json" => (+ tree_sitter_json::LANGUAGE.into(),+ tree_sitter_json::HIGHLIGHTS_QUERY,+ ),+ "c" => (+ tree_sitter_c::LANGUAGE.into(),+ tree_sitter_c::HIGHLIGHT_QUERY,+ ),+ "cpp" => (+ tree_sitter_cpp::LANGUAGE.into(),+ tree_sitter_cpp::HIGHLIGHT_QUERY,+ ),+ _ => return None,+ };+ Some(entry)+}++/// Maps a highlights capture name (e.g. `keyword.control`, `variable.member`) to a `TsKind` ordinal,+/// or `-1` to skip captures we don't colour.+fn kind_for(name: &str) -> i32 {+ match name.split('.').next().unwrap_or("") {+ "keyword" => 0,+ "string" | "char" => 1,+ "number" | "constant" | "float" => 2,+ "comment" => 3,+ "attribute" | "annotation" => 4,+ "function" | "method" => 5,+ "type" | "constructor" | "namespace" => 6,+ "property" | "variable" | "field" => 7,+ _ => -1,+ }+}++/// JNI: `TreeSitterNative.highlight(languageId, source): int[]` — packed span triples, or null.+///+/// # Safety+/// Called by the JVM with valid `env`/argument references.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_code_util_TreeSitterNative_highlight<'local>(+ mut env: JNIEnv<'local>,+ _class: JClass<'local>,+ language_id: JString<'local>,+ source: JString<'local>,+) -> jintArray {+ let null = std::ptr::null_mut();++ let id: String = match env.get_string(&language_id) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let src: String = match env.get_string(&source) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };++ let (language, query_src) = match grammar(&id) {+ Some(g) => g,+ None => return null,+ };++ let mut parser = Parser::new();+ if parser.set_language(&language).is_err() {+ return null;+ }+ let tree = match parser.parse(&src, None) {+ Some(t) => t,+ None => return null,+ };+ let query = match Query::new(&language, query_src) {+ Ok(q) => q,+ Err(_) => return null,+ };++ let names = query.capture_names();+ let bytes = src.as_bytes();+ let mut cursor = QueryCursor::new();+ let mut out: Vec<i32> = Vec::new();++ let mut matches = cursor.matches(&query, tree.root_node(), bytes);+ while let Some(m) = matches.next() {+ for cap in m.captures {+ let name = names[cap.index as usize];+ let kind = kind_for(name);+ if kind < 0 {+ continue;+ }+ let node = cap.node;+ out.push(node.start_byte() as i32);+ out.push(node.end_byte() as i32);+ out.push(kind);+ }+ }++ let arr = match env.new_int_array(out.len() as i32) {+ Ok(a) => a,+ Err(_) => return null,+ };+ if env.set_int_array_region(&arr, 0, &out).is_err() {+ return null;+ }+ arr.into_raw()+}