perf(lexer): O(N^2) -> O(N) tokenizer — self-compile 320s -> 28s#16
Merged
Conversation
The lexer helpers used `length cs == 0` as their empty-check. _rail_length walks the whole list, so that test is O(remaining) PER recursion step. The main loop `tc` recurses once per token over the remaining char list, making it O(chars x tokens) ~ 2.7e10 on the 551K-char compile.rail -- ~297s, 92% of the entire self-compile. `rev` (over ~100K tokens), `strip_nl_pp_loop`, `lx_str`/`lx_col` (long string/word spans) compounded it. Switched 10 empty-checks (tc, rev_acc, strip_nl_pp_loop, lx_str, lx_col, lx_skip, lx_pk, htint_acc, has + one `length (tail cs) > 0`) to `== []` / `!= []` (O(1)). Byte-identical: same tokens out -> same parse -> same codegen. Measured: tokenize 297s -> sub-second; self-compile 320s -> 28s (~11x). 177/177 tests; 2-pass self-host fixed point byte-identical (rail_native reseeded). Not audit-resolve-specific -- the lexer was always O(N^2); compile.rail growing to 551K chars made it dominant. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The lexer used
length cs == 0as its empty-check; _rail_length walks the whole list, so the main looptc(recursing per-token over remaining chars) was O(chars x tokens) ~2.7e10 on the 551K-char compile.rail = ~297s, 92% of every self-compile. Switched 10 empty-checks to== [](O(1)). Byte-identical (same tokens).Measured: self-compile 320s -> 28s (~11x). 177/177 tests. 2-pass fixed point byte-identical (reseeded). The lexer was always O(N^2); compile.rail growing to 551K chars made it dominant.
🤖 Generated with Claude Code