Skip to content

Accelerate lexer fallback and parser deduplication - #111

Merged
tinovyatkin merged 4 commits into
mainfrom
codex/resume-compiled-lexer-escapes
Jul 18, 2026
Merged

Accelerate lexer fallback and parser deduplication#111
tinovyatkin merged 4 commits into
mainfrom
codex/resume-compiled-lexer-escapes

Conversation

@tinovyatkin

@tinovyatkin tinovyatkin commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Summary

  • preserve narrowed ATN configs when compiled lexer DFA construction encounters a dynamic escape edge
  • resume interpretation at that edge instead of restarting from the lexer mode's full start closure
  • replace quadratic clean parser-outcome scans with an adaptive inline/dense/sparse deduplicator
  • retain parser-owned bitmap and hash scratch across recursive recognizer calls
  • expose perf counters for deduplication inputs, removals, representation choices, and dense words

Closes #108.

Root causes

Compiled lexer fallback

The compiled lexer escaped at predicate-sensitive edges, then rematched the token from the mode start. For the MySQL lexer, that rebuilt a closure spanning roughly 900 rules for each dynamic edge.

The lexer now captures configs immediately after the escaped consuming transition and before its dynamic epsilon closure. The interpreter resumes from those narrowed configs while preserving semantic predicates, actions, recursive rule stacks, longest-match accepts, and recognition-error spans.

Clean parser outcome deduplication

Large VALUES lists produced compact, ordered endpoint ranges. The clean fast recognizer stored the first eight endpoints inline, then linearly scanned an overflow Vec for every subsequent endpoint. Statement 44 spent 27.7% of total sampled time in that quadratic scan even though almost every endpoint was unique.

The replacement chooses from the observed data shape:

  • up to 8 outcomes: stack-inline scan
  • compact endpoint span: direct bitmap with two bits per token index, capped at 64 KiB
  • wide sparse span: reusable FxHashSet<(usize, bool)>

Vec::retain preserves first-discovered greedy ordering, and the key keeps ordinary and EOF-consuming outcomes distinct. Bitmap words are cleared through a touched-word list, so scratch reuse does not scan the full retained capacity.

Both runtime and codegen changes remain grammar-agnostic.

Performance

Exact same-host parser A/B, d57174505 versus bc9ee21ad:

Fixture Before After Change
Sakila statement 44 parse 617.5 ms 280.0 ms 2.21x faster
Full workload warm total 4.19 s 3.19-3.29 s about 23% faster
Sakila warm total 3.40 s 2.41 s about 29% faster

Synthetic bulk-VALUES parse scaling:

Rows int7 before int7 after payment before payment after
1,000 28.3 ms 26.4 ms 25.5 ms 24.3 ms
2,000 55.9 ms 49.2 ms 57.4 ms 49.3 ms
4,000 125.4 ms 98.2 ms 131.0 ms 98.4 ms
8,000 312.8 ms 186.8 ms 324.6 ms 191.5 ms
12,000 591.2 ms 264.5 ms 587.3 ms 272.1 ms

The 12k payment fixture recorded 2.33 million clean endpoint inputs: 2.35 million calls stayed inline, 15 large lists used the dense bitmap, and none required sparse hashing. A three-run statement-44 profile reduced clean deduplication from 27.7% to 1.36% of total self samples.

The previously recorded C++ workload total on this host is 2.96 s; current Rust is 3.19-3.29 s.

Validation

  • cargo test --locked --all-targets --all-features
  • cargo clippy --locked --all-targets --all-features -- -D warnings
  • cargo run --release --quiet --bin antlr4-runtime-testsuite (357 passed, 0 failed, 0 skipped)
  • protected parse benchmark against the exact pre-change head (12/12 under 1.15x, 0.9984x geomean, 1.0305x worst fixture)
  • full MySQL benchmark corpus (1,509 statements, zero errors)
  • focused inline, dense, sparse, ordering, EOF distinction, and scratch-reuse tests
  • git diff --check

@github-actions

github-actions Bot commented Jul 18, 2026

Copy link
Copy Markdown

Copy/Paste Detection

Found 25 duplication(s) across 3 changed Rust file(s) (threshold: 100 tokens).

Show duplications

Found a 54 line (320 tokens) duplication in the following files:

  • Starting at line 475 of src/atn/lexer.rs
  • Starting at line 546 of src/atn/lexer.rs
    atn: &LexerAtn,
    hooks: &mut H,
    mut generated_action: A,
    mut generated_predicate: P,
    unknown_policy: UnknownSemanticPolicy,
    mut accept_adjuster: E,
) -> Result<TokenId, TokenStoreError>
where
    I: CharStream,
    H: SemanticHooks,
    A: FnMut(&mut BaseLexer<I>, LexerCustomAction) -> bool,
    P: FnMut(&BaseLexer<I>, LexerPredicate) -> Option<bool>,
    E: FnMut(&mut BaseLexer<I>, i32, usize),
{
    let hooks = RefCell::new(hooks);
    let token = next_token_with_hooks_impl(
        lexer,
        sink,
        atn,
        &mut |lexer, action| {
            if !generated_action(lexer, action)
                && !dispatch_lexer_action_hook(&hooks, lexer, action)
                && unknown_policy == UnknownSemanticPolicy::Error
                && let (Ok(rule), Ok(index)) = (
                    usize::try_from(action.rule_index()),
                    usize::try_from(action.action_index()),
                )
            {
                lexer.record_semantic_error(true, rule, index);
            }
        },
        &mut |lexer, predicate| {
            generated_predicate(lexer, predicate)
                .or_else(|| dispatch_lexer_predicate_hook(&hooks, lexer, predicate))
                .unwrap_or_else(|| match unknown_policy {
                    UnknownSemanticPolicy::AssumeTrue => true,
                    UnknownSemanticPolicy::AssumeFalse => false,
                    UnknownSemanticPolicy::Error => {
                        lexer.record_semantic_error(
                            false,
                            predicate.rule_index(),
                            predicate.pred_index(),
                        );
                        false
                    }
                })
        },
        &mut |lexer| dispatch_lexer_before_token_hook(&hooks, lexer),
        &mut accept_adjuster,
        &mut |lexer, accept_position| {
            dispatch_lexer_after_accept_hook(&hooks, lexer, accept_position);
        },
        LexerMatchStrategy {
            compiled: None,

Found a 26 line (153 tokens) duplication in the following files:

  • Starting at line 197 of src/atn/lexer.rs
  • Starting at line 611 of src/atn/lexer.rs
pub fn next_token_with_hooks<I, A, P, E>(
    lexer: &mut BaseLexer<I>,
    sink: &mut TokenSink<'_>,
    atn: &LexerAtn,
    mut custom_action: A,
    mut semantic_predicate: P,
    mut accept_adjuster: E,
) -> Result<TokenId, TokenStoreError>
where
    I: CharStream,
    A: FnMut(&mut BaseLexer<I>, LexerCustomAction),
    P: FnMut(&BaseLexer<I>, LexerPredicate) -> bool,
    E: FnMut(&mut BaseLexer<I>, i32, usize),
{
    next_token_with_hooks_impl(
        lexer,
        sink,
        atn,
        &mut custom_action,
        &mut semantic_predicate,
        &mut |_| {},
        &mut accept_adjuster,
        &mut |_, _| {},
        LexerMatchStrategy {
            compiled: None,
            use_cache: false,

Found a 27 line (145 tokens) duplication in the following files:

  • Starting at line 14305 of src/parser.rs
  • Starting at line 14438 of src/parser.rs
    fn generated_match_token_recovers_missing_token_from_context_follow() {
        let atn = generated_match_recovery_atn();
        let data = RecognizerData::new(
            "Mini.g4",
            Vocabulary::new(
                [None, Some("'X'"), Some("'Y'")],
                [None, Some("X"), Some("Y")],
                [None::<&str>, None, None],
            ),
        );
        let mut parser = BaseParser::new(
            CommonTokenStream::new(Source {
                tokens: vec![TestToken::eof("parser-test", 3, 1, 3)],
                index: 0,
            }),
            data,
        );
        parser.rule_context_stack = vec![
            RuleContextFrame {
                rule_index: 0,
                invoking_state: 0,
            },
            RuleContextFrame {
                rule_index: 1,
                invoking_state: 1,
            },
        ];

Found a 25 line (142 tokens) duplication in the following files:

  • Starting at line 319 of src/atn/lexer.rs
  • Starting at line 428 of src/atn/lexer.rs
    atn: &LexerAtn,
    hooks: &mut H,
) -> Result<TokenId, TokenStoreError>
where
    I: CharStream,
    H: SemanticHooks,
{
    let hooks = RefCell::new(hooks);
    let token = next_token_with_hooks_impl(
        lexer,
        sink,
        atn,
        &mut |lexer, action| {
            let _ = dispatch_lexer_action_hook(&hooks, lexer, action);
        },
        &mut |lexer, predicate| {
            dispatch_lexer_predicate_hook(&hooks, lexer, predicate).unwrap_or(true)
        },
        &mut |lexer| dispatch_lexer_before_token_hook(&hooks, lexer),
        &mut |_, _, _| {},
        &mut |lexer, accept_position| {
            dispatch_lexer_after_accept_hook(&hooks, lexer, accept_position);
        },
        LexerMatchStrategy {
            compiled: None,

Found a 23 line (138 tokens) duplication in the following files:

  • Starting at line 1003 of src/atn/lexer.rs
  • Starting at line 1303 of src/atn/lexer.rs
        let mut next = Vec::new();
        for config in active {
            let Some(state) = atn.state(config.state) else {
                continue;
            };
            for transition in &state.transitions {
                if !transition.matches(symbol, MIN_CHAR_VALUE, MAX_CHAR_VALUE) {
                    continue;
                }
                let mut advanced = config.clone();
                set_config_state(atn, &mut advanced, transition.target());
                if symbol == EOF {
                    advanced.consumed_eof = true;
                } else {
                    advanced.position += 1;
                }
                next.push(advanced);
            }
        }

        let closure = epsilon_closure(atn, next, &mut |predicate| {
            semantic_predicate(lexer, predicate)
        });

Found a 24 line (136 tokens) duplication in the following files:

  • Starting at line 886 of src/atn/lexer.rs
  • Starting at line 1003 of src/atn/lexer.rs
        let source_has_semantic_context = dfa_state_has_semantic_context;
        for config in active {
            let Some(state) = atn.state(config.state) else {
                continue;
            };
            for transition in &state.transitions {
                if !transition.matches(symbol, MIN_CHAR_VALUE, MAX_CHAR_VALUE) {
                    continue;
                }
                let mut advanced = config.clone();
                set_config_state(atn, &mut advanced, transition.target());
                if symbol == EOF {
                    advanced.consumed_eof = true;
                } else {
                    advanced.position += 1;
                }
                next.push(advanced);
            }
        }

        let closure = epsilon_closure(atn, next, &mut |predicate| {
            semantic_predicate(lexer, predicate)
        });
        let target_has_semantic_context = closure.has_semantic_context;

Found a 24 line (134 tokens) duplication in the following files:

  • Starting at line 2851 of src/atn/lexer.rs
  • Starting at line 1332 of src/atn/lexer_dfa.rs
        let atn = AtnDeserializer::new(&SerializedAtn::from_i32(&[
            4, 0, 2, // version, lexer, max token type
            9, // states
            6, -1, // 0 token start
            2, 0, // 1 rule 0 start
            1, 0, // 2
            1, 0, // 3
            7, 0, // 4 rule 0 stop
            2, 1, // 5 rule 1 start
            1, 1, // 6
            1, 1, // 7
            7, 1, // 8 rule 1 stop
            0, // non-greedy
            0, // precedence
            2, // rules
            1, 1, // rule 0 starts at 1, token type 1
            5, 2, // rule 1 starts at 5, token type 2
            1, // modes
            0, // default mode starts at 0
            0, // sets
            8, // edges
            0, 1, 1, 0, 0, 0, // start -> rule 0
            0, 5, 1, 0, 0, 0, // start -> rule 1
            1, 2, 5, 'a' as i32, 0, 0, 2, 3, 5, 'b' as i32, 0, 0, 3, 4, 1, 0, 0, 0, 5, 6, 5,

Found a 23 line (129 tokens) duplication in the following files:

  • Starting at line 886 of src/atn/lexer.rs
  • Starting at line 1303 of src/atn/lexer.rs
        let source_has_semantic_context = dfa_state_has_semantic_context;
        for config in active {
            let Some(state) = atn.state(config.state) else {
                continue;
            };
            for transition in &state.transitions {
                if !transition.matches(symbol, MIN_CHAR_VALUE, MAX_CHAR_VALUE) {
                    continue;
                }
                let mut advanced = config.clone();
                set_config_state(atn, &mut advanced, transition.target());
                if symbol == EOF {
                    advanced.consumed_eof = true;
                } else {
                    advanced.position += 1;
                }
                next.push(advanced);
            }
        }

        let closure = epsilon_closure(atn, next, &mut |predicate| {
            semantic_predicate(lexer, predicate)
        });

Found a 27 line (127 tokens) duplication in the following files:

  • Starting at line 13325 of src/parser.rs
  • Starting at line 13397 of src/parser.rs
        let mut atn = ParserAtnBuilder::new(2);
        assert_eq!(
            atn.add_state(AtnStateKind::RuleStart, Some(0))
                .expect("state")
                .index(),
            0
        );
        assert_eq!(
            atn.add_state(AtnStateKind::BlockStart, Some(0))
                .expect("state")
                .index(),
            1
        );
        assert_eq!(
            atn.add_state(AtnStateKind::Basic, Some(0))
                .expect("state")
                .index(),
            2
        );
        assert_eq!(
            atn.add_state(AtnStateKind::Basic, Some(0))
                .expect("state")
                .index(),
            3
        );
        assert_eq!(
            atn.add_state(AtnStateKind::BlockEnd, Some(0))

Found a 33 line (126 tokens) duplication in the following files:

  • Starting at line 8169 of src/parser.rs
  • Starting at line 8207 of src/parser.rs
                    if self.fast_parser_predicate_matches(predicate_context, transition, index) {
                        let boundary = left_recursive_boundary(atn, state, target);
                        outcomes.extend(
                            self.recognize_state_fast(
                                atn,
                                FastRecognizeRequest {
                                    state_number: target,
                                    stop_state,
                                    index,
                                    rule_start_index,
                                    decision_start_index: next_decision_start_index,
                                    precedence,
                                    depth: depth + 1,
                                    recovery_symbols: Rc::clone(&epsilon_recovery_symbols),
                                    recovery_state: epsilon_recovery_state,
                                },
                                FastRecognizeScratch {
                                    predicate_context,
                                    visiting,
                                    memo,
                                    expected,
                                },
                            )
                            .into_iter()
                            .map(|mut outcome| {
                                if let Some(rule_index) = boundary {
                                    let boundary = self.arena_boundary_node(rule_index);
                                    self.defer_fast_outcome_node(&mut outcome, boundary);
                                }
                                outcome
                            }),
                        );
                    } else {

Found a 32 line (125 tokens) duplication in the following files:

  • Starting at line 8134 of src/parser.rs
  • Starting at line 8170 of src/parser.rs
  • Starting at line 8208 of src/parser.rs
                    let boundary = left_recursive_boundary(atn, state, target);
                    outcomes.extend(
                        self.recognize_state_fast(
                            atn,
                            FastRecognizeRequest {
                                state_number: target,
                                stop_state,
                                index,
                                rule_start_index,
                                decision_start_index: next_decision_start_index,
                                precedence,
                                depth: depth + 1,
                                recovery_symbols: Rc::clone(&epsilon_recovery_symbols),
                                recovery_state: epsilon_recovery_state,
                            },
                            FastRecognizeScratch {
                                predicate_context,
                                visiting,
                                memo,
                                expected,
                            },
                        )
                        .into_iter()
                        .map(|mut outcome| {
                            if let Some(rule_index) = boundary {
                                let boundary = self.arena_boundary_node(rule_index);
                                self.defer_fast_outcome_node(&mut outcome, boundary);
                            }
                            outcome
                        }),
                    );
                }

Found a 22 line (125 tokens) duplication in the following files:

  • Starting at line 13351 of src/parser.rs
  • Starting at line 13423 of src/parser.rs
            atn.add_state(AtnStateKind::BlockEnd, Some(0))
                .expect("state")
                .index(),
            4
        );
        assert_eq!(
            atn.add_state(AtnStateKind::RuleStop, Some(0))
                .expect("state")
                .index(),
            5
        );
        atn.set_rule_to_start_state(vec![0])
            .expect("rule start states");
        atn.set_rule_to_stop_state(vec![5])
            .expect("rule stop states");
        atn.add_decision_state(1).expect("decision state");
        atn.add_transition(0, ParserTransitionSpec::Epsilon { target: 1 })
            .expect("transition");
        atn.add_transition(
            1,
            ParserTransitionSpec::Atom {
                target: 2,

Found a 22 line (117 tokens) duplication in the following files:

  • Starting at line 200 of src/atn/lexer.rs
  • Starting at line 395 of src/atn/lexer.rs
  • Starting at line 614 of src/atn/lexer.rs
    atn: &LexerAtn,
    mut custom_action: A,
    mut semantic_predicate: P,
    mut accept_adjuster: E,
) -> Result<TokenId, TokenStoreError>
where
    I: CharStream,
    A: FnMut(&mut BaseLexer<I>, LexerCustomAction),
    P: FnMut(&BaseLexer<I>, LexerPredicate) -> bool,
    E: FnMut(&mut BaseLexer<I>, i32, usize),
{
    next_token_with_hooks_impl(
        lexer,
        sink,
        atn,
        &mut custom_action,
        &mut semantic_predicate,
        &mut |_| {},
        &mut accept_adjuster,
        &mut |_, _| {},
        LexerMatchStrategy {
            compiled: None,

Found a 33 line (115 tokens) duplication in the following files:

  • Starting at line 9088 of src/parser.rs
  • Starting at line 9161 of src/parser.rs
                        outcomes.extend(
                            self.recognize_state(
                                atn,
                                RecognizeRequest {
                                    state_number: *target,
                                    stop_state,
                                    index,
                                    rule_start_index,
                                    decision_start_index: next_decision_start_index,
                                    init_action_rules,
                                    predicates,
                                    semantics,
                                    rule_args,
                                    member_actions,
                                    return_actions,
                                    local_int_arg,
                                    member_values: member_values.clone(),
                                    return_values: return_values.clone(),
                                    rule_alt_number: next_alt_number,
                                    track_alt_numbers,
                                    consumed_eof,
                                    precedence,
                                    depth: depth + 1,
                                    recovery_symbols: epsilon_recovery_symbols.clone(),
                                    recovery_state: epsilon_recovery_state,
                                },
                                visiting,
                                memo,
                                expected,
                            )
                            .into_iter()
                            .map(|mut outcome| {
                                prepend_decision(&mut outcome, decision);

Found a 15 line (113 tokens) duplication in the following files:

  • Starting at line 14363 of src/parser.rs
  • Starting at line 14647 of src/parser.rs
    fn generated_match_token_counts_single_token_deletion_recovery() {
        let atn = generated_match_recovery_atn();
        let data = RecognizerData::new(
            "Mini.g4",
            Vocabulary::new(
                [None, Some("'X'"), Some("'Y'"), Some("'Z'")],
                [None, Some("X"), Some("Y"), Some("Z")],
                [None::<&str>, None, None, None],
            ),
        );
        let mut parser = BaseParser::new(
            CommonTokenStream::new(Source {
                tokens: vec![
                    TestToken::new(3).with_text("z"),
                    TestToken::new(2).with_text("y"),

Found a 12 line (112 tokens) duplication in the following files:

  • Starting at line 12331 of src/parser.rs
  • Starting at line 12414 of src/parser.rs
        let mut atn = ParserAtnBuilder::new(1);
        for (state, kind, rule) in [
            (0, AtnStateKind::RuleStart, 0),
            (1, AtnStateKind::StarLoopEntry, 0),
            (2, AtnStateKind::Basic, 0), // ops hub
            (3, AtnStateKind::Basic, 0), // shift prec
            (4, AtnStateKind::Basic, 0), // shift first >
            (5, AtnStateKind::Basic, 0), // shift second >
            (6, AtnStateKind::Basic, 0), // rel prec
            (7, AtnStateKind::Basic, 0), // rel >
            (8, AtnStateKind::LoopEnd, 0),
            (9, AtnStateKind::RuleStop, 0),

Found a 22 line (112 tokens) duplication in the following files:

  • Starting at line 13762 of src/parser.rs
  • Starting at line 13963 of src/parser.rs
    fn predicate_after_token_atn() -> Atn {
        let mut atn = ParserAtnBuilder::new(2);
        assert_eq!(
            atn.add_state(AtnStateKind::RuleStart, Some(0))
                .expect("state")
                .index(),
            0
        );
        assert_eq!(
            atn.add_state(AtnStateKind::Basic, Some(0))
                .expect("state")
                .index(),
            1
        );
        assert_eq!(
            atn.add_state(AtnStateKind::Basic, Some(0))
                .expect("state")
                .index(),
            2
        );
        assert_eq!(
            atn.add_state(AtnStateKind::Basic, Some(0))

Found a 22 line (111 tokens) duplication in the following files:

  • Starting at line 12196 of src/parser.rs
  • Starting at line 13762 of src/parser.rs
  • Starting at line 13963 of src/parser.rs
    fn left_recursive_loop_with_caller_follow_atn(caller_symbol: i32) -> Atn {
        let mut atn = ParserAtnBuilder::new(2);
        assert_eq!(
            atn.add_state(AtnStateKind::RuleStart, Some(0))
                .expect("state")
                .index(),
            0
        );
        assert_eq!(
            atn.add_state(AtnStateKind::Basic, Some(0))
                .expect("state")
                .index(),
            1
        );
        assert_eq!(
            atn.add_state(AtnStateKind::Basic, Some(0))
                .expect("state")
                .index(),
            2
        );
        assert_eq!(
            atn.add_state(AtnStateKind::RuleStart, Some(1))

Found a 14 line (110 tokens) duplication in the following files:

  • Starting at line 14096 of src/parser.rs
  • Starting at line 16348 of src/parser.rs
    fn parser_matches_token_and_reports_mismatch() {
        let source = Source {
            tokens: vec![
                TestToken::new(1).with_text("x"),
                TestToken::eof("parser-test", 1, 1, 1),
            ],
            index: 0,
        };
        let data = RecognizerData::new(
            "Mini.g4",
            Vocabulary::new([None, Some("'x'")], [None, Some("X")], [None::<&str>, None]),
        );
        let mut parser = BaseParser::new(CommonTokenStream::new(source), data);
        let matched = parser.match_token(1).expect("token 1 should match");

Found a 13 line (109 tokens) duplication in the following files:

  • Starting at line 14096 of src/parser.rs
  • Starting at line 16373 of src/parser.rs
    fn parser_matches_token_and_reports_mismatch() {
        let source = Source {
            tokens: vec![
                TestToken::new(1).with_text("x"),
                TestToken::eof("parser-test", 1, 1, 1),
            ],
            index: 0,
        };
        let data = RecognizerData::new(
            "Mini.g4",
            Vocabulary::new([None, Some("'x'")], [None, Some("X")], [None::<&str>, None]),
        );
        let mut parser = BaseParser::new(CommonTokenStream::new(source), data);

Found a 22 line (108 tokens) duplication in the following files:

  • Starting at line 7041 of src/parser.rs
  • Starting at line 7429 of src/parser.rs
    ) -> Option<RecognizeOutcome> {
        let (error_index, message) = self.expected_error_message(rule_index, start_index, expected);
        let diagnostic = diagnostic_for_token(self.token_at(error_index), message);
        let mut next_index = error_index;
        loop {
            let symbol = self.token_type_at(next_index);
            if sync_symbols.contains(&symbol) {
                if next_index == error_index {
                    return None;
                }
                break;
            }
            if symbol == TOKEN_EOF {
                break;
            }
            let after = self.consume_index(next_index, symbol);
            if after == next_index {
                break;
            }
            next_index = after;
        }
        let mut nodes = NodeSeqId::EMPTY;

Found a 15 line (108 tokens) duplication in the following files:

  • Starting at line 16627 of src/parser.rs
  • Starting at line 16651 of src/parser.rs
    fn outcome_ties_keep_later_non_recursive_alternative() {
        let arena = RecognitionArena::default();
        let first = RecognizeOutcome {
            index: 1,
            consumed_eof: false,
            alt_number: 0,
            member_values: BTreeMap::new(),
            return_values: BTreeMap::new(),
            diagnostics: DiagnosticSeqId::EMPTY,
            decisions: Vec::new(),
            actions: vec![ParserAction::new(1, 0, 0, None)],
            nodes: NodeSeqId::EMPTY,
        };
        let second = RecognizeOutcome {
            actions: vec![ParserAction::new(2, 0, 0, None)],

Found a 13 line (107 tokens) duplication in the following files:

  • Starting at line 2407 of src/atn/lexer.rs
  • Starting at line 2655 of src/atn/lexer.rs
        let mut hooks = LifecycleRecordingHooks::default();
        let mut store = TokenStore::new(lexer.source_text(), lexer.source_name());
        let mut sink = TokenSink::new(&mut store);
        let mut ids = Vec::new();
        for _ in 0..3 {
            let id = if compiled {
                next_token_compiled_with_semantic_hooks(
                    &mut lexer, &mut sink, &atn, &dfa, &mut hooks,
                )
            } else {
                next_token_with_semantic_hooks(&mut lexer, &mut sink, &atn, &mut hooks)
            }
            .expect("lifecycle token should fit");

Found a 16 line (105 tokens) duplication in the following files:

  • Starting at line 6242 of src/parser.rs
  • Starting at line 6808 of src/parser.rs
        let start_state = atn.rule_to_start_state().get(rule_index).ok_or_else(|| {
            AntlrError::Unsupported(format!("rule {rule_index} has no start state"))
        })?;
        let stop_state = atn
            .rule_to_stop_state()
            .get(rule_index)
            .filter(|state| *state != usize::MAX)
            .ok_or_else(|| {
                AntlrError::Unsupported(format!("rule {rule_index} has no stop state"))
            })?;

        let start_index = self.current_visible_index();
        self.clear_prediction_diagnostics();
        self.reset_per_parse_caches();
        self.reset_recognition_arena();
        let caller_follow_state = self.pending_invoking_follow_state(atn);

Found a 13 line (100 tokens) duplication in the following files:

  • Starting at line 5977 of src/parser.rs
  • Starting at line 6001 of src/parser.rs
        let mut expected = BTreeSet::new();
        for index in (1..self.rule_context_stack.len()).rev() {
            let invoking_state = self.rule_context_stack[index].invoking_state;
            let Ok(state_number) = usize::try_from(invoking_state) else {
                continue;
            };
            let Some(Transition::Rule { follow_state, .. }) = atn
                .state(state_number)
                .and_then(|state| state.transitions().first())
                .map(ParserTransition::data)
            else {
                continue;
            };

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@tinovyatkin, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 46 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4632644b-8f3d-4aae-a6b9-336865ff47ab

📥 Commits

Reviewing files that changed from the base of the PR and between bc9ee21 and 045b68e.

📒 Files selected for processing (3)
  • src/atn/lexer.rs
  • src/atn/lexer_dfa.rs
  • src/parser.rs

Walkthrough

The lexer DFA now records escape edges with serialized continuation configurations and can resume ATN interpretation from narrowed states. Compiled matching distinguishes completed matches, continuation resumes, and budget-only restarts. Serialization validation and predicate-related tests cover the new data. Parser fast outcome deduplication now selects inline, dense, or sparse strategies, reuses scratch storage, and reports strategy-specific performance counters.

Poem

I’m a rabbit hopping through DFA lanes,
With tiny escape maps and fewer pains.
The parser sorts outcomes, neat and bright,
Reusing its scratch through day and night.
“Squeak!” says the lexer, “continuations take flight!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The lexer fallback optimization is not part of issue #108's parser-focused scope, so the PR includes unrelated code changes. Split the lexer fallback work into a separate PR or add a linked issue; keep this PR focused on parser outcome deduplication.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the two main performance changes in the PR.
Description check ✅ Passed The description is clearly related to the PR and summarizes the lexer and parser performance work.
Linked Issues check ✅ Passed The parser deduplication changes address the issue's mixed-type VALUES performance gap and preserve the required outcome semantics.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances the lexer DFA compilation by allowing the interpreter to resume from narrowed pre-closure configurations (continuations) upon reaching an escape edge, rather than restarting from the token boundary. This is achieved by introducing CompiledMatch, CompiledResume, and CompiledLexerContinuation structures, alongside updating the matching logic and serialization format. Feedback on these changes focuses on improving safety and robustness, specifically by avoiding direct indexing on collections to prevent runtime panics, replacing direct as casts with checked conversions (try_from) to avoid silent truncation, and using checked_add to prevent potential integer overflow panics during range merging.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/atn/lexer.rs Outdated
Comment thread src/atn/lexer_dfa.rs Outdated
Comment thread src/atn/lexer_dfa.rs Outdated
Comment thread src/atn/lexer_dfa.rs
Comment thread src/atn/lexer_dfa.rs Outdated
@tinovyatkin tinovyatkin changed the title [codex] Resume compiled lexer escapes from narrowed configs [codex] Accelerate lexer fallback and parser deduplication Jul 18, 2026
@tinovyatkin tinovyatkin changed the title [codex] Accelerate lexer fallback and parser deduplication Accelerate lexer fallback and parser deduplication Jul 18, 2026
@tinovyatkin
tinovyatkin marked this pull request as ready for review July 18, 2026 15:43
@tinovyatkin

Copy link
Copy Markdown
Contributor Author

@codex review

@tinovyatkin

Copy link
Copy Markdown
Contributor Author

@codex review

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/atn/lexer_dfa.rs (1)

1413-1488: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Exercise EOF and wide-character continuation routes.

This test only covers an ASCII character escape. Add compiled-vs-interpreted cases for an EOF escape and a non-ASCII escape range; both use distinct routing and position semantics.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/atn/lexer_dfa.rs` around lines 1413 - 1488, Extend
predicate_edge_resumes_the_interpreter_for_true_and_false_outcomes with
compiled-vs-interpreted cases covering an EOF escape and a non-ASCII escape
range, using appropriate inputs and predicate outcomes. Assert token results and
drained error messages match for both implementations, while preserving the
existing ASCII coverage and exercising each route’s distinct position semantics.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/atn/lexer.rs`:
- Around line 669-675: Validate the continuation from CompiledMatch::Resume
against the ATN before calling match_token_from_continuation, including config,
stack, rule/action indices, non-empty states, and valid behind offsets; if any
check fails, treat it like CompiledMatch::Restart and fall through to
cached/interpreted matching instead of resuming unchecked payloads.

In `@src/parser.rs`:
- Around line 11699-11713: Update the Sparse branch in fast_outcome_dedup to
release scratch.sparse_keys storage when its capacity exceeds a defined
retention threshold after deduplication, while retaining the existing allocation
for normal sizes. Ensure the oversized set is cleared and shrunk so reused
parsers do not permanently retain capacity.

---

Outside diff comments:
In `@src/atn/lexer_dfa.rs`:
- Around line 1413-1488: Extend
predicate_edge_resumes_the_interpreter_for_true_and_false_outcomes with
compiled-vs-interpreted cases covering an EOF escape and a non-ASCII escape
range, using appropriate inputs and predicate outcomes. Assert token results and
drained error messages match for both implementations, while preserving the
existing ASCII coverage and exercising each route’s distinct position semantics.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6c9f93a0-de6f-4ecf-89a8-4a5bc888d129

📥 Commits

Reviewing files that changed from the base of the PR and between f95b0d2 and bc9ee21.

📒 Files selected for processing (3)
  • src/atn/lexer.rs
  • src/atn/lexer_dfa.rs
  • src/parser.rs

Comment thread src/atn/lexer.rs
Comment thread src/parser.rs
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: c2a5e88357

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@tinovyatkin

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 045b68e8cc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@tinovyatkin
tinovyatkin merged commit 21ac78f into main Jul 18, 2026
11 checks passed
@tinovyatkin
tinovyatkin deleted the codex/resume-compiled-lexer-escapes branch July 18, 2026 19:42
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.

perf(parser): sakila-data.sql ~7x slower than antlr4-cpp — mixed-type multi-column VALUES tuples cost ~17x pure-int

1 participant