dbt-antlr-runtime 0.4.0

Dbt fork of ANTLR4 runtime for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
//! Implementation of lexer automata(DFA)
use crate::atn::ATN;
use crate::atn_config::LexerATNConfig;
use crate::atn_config_set::{LexerATNConfigSet, MutableLexerATNConfigSet};
use crate::atn_simulator::{BaseATNSimulator, IATNSimulator};
use crate::atn_state::{ATNState, ATNStateRef, ATNStateType};
use crate::char_stream::CharStream;
use crate::dfa::static_lexer_dfa::{
    Accel, LexerContinuation, StaticLexerDFA, StaticLexerTables, ACCEPT_BIT,
    CONTINUATION_MOVED_CONFIGS, CONTINUATION_SOURCE_SET, ESCAPE, NO_CONTINUATION, NO_EDGE,
    STATE_MASK,
};
use crate::dfa::{DFAState, ProposedDFAState, DFA};
use crate::errors::ANTLRError;
use crate::int_stream::{IntStream, EOF};
use crate::lexer::{Lexer, LEXER_MAX_CHAR_VALUE, LEXER_MIN_CHAR_VALUE};
use crate::lexer_action_executor::LexerActionExecutor;
use crate::prediction_context::PredictionContextRef;
use crate::prediction_context::{PredictionContext, PredictionContextCache};
use crate::token::TOKEN_EOF;

use crate::token_factory::TokenFactory;
use crate::transition::{Transition, TransitionType};

// todo rewrite this to be actually usable
#[doc(hidden)]
pub trait ILexerATNSimulator<'sim>: IATNSimulator<'sim, LexerATNConfigSet<'sim>> {
    fn reset(&mut self);
    fn match_token<'input, 'arena, Input, TF>(
        &mut self,
        mode: usize,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena;
    fn consume<T: IntStream + ?Sized>(&self, input: &mut T);
    #[cold]
    fn recover(&mut self, _re: ANTLRError, input: &mut impl IntStream) {
        if input.la(1) != EOF {
            self.consume(input)
        }
    }
}

/// Simple DFA implementation enough for lexer.
#[derive(Debug)]
pub struct LexerATNSimulator<'sim> {
    base: BaseATNSimulator<'sim, LexerATNConfigSet<'sim>>,

    start_index: isize,
    mode: usize,
    prev_accept: Option<ResolvedAccept<'sim>>,
    static_tables: Option<&'static StaticLexerTables>,
    /// Number of escape edges the table walker handed to the lazy path.
    #[doc(hidden)]
    pub escape_count: usize,
    /// Number of tokens the table walker restarted on the lazy path.
    #[doc(hidden)]
    pub restart_count: usize,
}

impl<'sim> ILexerATNSimulator<'sim> for LexerATNSimulator<'sim> {
    fn reset(&mut self) {
        self.prev_accept = None
    }

    fn match_token<'input, 'arena, Input, TF>(
        &mut self,
        mode: usize,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        let scratch = bumpalo::Bump::new();

        self.mode = mode;
        let mark = lexer.input().mark();
        let result = (|| {
            self.start_index = lexer.input().index();
            self.prev_accept = None;
            // Table-driven fast path: modes the builder compiled have a
            // static DFA table. Escape edges inside the walk hand the token
            // back to the lazy path.
            if let Some(tables) = self.static_tables {
                if let Some(table) = tables.mode(mode) {
                    return if lexer.input().has_item_at() {
                        self.match_static_random_access(table, lexer, &scratch)
                    } else {
                        self.match_static_cursor(table, lexer, &scratch)
                    };
                }
            }
            self.match_token_lazy(lexer, &scratch)
        })();
        lexer.input().release(mark);
        result
    }

    #[inline]
    fn consume<T: IntStream + ?Sized>(&self, input: &mut T) {
        input.consume();
    }
}

impl<'sim> IATNSimulator<'sim, LexerATNConfigSet<'sim>> for LexerATNSimulator<'sim> {
    fn shared_context_cache(&self) -> &'sim PredictionContextCache<'sim> {
        self.base.shared_context_cache()
    }

    fn atn(&self) -> &'static ATN {
        self.base.atn()
    }

    fn decision_to_dfa(&self, decision: usize) -> Option<&'sim DFA<'sim, LexerATNConfigSet<'sim>>> {
        self.base.decision_to_dfa(decision)
    }
}

#[allow(missing_docs)]
pub const MIN_DFA_EDGE: i32 = 0;
#[allow(missing_docs)]
pub const MAX_DFA_EDGE: i32 = 127;
pub const LEXER_DFA_EDGE_SET_SIZE: usize = (MAX_DFA_EDGE - MIN_DFA_EDGE + 1) as usize;

impl<'sim> LexerATNSimulator<'sim> {
    /// Creates `LexerATNSimulator` instance which creates DFA over `atn`
    pub fn new(base: BaseATNSimulator<'sim, LexerATNConfigSet<'sim>>) -> LexerATNSimulator<'sim> {
        LexerATNSimulator {
            // Note: already validated by the manager at construction:
            static_tables: base.static_lexer_tables,
            base,
            start_index: 0,
            mode: 0,
            prev_accept: None,
            escape_count: 0,
            restart_count: 0,
        }
    }

    /// Attaches static lexer DFA tables. Modes with a table tokenize
    /// through the table walker; modes without one (and every escape edge)
    /// keep using the lazy path.
    ///
    /// Panics when the tables reference ATN states or lexer actions the ATN
    /// of this simulator does not have: the tables and the ATN come from
    /// the same generated lexer, so a mismatch is a build inconsistency.
    /// Regenerate the lexer.
    ///
    /// This is mostly for use by tests.
    pub fn set_static_tables(&mut self, tables: &'static StaticLexerTables) {
        tables.validate_for_atn(self.atn());
        self.static_tables = Some(tables);
    }

    /// The lazy `match_token` path: ATN simulation with the lazily built
    /// DFA cache.
    fn match_token_lazy<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        let dfa = self
            .decision_to_dfa(self.mode)
            .ok_or_else(|| ANTLRError::illegal_state("invalid mode".into()))?;

        match dfa.s0() {
            None => self.match_atn(lexer, dfa, scratch),
            Some(s0) => self.exec_atn(s0, lexer, dfa, scratch),
        }
    }

    /// Token matching with a precomputed [`StaticLexerDFA`] over a
    /// random-access input stream.
    fn match_static_random_access<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        table: &'static StaticLexerDFA,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        let start_index = self.start_index;
        let mut s = table.start_state();
        // Accept states have accept_type >= 0. A rule with a `more` or
        // `type(...)` command accepts with token type 0.
        let mut prev_accept: Option<(isize, u16)> = if table.accept_type(s) >= 0 {
            Some((start_index, s))
        } else {
            None
        };

        let input = lexer.input();
        let mut cursor = start_index;
        let bytes = input.bytes_at(0);
        let mut symbol = input.item_at(cursor).unwrap_or(EOF);
        loop {
            let entry = table.edge_entry(s, symbol);
            if entry == NO_EDGE {
                break;
            }
            if entry == ESCAPE {
                return self.static_escape(table, s, symbol, cursor, prev_accept, lexer, scratch);
            }
            let target = entry & STATE_MASK;
            if symbol != EOF {
                cursor += if symbol < 0x80 {
                    1
                } else {
                    char::from_u32(symbol as u32).map_or(1, |c| c.len_utf8() as isize)
                };
            }
            if entry & ACCEPT_BIT != 0 {
                prev_accept = Some((cursor, target));
                if symbol == EOF {
                    break;
                }
            }
            symbol = input.item_at(cursor).unwrap_or(EOF);
            s = target;

            if let Some(hay) = bytes {
                let tag = table.accel_tag(s);
                if tag != 0 {
                    let accel = table.accel_payload(tag);
                    let start = cursor as usize;
                    let c = run_scan(hay, start, accel, scratch);
                    if c > start {
                        cursor = c as isize;
                        if entry & ACCEPT_BIT != 0
                            && !matches!(accel, Accel::CountedExclusion { .. })
                        {
                            prev_accept = Some((cursor, s));
                        }
                        symbol = match hay.get(c) {
                            Some(&b) if b < 0x80 => b as i32,
                            _ => input.item_at(cursor).unwrap_or(EOF),
                        };
                    }
                }
            }
        }
        input.seek(cursor);
        self.finish_static(table, prev_accept, symbol, lexer)
    }

    /// Token matching with a precomputed [`StaticLexerDFA`] over a cursor-only
    /// input stream.
    fn match_static_cursor<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        table: &'static StaticLexerDFA,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        let start_index = self.start_index;
        let mut s = table.start_state();
        let mut prev_accept: Option<(isize, u16)> = if table.accept_type(s) >= 0 {
            Some((start_index, s))
        } else {
            None
        };

        let mut symbol = lexer.input().la(1);
        loop {
            let entry = table.edge_entry(s, symbol);
            if entry == NO_EDGE {
                break;
            }
            if entry == ESCAPE {
                return self.static_escape(
                    table,
                    s,
                    symbol,
                    lexer.input().index(),
                    prev_accept,
                    lexer,
                    scratch,
                );
            }
            let target = entry & STATE_MASK;
            if symbol != EOF {
                lexer.input().consume();
            }
            if entry & ACCEPT_BIT != 0 {
                prev_accept = Some((lexer.input().index(), target));
                if symbol == EOF {
                    break;
                }
            }
            symbol = lexer.input().la(1);
            s = target;
            let tag = table.accel_tag(s);
            if tag != 0 {
                if let Accel::CountedExclusion { opener, closer, n } = table.accel_payload(tag) {
                    let input = lexer.input();
                    let start = input.index() as usize;
                    let c = {
                        let text = input.get_text(0, input.size());
                        run_scan_counted(
                            text.as_bytes(),
                            start,
                            &opener[..n as usize],
                            &closer[..n as usize],
                            scratch,
                        )
                    };
                    if c > start {
                        input.seek(c as isize);
                        symbol = input.la(1);
                    }
                }
            }
        }
        self.finish_static(table, prev_accept, symbol, lexer)
    }

    #[inline]
    fn finish_static<'input, 'arena, Input, TF>(
        &self,
        table: &'static StaticLexerDFA,
        prev_accept: Option<(isize, u16)>,
        symbol: i32,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        match prev_accept {
            Some((index, state)) => {
                lexer.input().seek(index);
                for action in table.accept_actions(state) {
                    action.execute(lexer);
                }
                Ok(table.accept_type(state))
            }
            None => {
                if symbol == EOF && lexer.input().index() == self.start_index {
                    return Ok(TOKEN_EOF);
                }
                Err(ANTLRError::lexer_no_alt(self.start_index))
            }
        }
    }

    /// Handles an ESCAPE edge hit by
    /// [`LexerATNSimulator::match_static_random_access`] or
    /// [`LexerATNSimulator::match_static_cursor`]: positions the input at the
    /// unconsumed escape symbol, carries the best accept so far into
    /// `self.prev_accept`, and resumes the lazy simulation from the edge's
    /// continuation. A budget escape has no continuation and restarts the token
    /// on the lazy path from the token start.
    #[cold]
    #[allow(clippy::too_many_arguments)]
    fn static_escape<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        table: &'static StaticLexerDFA,
        state: u16,
        symbol: i32,
        cursor: isize,
        prev_accept: Option<(isize, u16)>,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        self.escape_count += 1;
        lexer.input().seek(cursor);
        self.prev_accept = prev_accept.map(|(index, state)| {
            let actions = table.accept_actions(state);
            ResolvedAccept {
                index,
                prediction: table.accept_type(state),
                executor: if actions.is_empty() {
                    None
                } else {
                    Some(AcceptExecutor::Static(actions))
                },
            }
        });
        let continuation = table.escape_continuation(state, symbol);
        if continuation == NO_CONTINUATION {
            return self.restart_token_lazy(lexer, scratch);
        }
        self.match_token_from_continuation(table.continuation(continuation), symbol, lexer, scratch)
    }

    /// Restarts the current token on the lazy path from the token start.
    /// Used for budget escapes (no continuation).
    #[cold]
    fn restart_token_lazy<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        self.restart_count += 1;
        lexer.input().seek(self.start_index);
        self.prev_accept = None;
        self.match_token_lazy(lexer, scratch)
    }
    /// Resumes the lazy simulation at an escape edge. Rebuilds the
    /// serialized configs of the continuation, closes them with real
    /// predicate evaluation (the input is at the unconsumed escape symbol),
    /// interns the closed set through `add_dfastate`, and continues the
    /// normal exec loop for the rest of the token. The best accept of the
    /// table walk is already in `self.prev_accept`, so maximal munch across
    /// the hand-off is exact.
    fn match_token_from_continuation<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        continuation: &'static LexerContinuation,
        escape_symbol: i32,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        let atn = self.atn();
        let start_index = self.start_index;

        // Rebuild the singleton context chains bottom-up: local id 0 is the
        // empty context, entry i has local id i + 1 with parents that refer
        // to smaller ids.
        let mut contexts = Vec::with_capacity(continuation.ctxs.len() + 1);
        contexts.push(PredictionContextRef::new_empty());
        for &(parent, return_state) in &continuation.ctxs {
            let ctx = PredictionContext::new_singleton(
                Some(contexts[parent as usize]),
                atn.make_state_ref(return_state),
            );
            contexts.push(PredictionContextRef::from(scratch.alloc(ctx)));
        }

        let configs: Vec<LexerATNConfig> = continuation
            .configs
            .iter()
            .map(|c| {
                let mut config = LexerATNConfig::new(
                    atn.make_state_ref(c.state),
                    c.alt,
                    contexts[c.ctx as usize],
                );
                config.set_passed_through_non_greedy_decision(c.non_greedy);
                let mut executor = None;
                for &action_index in &c.actions {
                    let action: crate::lexer_action::LexerAction =
                        atn.lexer_actions[action_index as usize].clone();
                    executor = Some(&*scratch.alloc(LexerActionExecutor::new_copy_append(
                        scratch, executor, action,
                    )));
                }
                config.with_lexer_executor(executor)
            })
            .collect();

        let mut reach = MutableLexerATNConfigSet::new(scratch);
        match continuation.kind {
            CONTINUATION_MOVED_CONFIGS => {
                // The configs are post-move, pre-closure: replay the
                // closure of each with its serialized
                // alt_reached_accept flag.
                let mut env = LazyClosureEnv::new(self, lexer);
                for (config, serialized) in configs.iter().zip(continuation.configs.iter()) {
                    closure_core(
                        atn,
                        config.clone(),
                        &mut reach,
                        serialized.alt_reached_accept,
                        true,
                        escape_symbol == EOF,
                        &mut env,
                        scratch,
                    );
                }
            }
            CONTINUATION_SOURCE_SET => {
                // The configs are the source set of the state: re-run the
                // full move step, so the pruning decisions use runtime
                // predicate results.
                let mut env = LazyClosureEnv::new(self, lexer);
                reachable_core(
                    atn,
                    start_index,
                    configs.iter(),
                    &mut reach,
                    escape_symbol,
                    &mut env,
                    None,
                    scratch,
                );
            }
            _ => unreachable!("continuation kinds are validated at load"),
        }

        if reach.is_empty() {
            // The resumed move has no target: the lazy equivalent is the
            // error state, which ends the walk at the escape position.
            return self.fail_or_accept(escape_symbol, lexer);
        }
        let dfa = self.get_dfa();
        // As in compute_target_state, a predicate in the closure suppresses
        // the caching of the edge; the resumed edge comes from a table
        // state, so there is no edge to cache in any case. The interned
        // state itself dedups against the lazy DFA states.
        reach.set_has_semantic_context(false);
        let to = self.add_dfastate(dfa, reach)?;

        if escape_symbol != EOF {
            self.consume(lexer.input());
        }
        if self.capture_sim_state(lexer.input(), to) && escape_symbol == EOF {
            return self.fail_or_accept(escape_symbol, lexer);
        }
        let symbol = lexer.input().la(1);
        self.exec_atn_loop(to, symbol, lexer, dfa, scratch)
    }

    #[cold]
    fn match_atn<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        dfa: &'sim DFA<LexerATNConfigSet<'sim>>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        //        let start_state = self.atn().mode_to_start_state.get(self.mode as usize).ok_or(ANTLRError::IllegalStateError("invalid mode".into()))?;
        let atn = self.atn();
        let start_state = *atn
            .mode_to_start_state
            .get(self.mode)
            .ok_or_else(|| ANTLRError::illegal_state("invalid mode".into()))?;

        let _old_mode = self.mode;
        let mut s0_closure = self.compute_start_state(start_state.as_ref(), lexer, scratch);
        let _supress_edge = s0_closure.has_semantic_context();
        s0_closure.set_has_semantic_context(false);

        let next_state = self.add_dfastate(dfa, s0_closure)?;
        if !_supress_edge {
            dfa.set_s0(next_state);
        }

        self.exec_atn(next_state, lexer, dfa, scratch)
    }

    fn exec_atn<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        //        input: &'a mut dyn CharStream,
        ds0: &'sim DFAState<'sim, LexerATNConfigSet<'sim>>,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        dfa: &'sim DFA<LexerATNConfigSet<'sim>>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        //        if self.get_dfa().states.read().unwrap().get(ds0).unwrap().is_accept_state{
        self.capture_sim_state(lexer.input(), ds0);
        //        }

        let symbol = lexer.input().la(1);
        self.exec_atn_loop(ds0, symbol, lexer, dfa, scratch)
    }

    /// The inner loop of `exec_atn`: from state `s` with `symbol` the
    /// (unconsumed) lookahead. Also the tail of the continuation resume
    /// path, which has already consumed the escape symbol.
    fn exec_atn_loop<'scratch, 'input, 'arena, Input, TF>(
        &mut self,
        mut s: &'sim DFAState<'sim, LexerATNConfigSet<'sim>>,
        mut symbol: i32,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        dfa: &'sim DFA<'sim, LexerATNConfigSet<'sim>>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        loop {
            let target = if let Some(target) = dfa.get_edge(s, (symbol - MIN_DFA_EDGE) as usize) {
                target
            } else {
                self.compute_target_state(dfa, s, symbol, lexer, scratch)?
            };

            if target.is_error_state() {
                break;
            }
            //            println!(" --- target computed {:?}", self.get_dfa().states.read().unwrap()[target].configs.configs.iter().map(|it|it.get_state()).collect::<Vec<_>>());

            if symbol != EOF {
                self.consume(lexer.input());
            }

            if self.capture_sim_state(lexer.input(), target) && symbol == EOF {
                break;
            }

            symbol = lexer.input().la(1);

            s = target;
        }
        // let _last = self.get_dfa().states.read().get(s).unwrap();

        self.fail_or_accept(symbol, lexer)
    }

    #[cold]
    fn compute_target_state<'scratch, 'input, 'arena, Input, TF>(
        &self,
        dfa: &'sim DFA<LexerATNConfigSet<'sim>>,
        s: &'sim DFAState<'sim, LexerATNConfigSet<'sim>>,
        _t: i32,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> Result<&'sim DFAState<'sim, LexerATNConfigSet<'sim>>, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        let mut reach = MutableLexerATNConfigSet::new(scratch);
        self.get_reachable_config_set(s.configs(), &mut reach, _t, lexer, scratch);
        //        println!(" --- target computed {:?}", reach.configs.iter().map(|it|it.get_state()).collect::<Vec<_>>());

        // let mut states = dfa_mut.states;
        if reach.is_empty() {
            if !reach.has_semantic_context() {
                self.add_dfaedge(dfa, s, _t, dfa.get_error_state());
            }

            return Ok(dfa.get_error_state());
        }

        let supress_edge = reach.has_semantic_context();
        reach.set_has_semantic_context(false);
        let to = self.add_dfastate(dfa, reach)?;
        if !supress_edge {
            let from = s;
            self.add_dfaedge(dfa, from, _t, to);
        }
        //        println!("target state computed from {:?} to {:?} on symbol {}", _s, to, char::try_from(_t as u32).unwrap());
        Ok(to)
    }

    fn get_reachable_config_set<'scratch, 'input, 'arena, Input, TF>(
        &self,
        // _states: &V,
        //        _input: &mut dyn CharStream,
        _closure: &'scratch LexerATNConfigSet<'scratch>,
        _reach: &mut MutableLexerATNConfigSet<'scratch>,
        _t: i32,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) where
        'input: 'arena,
        'sim: 'scratch,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        reachable_core(
            self.atn(),
            self.start_index,
            _closure.get_items(),
            _reach,
            _t,
            &mut LazyClosureEnv::new(self, lexer),
            None,
            scratch,
        )
    }

    //    fn get_reachable_target<T>(&self, states: &T, _trans: &Transition, _t: i32) -> &ATNState
    //    where
    //        T: Deref<Target = Vec<DFAState>>,
    //    {
    //        unimplemented!()
    //    }

    fn fail_or_accept<'input, 'arena, Input, TF>(
        &mut self,
        _t: i32,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
    ) -> Result<i32, ANTLRError>
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        //        println!("fail_or_accept");
        if let Some(accept) = self.prev_accept.take() {
            lexer.input().seek(accept.index);

            match accept.executor {
                Some(AcceptExecutor::Lazy(x)) => x.execute(lexer, self.start_index),
                // Position-independent actions only: no match offset is
                // needed, so plain `execute` matches
                // `LexerActionExecutor::execute` here.
                Some(AcceptExecutor::Static(actions)) => {
                    for action in actions {
                        action.execute(lexer);
                    }
                }
                None => {}
            }

            Ok(accept.prediction)
        } else {
            if _t == EOF && lexer.input().index() == self.start_index {
                return Ok(TOKEN_EOF);
            }
            Err(ANTLRError::lexer_no_alt(self.start_index))
        }
    }

    fn compute_start_state<'scratch, 'input, 'arena, Input, TF>(
        &self,
        p: &ATNState,
        lexer: &mut impl Lexer<'input, 'arena, Input, TF>,
        scratch: &'scratch bumpalo::Bump,
    ) -> MutableLexerATNConfigSet<'scratch>
    where
        'input: 'arena,
        'sim: 'scratch,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        start_state_core(
            self.atn(),
            p,
            &mut LazyClosureEnv::new(self, lexer),
            scratch,
        )
    }

    fn evaluate_predicate<'input, 'arena, Input, TF, T: Lexer<'input, 'arena, Input, TF>>(
        &self,
        rule_index: i32,
        pred_index: i32,
        speculative: bool,
        lexer: &mut T,
    ) -> bool
    where
        'input: 'arena,
        Input: CharStream<'input>,
        TF: TokenFactory<'input, 'arena> + 'arena,
    {
        if !speculative {
            return lexer.sempred(None, rule_index, pred_index);
        }

        let index = lexer.input().index();
        let marker = lexer.input().mark();
        self.consume(lexer.input());

        let result = lexer.sempred(None, rule_index, pred_index);

        lexer.input().seek(index);
        lexer.input().release(marker);
        result
    }

    fn capture_sim_state(
        &mut self,
        input: &impl IntStream,
        dfa_state: &'sim DFAState<'sim, LexerATNConfigSet<'sim>>,
    ) -> bool {
        if dfa_state.is_accept_state() {
            // Resolve the DFAState into a ResolvedAccept here, so the
            // accept slot has one form for lazy states and for the table
            // accepts the static walker carries.
            self.prev_accept = Some(ResolvedAccept {
                index: input.index(),
                prediction: dfa_state.prediction(),
                executor: dfa_state.lexer_action_executor().map(AcceptExecutor::Lazy),
            });
            return true;
        }
        false
    }

    fn add_dfaedge(
        &self,
        dfa: &'sim DFA<LexerATNConfigSet<'sim>>,
        from: &'sim DFAState<'sim, LexerATNConfigSet<'sim>>,
        t: i32,
        to: &'sim DFAState<'sim, LexerATNConfigSet<'sim>>,
    ) {
        if !(MIN_DFA_EDGE..=MAX_DFA_EDGE).contains(&t) {
            return;
        }

        dfa.set_edge(from, (t - MIN_DFA_EDGE) as usize, to);
    }

    fn add_dfastate<'scratch>(
        &self,
        dfa: &'sim DFA<LexerATNConfigSet<'sim>>,
        configs: MutableLexerATNConfigSet<'scratch>,
    ) -> Result<&'sim DFAState<'sim, LexerATNConfigSet<'sim>>, ANTLRError> {
        assert!(!configs.has_semantic_context());

        let state = ProposedDFAState::new(configs);

        self.base.check_allocation_limit()?;
        Ok(dfa.add_lexer_state(state, self))
    }

    /// Returns current DFA that is currently used.
    pub fn get_dfa(&self) -> &'sim DFA<'sim, LexerATNConfigSet<'sim>> {
        self.decision_to_dfa(self.mode)
            .expect("self.mode should be valid")
    }

    /// Returns current DFA for particular lexer mode
    pub fn get_dfa_for_mode(&self, mode: usize) -> &'sim DFA<'sim, LexerATNConfigSet<'sim>> {
        self.decision_to_dfa(mode).expect("mode should be valid")
    }

    /// Returns the current size of the DFA cache in bytes.
    pub fn total_allocated_bytes(&self) -> usize {
        self.base.total_allocated_bytes()
    }

    // fn get_token_name(&self, _tt: i32) -> String { unimplemented!() }
}

/// The best accept seen so far in a token match, with the action source
/// resolved. The lazy path resolves a DFAState into this form at capture
/// time; the table walker carries it directly, so table accepts and lazy
/// accepts share `fail_or_accept`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ResolvedAccept<'sim> {
    index: isize,
    prediction: i32,
    executor: Option<AcceptExecutor<'sim>>,
}

/// The lexer actions of a resolved accept.
#[derive(Debug, Clone, Copy)]
pub(crate) enum AcceptExecutor<'sim> {
    /// The executor of a lazy DFA accept state.
    Lazy(&'sim LexerActionExecutor<'sim>),
    /// The position-independent action list of a static table accept state.
    Static(&'static [crate::lexer_action::LexerAction<'static>]),
}

/// Consume a maximal run of self-looping bytes of an accelerated state,
/// starting at byte index `c` in `hay`, and return the index of the first
/// byte that does not loop.
#[inline(never)]
fn run_scan(hay: &[u8], mut c: usize, accel: Accel, scratch: &bumpalo::Bump) -> usize {
    match accel {
        Accel::Positive(bitmap) => {
            while c < hay.len() {
                let b = hay[c];
                if b < 0x80 && (bitmap >> b) & 1 != 0 {
                    c += 1;
                } else {
                    break;
                }
            }
        }
        Accel::Exclude(needle) => match memchr::memchr(needle, &hay[c..]) {
            None => c = hay.len(),
            Some(i) => c += i,
        },
        Accel::Exclude2(needle1, needle2) => match memchr::memchr2(needle1, needle2, &hay[c..]) {
            None => c = hay.len(),
            Some(i) => c += i,
        },
        Accel::Exclude3(needle1, needle2, needle3) => {
            match memchr::memchr3(needle1, needle2, needle3, &hay[c..]) {
                None => c = hay.len(),
                Some(i) => c += i,
            }
        }
        Accel::CountedExclusion {
            ref opener,
            ref closer,
            n,
        } => {
            c = run_scan_counted(
                hay,
                c,
                &opener[..n as usize],
                &closer[..n as usize],
                scratch,
            );
        }
    }
    c
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum CountedEntry {
    Body(u32),
    Close(u8, u32),
    Open(u8, u32),
}

fn push_unique(vec: &mut bumpalo::collections::Vec<CountedEntry>, entry: CountedEntry) {
    if !vec.contains(&entry) {
        vec.push(entry);
    }
}

fn run_scan_counted(
    hay: &[u8],
    mut c: usize,
    opener: &[u8],
    closer: &[u8],
    scratch: &bumpalo::Bump,
) -> usize {
    let start = c;
    let n = opener.len();
    let o0 = opener[0];
    let c0 = closer[0];

    while c + n <= hay.len() {
        let Some(i) = memchr::memchr2(o0, c0, &hay[c..]) else {
            return hay.len();
        };
        let pos = c + i;
        if pos + n > hay.len() {
            return hay.len();
        }
        let slice = &hay[pos..pos + n];
        if slice == closer {
            return pos;
        }
        if slice == opener {
            c = pos.saturating_sub(n - 1).max(start);
            break;
        }
        c = pos + 1;
    }
    if c + n > hay.len() {
        return hay.len();
    }

    let mut state = bumpalo::vec![in scratch; CountedEntry::Body(0)];
    let mut next = bumpalo::collections::Vec::with_capacity_in(8, scratch);
    let mut last_closer = hay.len();

    while c < hay.len() {
        let has_partial = state.iter().any(|e| !matches!(e, CountedEntry::Body(_)));
        if !has_partial {
            let Some(i) = memchr::memchr2(o0, c0, &hay[c..]) else {
                break;
            };
            c += i;
        }
        let b = hay[c];
        next.clear();
        for &entry in &state {
            match entry {
                CountedEntry::Close(idx, d) => {
                    if b == closer[idx as usize] {
                        if idx as usize + 1 == n {
                            if d == 0 {
                                last_closer = c + 1 - n;
                                break;
                            }
                            push_unique(&mut next, CountedEntry::Body(d - 1));
                        } else {
                            push_unique(&mut next, CountedEntry::Close(idx + 1, d));
                        }
                    }
                }
                CountedEntry::Open(idx, d) => {
                    if b == opener[idx as usize] {
                        if idx as usize + 1 == n {
                            push_unique(&mut next, CountedEntry::Body(d));
                        } else {
                            push_unique(&mut next, CountedEntry::Open(idx + 1, d));
                        }
                    }
                }
                CountedEntry::Body(d) => {
                    if b == c0 {
                        if n == 1 {
                            if d == 0 {
                                last_closer = c;
                                break;
                            }
                            push_unique(&mut next, CountedEntry::Body(d - 1));
                        } else {
                            push_unique(&mut next, CountedEntry::Close(1, d));
                        }
                    }
                    if b == o0 {
                        if n == 1 {
                            push_unique(&mut next, CountedEntry::Body(d + 1));
                        } else {
                            push_unique(&mut next, CountedEntry::Open(1, d + 1));
                        }
                    }
                    push_unique(&mut next, CountedEntry::Body(d));
                }
            }
        }
        std::mem::swap(&mut state, &mut next);
        if state.is_empty() {
            return last_closer;
        }
        c += 1;
    }
    last_closer
}

/// Environment that the lexer move/closure core reads runtime input facts
/// from: the absolute input index (used to fix position-dependent lexer
/// action offsets at move time) and the predicate evaluation.
///
/// The lazy simulator drives the core through [`LazyClosureEnv`], which
/// evaluates predicates against the live input. The static lexer DFA builder
/// (feature `static-dfa-build`) drives the same core headless: it reports a
/// fixed input index and evaluates every predicate as `true`, so the builder
/// reproduces the lazy config sets exactly when no predicate is involved.
pub(crate) trait LexerClosureEnv {
    /// The absolute input index at the move step.
    fn input_index(&mut self) -> isize;

    /// Evaluate one lexer predicate.
    fn eval_predicate(&mut self, rule_index: i32, pred_index: i32, speculative: bool) -> bool;
}

/// The [`LexerClosureEnv`] of the lazy simulator: delegates to the live lexer.
struct LazyClosureEnv<'a, 'sim, L, Input, TF> {
    sim: &'a LexerATNSimulator<'sim>,
    lexer: &'a mut L,
    _marker: std::marker::PhantomData<fn() -> (Input, TF)>,
}

impl<'a, 'sim, L, Input, TF> LazyClosureEnv<'a, 'sim, L, Input, TF> {
    fn new(sim: &'a LexerATNSimulator<'sim>, lexer: &'a mut L) -> Self {
        LazyClosureEnv {
            sim,
            lexer,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<'input, 'arena, Input, TF, L> LexerClosureEnv for LazyClosureEnv<'_, '_, L, Input, TF>
where
    'input: 'arena,
    Input: CharStream<'input>,
    TF: TokenFactory<'input, 'arena> + 'arena,
    L: Lexer<'input, 'arena, Input, TF>,
{
    fn input_index(&mut self) -> isize {
        self.lexer.input().index()
    }

    fn eval_predicate(&mut self, rule_index: i32, pred_index: i32, speculative: bool) -> bool {
        self.sim
            .evaluate_predicate(rule_index, pred_index, speculative, &mut *self.lexer)
    }
}

/// Capture of one move step, requested by the static lexer DFA builder only.
/// The lazy path passes `None` and pays no cost.
#[derive(Debug, Default)]
pub(crate) struct ReachCapture<'scratch> {
    /// The post-move, pre-closure configs in move order. Each config carries
    /// the `current_alt_reached_accept_state` flag its closure ran with.
    pub(crate) moved: Vec<(LexerATNConfig<'scratch>, bool)>,
    /// True when the move step set `skip_alt` and broke out of the transition
    /// loop early. The build-time pruning decision then depends on the
    /// build-time closure results, so an escaping edge must not bake the
    /// moved configs into a continuation.
    pub(crate) pruning_activity: bool,
}

/// The start-state computation of [`LexerATNSimulator`], callable without a
/// live lexer through [`LexerClosureEnv`].
pub(crate) fn start_state_core<'scratch>(
    atn: &ATN,
    p: &ATNState,
    env: &mut impl LexerClosureEnv,
    scratch: &'scratch bumpalo::Bump,
) -> MutableLexerATNConfigSet<'scratch> {
    //        let initial_context = &EMPTY_PREDICTION_CONTEXT;
    let mut config_set = MutableLexerATNConfigSet::new(scratch);
    for (i, tr) in p.get_transitions().iter().enumerate() {
        let target = tr.get_target();
        let atn_config =
            LexerATNConfig::new(target, (i + 1) as i32, PredictionContextRef::new_empty());
        closure_core(
            atn,
            atn_config,
            &mut config_set,
            false,
            false,
            false,
            env,
            scratch,
        );
    }

    config_set
}

/// The move+closure step of [`LexerATNSimulator::get_reachable_config_set`],
/// callable without a live lexer through [`LexerClosureEnv`].
#[allow(clippy::too_many_arguments)]
pub(crate) fn reachable_core<'scratch, 'a>(
    atn: &ATN,
    start_index: isize,
    source: impl Iterator<Item = &'a LexerATNConfig<'scratch>>,
    reach: &mut MutableLexerATNConfigSet<'scratch>,
    t: i32,
    env: &mut impl LexerClosureEnv,
    mut capture: Option<&mut ReachCapture<'scratch>>,
    scratch: &'scratch bumpalo::Bump,
) where
    'scratch: 'a,
{
    let mut skip_alt = 0;
    //        println!(" --- source {:?}", _closure.configs.iter().map(|it|it.get_state()).collect::<Vec<_>>());
    for config in source {
        let current_alt_reached_accept_state = config.get_alt() == skip_alt;
        if current_alt_reached_accept_state && config.has_passed_through_non_greedy_decision() {
            continue;
        }
        let atn_state = config.get_state();
        for tr in atn_state.get_transitions() {
            if let Some(target) = tr.get_reachable_target(t) {
                let exec = config.get_lexer_executor().map(|x| {
                    scratch
                        .alloc(x.fix_offset_before_match(scratch, env.input_index() - start_index))
                        as &'scratch LexerActionExecutor<'scratch>
                });

                let new = config.clone().with_state(target).with_lexer_executor(exec);
                if let Some(capture) = capture.as_deref_mut() {
                    capture
                        .moved
                        .push((new.clone(), current_alt_reached_accept_state));
                }
                if closure_core(
                    atn,
                    new,
                    reach,
                    current_alt_reached_accept_state,
                    true,
                    t == EOF,
                    env,
                    scratch,
                ) {
                    skip_alt = config.get_alt();
                    if let Some(capture) = capture.as_deref_mut() {
                        capture.pruning_activity = true;
                    }
                    break;
                }
            }
        }
    }
}

/// The closure computation of [`LexerATNSimulator`], callable without a live
/// lexer through [`LexerClosureEnv`].
#[allow(clippy::too_many_arguments)]
pub(crate) fn closure_core<'scratch>(
    atn: &ATN,
    mut config: LexerATNConfig<'scratch>,
    config_set: &mut MutableLexerATNConfigSet<'scratch>,
    mut _current_alt_reached_accept_state: bool,
    speculative: bool,
    treat_eofas_epsilon: bool,
    env: &mut impl LexerClosureEnv,
    scratch: &'scratch bumpalo::Bump,
) -> bool {
    let state = config.get_state();
    //        println!("closure called on state {} {:?}", state.get_state_number(), state.get_state_type());

    if state.state_type() == ATNStateType::RuleStop {
        //            println!("reached rulestopstate {}",state.get_state_number());
        if config.get_context().map(|x| x.has_empty_path()) != Some(false) {
            if config.get_context().map(|x| x.is_empty()) != Some(false) {
                config_set.add(config);
                return true;
            } else {
                config_set.add(
                    config
                        .clone()
                        .with_state(state)
                        .with_prediction_context(Some(PredictionContextRef::new_empty())),
                );
                _current_alt_reached_accept_state = true
            }
        }

        if config.get_context().map(|x| x.is_empty()) == Some(false) {
            let ctx = config.take_context();
            for i in 0..ctx.length() {
                if ctx.get_return_state(i) != ATNStateRef::invalid() {
                    let new_ctx = ctx.get_parent(i);
                    let return_state = ctx.get_return_state(i);
                    let next_config = config
                        .clone()
                        .with_state(return_state)
                        .with_prediction_context(new_ctx);
                    _current_alt_reached_accept_state = closure_core(
                        atn,
                        next_config,
                        config_set,
                        _current_alt_reached_accept_state,
                        speculative,
                        treat_eofas_epsilon,
                        env,
                        scratch,
                    )
                }
            }
        }

        return _current_alt_reached_accept_state;
    }

    if !state.has_epsilon_only_transitions()
        && (!_current_alt_reached_accept_state || !config.has_passed_through_non_greedy_decision())
    {
        config_set.add(config.clone());
    }

    let state = config.get_state();
    let config = scratch.alloc(config);

    for tr in state.get_transitions() {
        let c = epsilon_target_core(
            atn,
            config,
            tr,
            config_set,
            speculative,
            treat_eofas_epsilon,
            env,
            scratch,
        );

        if let Some(c) = c {
            _current_alt_reached_accept_state = closure_core(
                atn,
                c,
                config_set,
                _current_alt_reached_accept_state,
                speculative,
                treat_eofas_epsilon,
                env,
                scratch,
            );
        }
    }

    _current_alt_reached_accept_state
}

/// One epsilon step of [`closure_core`].
#[allow(clippy::too_many_arguments)]
fn epsilon_target_core<'scratch>(
    atn: &ATN,
    //        _input: &mut dyn CharStream,
    _config: &'scratch LexerATNConfig<'scratch>,
    _trans: &Transition,
    _configs: &mut MutableLexerATNConfigSet<'scratch>,
    _speculative: bool,
    _treat_eofas_epsilon: bool,
    env: &mut impl LexerClosureEnv,
    scratch: &'scratch bumpalo::Bump,
) -> Option<LexerATNConfig<'scratch>> {
    let mut result = None;
    let target = _trans.get_target();
    //        println!("epsilon target for {:?} is {:?}", _trans, target.get_state_type());
    match _trans.transition_type() {
        TransitionType::Epsilon => {
            result = Some(_config.clone().with_state(target));
        }
        TransitionType::Rule => {
            let rt = _trans
                .try_as::<crate::transition::RuleTransition>()
                .unwrap();
            //println!("rule transition follow state{}", rt.follow_state);
            let pred_ctx = PredictionContext::new_singleton(
                Some(_config.get_context().unwrap()),
                rt.follow_state,
            );
            result = Some(
                _config
                    .clone()
                    .with_state(target)
                    .with_prediction_context(Some(scratch.alloc(pred_ctx))),
            );
        }
        TransitionType::Predicate => {
            let tr = _trans
                .try_as::<crate::transition::PredicateTransition>()
                .unwrap();
            _configs.set_has_semantic_context(true);
            if env.eval_predicate(tr.rule_index(), tr.pred_index(), _speculative) {
                result = Some(_config.clone().with_state(target));
            }
        }
        TransitionType::Action => {
            //println!("action transition");
            if _config.get_context().map(|x| x.has_empty_path()) != Some(false) {
                let tr = _trans
                    .try_as::<crate::transition::ActionTransition>()
                    .unwrap();
                let lexer_action = atn.lexer_actions[tr.action_index() as usize].clone();
                //dbg!(&lexer_action);
                let lexer_action_executor = LexerActionExecutor::new_copy_append(
                    scratch,
                    _config.get_lexer_executor(),
                    lexer_action,
                );
                result = Some(
                    _config
                        .clone()
                        .with_state(target)
                        .with_lexer_executor(Some(scratch.alloc(lexer_action_executor))),
                )
            } else {
                result = Some(_config.clone().with_state(target));
            }
        }
        TransitionType::Range | TransitionType::Set | TransitionType::Atom => {
            if _treat_eofas_epsilon
                && _trans.matches(EOF, LEXER_MIN_CHAR_VALUE, LEXER_MAX_CHAR_VALUE)
            {
                let target = _trans.get_target();
                result = Some(_config.clone().with_state(target));
            }
        }
        TransitionType::Wildcard => {}
        TransitionType::NotSet => {}
        TransitionType::PrecedencePredicate => {
            panic!("precedence predicates are not supposed to be in lexer");
        }
    }

    result
}