Summary. In November 2026 I replaced the engine behind RibbonDiff's syntax highlighter. Each language's regex rules are now compiled automatically into a small bidirectional recurrent network built from clipped linear units, and the network is compiled to C. Nothing is trained. The goal, checked against the real regex highlighter, is identical output.

  • 27 languages have a network. 26 use it by default; plain text stays on regex, and C, C++ and Objective-C use regex for short texts.
  • On large inputs on an Apple M1 Max, the network was faster than the regex rules in 23 of 24 languages measured, by 2.4× to 17×. In a separate re-run on two large JavaScript files, read as JavaScript and as TypeScript, it was 7.6× to 9.5× faster, with zero differing units.
  • It is not the fastest highlighter that exists. Highlights, a WebAssembly lexer, publishes 13.5 ns per character on different hardware, and hand-written lexers or tree-sitter are the conventional choice. On short texts the network can be slower than the regex rules.
  • The idea comes from alpindale/lexnet on Hugging Face.

Where it started

RibbonDiff is a Mac diff app with a highlighter written in Swift. It found keywords, numbers and similar tokens with ICU's regular expressions (NSRegularExpression) and strings and comments with small hand-written scanners. Each match becomes a span, a range with a kind such as "string", and spans are painted in a fixed priority order. Those rules are the specification.

The starting point for the change was alpindale/lexnet, a Hugging Face repository that highlights C source code with a neural network. Its model card describes a bidirectional recurrent network (one pass in each direction) that outputs one class per byte, using Clip(x, 0, hi) activations in float64, with about 984 non-zero parameters. It lists no training data; the card states the weights were generated by Anthropic's Claude Fable 5.1. It compiles the network to C and reports 88 ns per character for that kernel on an Apple M4 Pro.

That network targets one language. I wanted a compiler: feed it RibbonDiff's existing regex rules for a language and get back a network that computes exactly the same coloring. I call the result lexnet too, because it follows the same approach. Like the original, it was built with Fable: I set the direction and judged the results, and Fable wrote most of the code.

Regex rules+ string/comment scanners Parse treeICU subset only NFAwith ordered paths Recurrent cellsF0, B1, F1, …, P Weightssparse, deflated Generated C kernelscalar + 64-lane Class per unit→ spans → colors Oraclethe app's highlighter compare every UTF-16 unit; any difference is a compiler bug
Figure 1. From the regex rules to colored spans. The left-hand oracle is the app's own highlighter source built as a command-line tool, using the real NSRegularExpression.

Why call it a neural network

Structurally it is one: a fixed embedding turns each character into a feature vector, layers of weighted sums and an activation process it, recurrent cells scan the text in both directions, and a linear head picks the highest-scoring class at each position. What it lacks is training. There is no dataset and no gradient descent; a compiler computes every weight from the regex rules.

Every unit computes one thing:

value = clip(bias + Σ wᵢ·xᵢ, 0, hi)

The clip, a ReLU also capped at hi, is the only activation. With 0/1 inputs and integer weights, clip(sum, 0, 1) asks "is the sum at least 1?", which makes the unit a logic gate: AND, OR and NOT differ only in weights and bias, and clip(x − k + 1, 0, 1) tests x ≥ k.

AND: clip(a + b − 1, 0, 1) OR: clip(a + b, 0, 1) absumoutput absumoutput 00−10 0100 1000 1111 0000 0111 1011 1121 Negative sums clip to 0; sums above 1 clip to 1. Integers in, so no values in between.
Figure 2. The same unit becomes AND or OR depending only on its bias.

With hi = ∞ a unit is an integer register for counters and word hashes. A bounded value can be gated by a 0/1 flag: with B = 2^50, clip(−B + x + B·g, 0, ∞) is x when g = 1 and 0 otherwise. Values are float64, but only integers below 2^53 ever appear, so nothing is rounded.

Input is one UTF-16 code unit per step, mapped to one of 154 rows: 128 for ASCII, 23 for the combinations of ICU character classes that non-ASCII characters actually fall into, and three special rows. Each row has a fixed vector of yes/no features such as "is \w".

A cell is a stack of layers that scans the whole text in one direction, passing state from position to position and leaving per-position outputs for later cells. Backward cells are needed because regex semantics depend on the future: whether a pattern can still complete from here, lookaheads, $, and keywords, which are only recognized at their last character and must be spread back over the word. A generated network runs cells in a fixed order: F0 (forward: word boundaries, lookbehinds, the string and comment scanners, a shared word hash), then B1/F1 pairs per stage of patterns, then a final backward painting cell P with the output head.

Compiling one regex

Take the pattern for a double-quoted string, "[^"\n]*", and the text x = "ab" if. The answer is the four units at positions 4 to 7.

A parser turns the pattern into a syntax tree, rejecting any ICU feature it does not implement rather than guessing. The tree then becomes an NFA (a nondeterministic finite automaton: states, and arrows that consume a character) in which each state consumes exactly one character. The non-consuming branches of alternation and repetition are expanded ahead of time into a list of paths from each state to the next consuming state. The order of that list is the regex's priority order: a|b lists a first, greedy * lists "loop again" before "exit", and lazy *? lists "exit" first.

A backtracking engine such as ICU tries paths in priority order and backs up when one fails. If you knew in advance which paths can still succeed, you could take the best of those directly and land where the backtracking engine lands. That knowledge is a backward recurrence:

canC[q][i] = char[i] ∈ set(q)  AND  some path from q is viable at i+1
viable(path, j) = conditions hold at j AND (target is accept OR canC[target][j])

canC means "state q can read the character at i and the pattern can still complete". It depends only on the text to the right, so the backward cell B1 computes it. Then the forward cell F1 runs a single deterministic thread per pattern, which at each step takes the first viable path. It is neither a set-of-states NFA simulation nor a DFA; the backward pass makes one thread enough and gives exact leftmost-first semantics. Greedy and lazy behavior follow from the path order alone.

position text B1: close B1: content B1: canStart F1: thread P: class 012345678910 x␣=␣"ab"␣if 00001001000 11110110000 00001000000 ······· openbodybodyclose string B1 runs right to left first; F1 then runs left to right reading B1's outputs.
Figure 3. Backward and forward cells for "[^"\n]*". Positions 0 to 3 are marked as possible string content because a quote follows them, but no string can start there, so the forward thread ignores them. The quote at 7 cannot open a string because no closing quote follows. Values worked out from the recurrences in the text.

Matches must not overlap, as with NSRegularExpression, which the net expresses as idle = canStart AND NOT busy. Capture groups are tracked with open and close events, including ICU's habit of reporting only the last iteration of a repeated group.

Keywords and span priority

Compiled naively, \b(if|for|while)\b needs one NFA state per keyword character, and a language with dozens of keywords needs hundreds. Instead, the first forward cell computes one hash per word that every pattern in the language shares. Digits map to 1–10, A–Z to 11–36, a–z to 37–62 and _ to 63, and inside a word h = 65·h + code. Since no code is 0, the value identifies both the letters and the length. The hash is split into chunks of seven characters to stay below 2^53 (65^7 is about 4.9·10^12), and the generic net keeps four chunks, so words longer than 28 characters never count as keywords. if hashes to 45·65 + 42 = 2967.

The comparison runs only at the last character of a word, and a backward cell carries the result across the word. A rewrite pass recognizes when an alternation of plain words, bounded by \b or an equivalent, is really "the longest run of word characters here is in this set", and replaces it with a single word-set state. Across the app's 155 patterns this cut consuming NFA states from 3,838 to 1,572; Swift's keyword pattern went from 380 states to 1. With a small set, though, the shared hash costs more than it saves: three keywords grew from 118 to 128 units.

Spans from different patterns overlap, and the app paints them in a fixed order. The net reproduces which span ends up on top by packing the painting order into one integer key per span and taking the minimum at each position:

key = 2^52·(1 − live) + 2^50·[not a comment] + 2^27·age + 32·rem + (13 − kind)

Here age counts units since the span started, rem counts units until it ends, and kind is the span type. The minimum of two values needs two ReLUs, min(a, b) = a − relu(a − b), so a knockout tournament over n spans costs about 2n units. The first generic net compared every pair of spans instead, which in TypeScript took 71% of the time and 7,041 units in the painting cell; the tournament needs 788.

Keeping it exact

None of this is proven correct. Instead, the answer is always the app's real code: the oracle is the app's highlighter source compiled unmodified into a command-line tool, with the real NSRegularExpression. All 155 patterns in the app match it on random texts. Each whole language is checked unit by unit on golden sample files and random text that includes non-ASCII characters. The C, C++ and Objective-C kernels were run over three sets of SDK headers (one of them 3,174 files, about 23.7 million units) with zero mismatches. Every optimization switched on and off gives byte-identical output. Every speed-up below computes the same function in a different form; a differing output is a bug, not an approximation.

What random testing missed

On 2026-11-13 two differences turned up that random text had not found, because they need shapes that real code has and random characters almost never form.

The first was nested JavaScript and TypeScript template strings. In one generated TypeScript file the net and the regex rules disagreed on 980 units. The app's scanner treats a ' inside ${…} as the start of a string, so an ordinary line such as `'${c.name}:${c.summary.replace(/'/g, "")}'` flips which backticks open and close templates, and the nesting reaches deeper levels. The net only tracked two levels at that point. I raised it to three, and added a fuzzer that generates nested templates from the grammar, plus a small corpus of such cases.

The second was in the compiler. Nested possessive repetition (*+) is simulated differently from ICU; the smallest example, \((?:a|\((?:a|\(a\))*+\))*+\), fails to match (a(a(a))). A C attribute rule hit this on 83 SDK headers. In that rule no alternative contains a closing parenthesis, so a greedy * means the same thing, and I rewrote the app's rule that way. The compiler itself is still not fixed.

In both cases the oracle was right; what was missing was test text with the right shape.

Making it fast

The first numbers are from the first C-family net, which was specified unit by unit before the compiler existed, measured inside the app on about 200 KB of C-like text (2026-11-05, M1 Max). A generic sparse-matrix interpreter took 1,407 ns per character, against 273 for the regex rules. Generating straight-line code with the weights baked in, where units proven to be 0/1 become bool with &&, || and !, gave 173 ns in Swift and 91 in C. The C kernels are compiled with -O2 even in Debug builds, because at -O0 they were five times slower than the regex rules.

Guards and lazy blocks

Most units are irrelevant at most positions. A guard is a promise that a unit is 0 whenever its guard input is 0, so the generator wraps guarded units in an if (g) { … } block whose outputs default to 0; skipping it gives the same value as computing it. For Swift's keyword pattern alone, removing all guards took it from 15.9 to 68.2 ns per unit. Later rounds added automatic guards, merging units that provably compute the same value (the idea behind DFA minimization), dead-unit removal and sparse weight storage.

64 lanes with speculative chunk starts

A 0/1 unit needs one bit per position, so a 64-bit register can hold 64 positions at once. The 64-lane kernel cuts the text into up to 64 equal chunks and gives chunk l bit l of every word. One instruction then evaluates a unit for all 64 chunks:

// one bit per lane; lane l = chunk l of the text
uint64_t pw_new = x_w & ~x_ext;     // was: bool pw_new = x_w && !x_ext;
uint64_t g = canStart;
if (g) { /* evaluate the guarded block only for lanes set in g */ }

Each chunk needs the recurrent state at its start, which is only known after the previous chunk has run, so each lane guesses. It starts K = 16 units early from the initial state, betting that state depends on recent characters only, and snapshots its state every M = 32 units. Afterwards the true end states are passed along and compared with each guess, field by field. A wrong lane is re-run from the true state until it matches a snapshot (it has merged); from there on its earlier results are correct. A wrong guess costs time, never correctness.

text → lane 0lane 1lane 2lane 3lane 4lane 5lane 6lane 7 re-run until merge, then keep warm-up of K units (guess) computed in parallel wrong guess, re-run After the parallel sweep, each lane's guessed start state is checked against the previous lane's true end state.
Figure 4. Eight of the 64 lanes, with the warm-up exaggerated. Most lanes guess their start state correctly; lane 3 does not and is re-swept only as far as the point where it merges with its earlier run.

Moving 21 languages to this kernel made the 24 languages that had nets at the time 2.41 times faster in the app (geometric mean, M1 Max, Debug build with -O). It also made clean builds slower: Debug went from 32 to 67 seconds and Release from 90 to 123, with the TypeScript kernel alone taking about 15 seconds.

Where the time went

After that step JavaScript still took about 180 ns per unit, so I profiled the 64-lane kernel in a standalone C harness (clang -O2, single thread, M1 Max, median of 5 to 7 runs) on a minified input of about 5.6 million units:

Wherens per unitShare
Numeric units (hashes, keyword comparisons, counters, priority keys) computed one lane at a time in doubles≈11564%
The B1 cell still running scalar, plus reshaping its output into lanes33.118%
0/1 logic, the part actually running 64-wide≈148%
Re-running mispredicted lanes10.86%
Transposing input features into lanes6.94%
Zeroing export buffers5.43%
Whole kernel181

The boolean logic was cheap; the numbers were not. Four further steps attacked that, each with output identical to the scalar kernel:

  1. Integer bit-planes. An integer is stored as a few 64-bit words, where word b holds bit b of the value for all 64 lanes. Addition and comparison become logic circuits that run 64-wide; for example, p0' = p0 ^ c; c = p0 & c; is the first stage of adding c to every lane at once. Counters get 22 planes, and any text whose values would overflow is recomputed with the scalar kernel. Kernel: 182 → 131 ns per unit (the profile run above measured 181).
  2. Keyword lookup by table. The tree of hash comparisons is replaced by one lookup in a collision-free table, done once per word end in the first cell, with the result passed on as bits. 131 → 91.
  3. An exact start-state pre-pass. Guessing failed for JavaScript's B1, which looks arbitrarily far ahead for template literals: 63 of 63 lanes guessed wrong, and the kernel slowed from about 91 to 110. When a cell's state is all 0/1 and its inputs are character features only, one step is a fixed remapping of state bits per input. The generator composes these into one entry-to-exit map per chunk and chains the maps from the text edge, which gives every chunk's true start state. 91 → 65 on minified code, 79 → 54 on readable code.
  4. Lane-wise blocks and a proven bound. Numeric guarded blocks are skipped, run lane by lane, or run as plane circuits depending on how many lanes need them. A reachability search proves the largest value a word hash can take, so SQL stopped falling back to scalar (164 ns per unit before).

Things I tried and dropped, all exact but not faster: packing boolean state into bit fields (TypeScript 505 → 635 ns per unit), branch-free &/| logic, a binary-tree keyword search, guarded numeric blocks for Lua and YAML (3–5% slower), and new cell configurations for seven languages that did not beat the noise over 15 interleaved runs.

For scale: on the same machine and input, a minimal lexer that only runs a 16-state DFA over a character-class table took about 2 ns per unit, and about 0.8 with 64 copies interleaved. The JavaScript net runs ten cells over the text and reads and writes hundreds of bits of state per position. That cost is structural.

0 500 1,000 1,500 ns per character, in the app (smaller is faster) In-app, first generic net 1,799 After round 1 643 After round 2 533 After round 3 530 64 lanes 174 Bit-planes etc., golden 49.6 Same kernel, real files 116.5 Regex rules 828
Figure 5. The TypeScript net in the app across the optimization rounds (ns per character, M1 Max; stages measured on different days, the last ones in a Debug build with -O). The last two net bars are golden files and real files from disk.

Results

The most recent per-language table I measured the same way for every language is from 2026-11-10. It ran inside the app on an Apple M1 Max, Debug build with -O, on each language's golden files concatenated to at least 200,000 units, median of 15 runs. The load average was 4.5–5.0, and an unchanged control kernel varied by ±3.6%, so differences of a few percent are noise. The cLike row (the fallback for C-like files of unknown dialect) is that first, individually specified net, still in use at the time; the C, C++ and Objective-C nets came on 2026-11-13 and are not included.

lexnet (net) regex rules 0 200 400 600 800 ns per UTF-16 unit (smaller is faster) toml 27.9 475.3 typescript 49.6 829.2 dotenv 19.0 309.9 sql 43.8 682.1 csharp 39.9 583.8 ada 30.2 437.9 kotlin 31.4 437.5 php 48.7 646.3 javascript 50.1 591.7 rust 35.5 337.5 go 34.3 323.0 dart 53.0 484.0 python 93.3 731.9 css 27.4 210.7 lua 30.3 185.6 java 60.7 291.9 yaml 33.3 142.9 swift 64.8 249.3 json 20.6 67.5 ruby 162.3 508.6 shell 53.4 166.8 cLike 49.2 130.1 dockerfile 58.0 136.5 plain 10.4 9.1
Figure 6. lexnet versus the regex rules for the 24 languages that had a net on 2026-11-10, sorted by ratio. Large inputs only; see the limits section for short texts.
Languagelexnetregexregex ÷ lexnet
toml27.9475.317.0
typescript49.6829.216.7
sql43.8682.115.6
javascript50.1591.711.8
rust35.5337.59.5
python93.3731.97.8
java60.7291.94.8
swift64.8249.33.8
ruby162.3508.63.1
dockerfile58.0136.52.4
plain10.49.10.9

ns per character (UTF-16 unit), median of 15. A selection of the 24 rows; Figure 6 has all of them. The sum over all 24 languages was 1,127 ns for lexnet.

Against other highlighters

On 2026-11-14 I re-ran a comparison on the same Mac Studio (M1 Max, macOS 27.2, Release build, C at -O2, JavaScript engines on node 22, all single-threaded, median of three rounds, load average 3.3–6.3). The inputs were ten copies of a minified library (5,642,010 units, lines up to 563,748 units long) and five copies of a readable one (5,520,910 units).

EngineSame output as RibbonDiff's rulesMinifiedReadable
lexnet javascript, app pathyes, 0 units differ7160
lexnet typescript, app pathyes, 0 units differ8068
RibbonDiff regex rules (javascript)reference589456
RibbonDiff regex rules (typescript)reference758574
tree-sitter 0.26.7, parse onlyno, different grammar14566
tree-sitter + highlights queryno, different grammar260114
highlight.js 10.7.3, no HTMLno, different rules343158
CodeMirror 5.58.2 runModeno, different rules1,00688
Pygments 2.14.0no, different rules1,013461
Prism 1.30.0 tokenizeno, different rules2,842373

ns per UTF-16 unit. tree-sitter's query predicates were not evaluated, so that row is slightly light. Speed Highlight (29 on minified) and vscode-textmate (about 93,300 on minified) are left out of this table: the first misread half of the minified file as one comment, and the second was measured on one copy only.

On these inputs lexnet was the fastest engine I measured and 7.6 to 9.5 times faster than the rules it reproduces. On a generated corpus of 12 languages plus cLike it was 2.4 times (JSON) to 10.9 times (TypeScript) faster than the regex rules, and the fastest engine in 7 of the 12 languages. For Python and Objective-C, Prism or highlight.js ran about twice as fast; for Java, Speed Highlight was faster; Rust and Swift were roughly even. Those engines apply their own, usually simpler, rules, so none of this compares engines that give the same answer.

Limits, and whether it was worth it

  • Short texts. Below a per-language length (512 to 8,192 units) the scalar kernel runs, and some scalar kernels are slower than the regex rules. On 2026-11-13, with generated files cut to 1k to 30k units, the net lost at small sizes in six languages (cLike, YAML, Ruby, JSON, shell, Dockerfile); YAML at 1k took 222 ns per unit against 108. Only C, C++ and Objective-C route short texts to regex so far.
  • Languages without a net. Plain text keeps the regex rules by default, because they are already very cheap (9.1 against 10.4 ns). XML and Markdown have no net at all: they embed other languages, which the compiler does not reproduce, and an attempt broke 23 tests.
  • The one known difference. JavaScript and TypeScript template strings are tracked to three levels of nesting, with brace depth limits of 4, 3 and 1 per level; beyond that the net and the regex rules disagree. Matching backticks needs a stack, and a finite cell can only emulate a fixed depth; three levels already took that cell from 79 to 195 states.
  • Compiler gaps. Nested possessive repetition is wrong in the compiler and worked around in the rules; backreferences and atomic groups are not supported because no rule uses them. The character class tables depend on the Unicode version of macOS's ICU.
  • Size and build cost. The 27 weight files total 516,037 bytes, but the generated C is 731,888 lines across 27 files, and adding the 64-lane kernels roughly doubled clean Debug build time at the time. Two kernels' x86_64 builds stalled the compiler during archiving until I disabled vectorization for that architecture. The app only colors texts up to 1,000,000 UTF-16 units per side, and the 64-lane kernel uses about 200 bytes of scratch memory per unit while it runs.
  • Unexplained. On real files from disk, TypeScript took 116.5 ns per character and JavaScript 109.2, more than twice their golden-file figures, and I have not found out why. Golden files are small and cover every construct, so they are not typical code.

If speed were the only goal, I would not have built this. A hand-written lexer per language, or tree-sitter, is the conventional answer. The reason to do it this way is that the regex rules stay the single source of truth. I edit a rule, the compiler emits a new net and kernel, and the oracle confirms the output is identical. Users see the same colors as before, only computed faster, and the old engine remains available as a reference and fallback. The cost is a large amount of generated code, a long build, and a compiler that has to be right about ICU semantics; when it is not, a rule has to be rewritten.

Next time I would build the realistic test corpus before the random fuzzers, since both real mismatches came from shapes random text does not produce, and measure on real files much earlier.

Credits

The approach comes from alpindale/lexnet: a per-character bidirectional recurrent network of clipped units for C highlighting, with weights that were never trained, and a code generator that compiles the network to C. My work generalizes it into a compiler from existing regex rules, adds the exactness checks against the original highlighter, and adds the 64-lane kernels. The comparison figures for gpu-lexer, Highlights and the other browser engines are the gpu-lexer project's published numbers, not my measurements.

The highlighter ships in RibbonDiff 4.2.9.