dbt-antlr-codegen 0.10.0

ANTLR v4 grammar compiler and Rust source generator
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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! Build-time SLL closure over the ATN.
//!
//! The lazy simulator's closure assumes there is an input stream: recursion is
//! cut off by the tokens running out, predicates are evaluated against the
//! live parser, and a rule stop pops the caller frame that pushed it. None of
//! that holds at build time, so this module runs the same closure *shape* over
//! a different policy:
//!
//! - **Widening.** A rule call whose returned context would exceed the depth
//!   bound, or would re-enter a return state already on the context path, is
//!   widened: the callee starts from the empty context and the config is
//!   marked [`WIDENED_TAINT`]. That is what makes recursive grammars
//!   terminate. The joints that were widened are remembered, because a
//!   conflict whose witness passes through one is not faithful to the runtime
//!   context and must not be trusted.
//! - **Boundary chase.** A config that reaches a rule stop with an empty
//!   context has left the decision; the runtime would pop the real caller.
//!   The build has no caller, so the config is marked
//!   [`BOUNDARY_TAINT`] and the closure continues through the grammar-wide
//!   FOLLOW links of that rule stop ("some caller"). Chased configs are
//!   tracked with a negative depth so their pop bookkeeping stays separate.
//! - **Symbolic predicates.** Predicate transitions pass through and mark
//!   the config with [`PRED_TAINT`]; the decision reports the first predicate
//!   it crossed. Precedence predicates are resolved from the *statically
//!   known* precedence class currently being built, or, when the class is not
//!   known, from the call sites recorded on the context path.
//!
//! Taints are kept in a side map keyed by `(state number, alternative)`
//! instead of on the configs themselves: [`ATNConfig`] identity ignores
//! `reaches_into_outer_context`, so a tainted and an untainted path to the
//! same config merge in the set, and OR-ing the side map is what preserves
//! the union of both paths' taints.

use std::collections::{BTreeSet, HashMap, HashSet};

use dbt_antlr_runtime::analysis::{
    ATN, ATNConfig, ATNStateRef, ATNStateType, BOUNDARY_TAINT, BitSet, Bump, EOF,
    FOREIGN_CONSUME_TAINT, FOREIGN_LINEAGE_TAINT, INTERIOR_TAINT, IntervalSetBuf, MIDWAY_TAINT,
    MergeCache, MutableATNConfigSet, NotSetTransition, PRECPRED_TAINT, PRED_TAINT,
    PrecedencePredicateTransition, PredicateTransition, PredictionContext, PredictionContextRef,
    ROOTED_TAINT, RuleTransition, TOKEN_MIN_USER_TOKEN_TYPE, TransitionType, WIDENED_TAINT,
};

use super::loop_block::LoopBlock;
use super::postfix::{PostfixShape, collect_guard_roots};

/// The alternative of an optional-postfix decision that skips the postfix
/// element.
const POSTFIX_SKIP_ALT: i32 = 2;

/// The alternative of a precedence loop's exit branch.
const ITERATE_EXIT_ALT: i32 = 2;

/// Union of the taints of every path that reached a closed config, keyed by
/// `(ATN state number, alternative)`.
pub(super) type Taint = HashMap<(i32, i32), i32>;

/// Union of the guard roots of every path that reached a closed config, keyed
/// like [`Taint`]. A config without roots has no entry.
///
/// A root rides on the lineage of the configuration that consumed outside the
/// decision's discipline. When that lineage dies on a later token, its roots
/// die with it, so a guarded state only carries the roots of the readings that
/// are still alive there.
pub(super) type GuardRoots = HashMap<(i32, i32), BTreeSet<i32>>;

/// A closed config set with the taints of the paths that produced it.
///
/// The configs are *not* merged here: like the reference Java tool, the
/// closure keeps every distinct `(state, alt, context)` it produced, and the
/// contexts are merged only once the set is finished (see
/// [`Closure::config_set`]). Merging during the closure would feed
/// analysis-only merged contexts back into the closure, and the successor sets
/// would stop corresponding to the states the runtime actually visits.
pub(super) struct ClosedSet<'a> {
    pub(super) configs: Vec<ATNConfig<'a>>,
    pub(super) taint: Taint,
    pub(super) roots: GuardRoots,
}

impl ClosedSet<'_> {
    /// The taint recorded for one config of the set.
    pub(super) fn taint_of(&self, config: &ATNConfig<'_>) -> i32 {
        taint_of(&self.taint, config)
    }
}

/// Whether a boundary-popped config with `context` is in the frame that it
/// popped into. The boundary chase gives that frame the empty context, and an
/// invocation started from it pushes a frame on top.
pub(super) fn in_popped_frame(context: Option<PredictionContextRef<'_>>) -> bool {
    context.is_none_or(|context| context.has_empty_path())
}

/// The positions of rule `rule_index` that still owe input before an epsilon
/// path reaches `stop`: some epsilon path that avoids `stop` reaches a token or
/// a rule call of the rule.
pub(super) fn positions_owing_input(atn: &ATN, rule_index: i32, stop: ATNStateRef) -> BitSet {
    let mut owing = BitSet::new();
    for state in atn.iter_states() {
        if state.get_rule_index() != rule_index {
            continue;
        }
        let start = atn.make_state_ref(state.get_state_number());
        let mut visited = BitSet::new();
        let mut work = vec![start];
        'walk: while let Some(current) = work.pop() {
            if current == stop
                || current.get_rule_index() != rule_index
                || current.state_type() == ATNStateType::RuleStop
                || !visited.insert(current.get_state_number() as usize)
            {
                continue;
            }
            for transition in current.get_transitions() {
                if !transition.is_epsilon() || transition.try_as::<RuleTransition>().is_some() {
                    owing.insert(state.get_state_number() as usize);
                    break 'walk;
                }
                work.push(transition.get_target());
            }
        }
    }
    owing
}

/// The positions of the rule of `start` that `start` reaches inside that rule:
/// rule calls contribute their follow states, and the walk stops at the rule
/// stop and at `end`.
pub(super) fn rule_positions(start: ATNStateRef, end: Option<ATNStateRef>) -> BitSet {
    let rule_index = start.get_rule_index();
    let mut states = BitSet::new();
    let mut work = vec![start];
    while let Some(state) = work.pop() {
        if Some(state) == end
            || state.get_rule_index() != rule_index
            || state.state_type() == ATNStateType::RuleStop
            || !states.insert(state.get_state_number() as usize)
        {
            continue;
        }
        for transition in state.get_transitions() {
            work.push(match transition.try_as::<RuleTransition>() {
                Some(rule) => rule.follow_state,
                None => transition.get_target(),
            });
        }
    }
    states
}

/// The taint recorded for one config of a set closed under `taint`.
pub(super) fn taint_of(taint: &Taint, config: &ATNConfig<'_>) -> i32 {
    taint
        .get(&(config.get_state().get_state_number(), config.get_alt()))
        .copied()
        .unwrap_or(0)
}

/// The precedence class a precedence-loop decision is being built for.
///
/// `eval_value` stands in for the precedence the parser will have when the
/// decision runs: the class is `lo..=hi` and the closure may only take
/// `PrecedencePredicateTransition`s whose predicate holds for it.
#[derive(Clone, Copy, Debug)]
pub(super) struct PrecedenceClass {
    pub(super) rule_index: i32,
    pub(super) eval_value: i32,
    pub(super) lo: i32,
    pub(super) hi: i32,
}

/// What one build attempt observed while closing config sets.
#[derive(Debug, Default)]
pub(super) struct ClosureFacts {
    pub(super) first_predicate: Option<(i32, i32)>,
}

#[derive(Clone, Copy, Debug)]
struct CallInfo {
    target_rule_index: i32,
    precedence: i32,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct RuleCall {
    /// The invoking state.
    pub(super) site: i32,
    /// The rule of the invoking state.
    pub(super) caller_rule: i32,
    /// The follow state: the return state that the call pushes.
    pub(super) follow: i32,
    /// The precedence argument of the call.
    pub(super) precedence: i32,
}

#[derive(Debug, Default)]
pub(super) struct CallSites {
    /// The state that makes each invocation, for the guard-root analysis of
    /// optional-postfix and precedence-loop decisions.
    site_by_follow_state: HashMap<i32, i32>,
    /// The rule and the precedence of each invocation.
    call_by_follow_state: HashMap<i32, CallInfo>,
    /// The invocations of each rule, by the rule index of the called rule, in
    /// ATN state order.
    calls_to_rule: Vec<Vec<RuleCall>>,
}

impl CallSites {
    pub(super) fn of(atn: &ATN) -> Self {
        let mut sites = Self {
            calls_to_rule: vec![Vec::new(); atn.rule_to_start_state.len()],
            ..Self::default()
        };
        for state in atn.iter_states() {
            for transition in state.get_transitions() {
                if let Some(rule_transition) = transition.try_as::<RuleTransition>() {
                    let follow_state = rule_transition.follow_state.get_state_number();
                    let target_rule_index = rule_transition.get_target().get_rule_index();
                    sites
                        .site_by_follow_state
                        .insert(follow_state, state.get_state_number());
                    sites.call_by_follow_state.insert(
                        follow_state,
                        CallInfo {
                            target_rule_index,
                            precedence: rule_transition.precedence(),
                        },
                    );
                    if let Some(calls) = usize::try_from(target_rule_index)
                        .ok()
                        .and_then(|rule| sites.calls_to_rule.get_mut(rule))
                    {
                        calls.push(RuleCall {
                            site: state.get_state_number(),
                            caller_rule: state.get_rule_index(),
                            follow: follow_state,
                            precedence: rule_transition.precedence(),
                        });
                    }
                }
            }
        }
        sites
    }

    /// The invocations of the rule `rule`.
    pub(super) fn calls_to(&self, rule: i32) -> &[RuleCall] {
        usize::try_from(rule)
            .ok()
            .and_then(|rule| self.calls_to_rule.get(rule))
            .map_or(&[], Vec::as_slice)
    }
}

/// The interned guard-root sets of one closure, so that the closure can pass
/// a root set down its recursion as one number. Set `0` is the empty set.
struct RootPool {
    sets: Vec<BTreeSet<i32>>,
    ids: HashMap<BTreeSet<i32>, u32>,
}

impl RootPool {
    fn new() -> Self {
        Self {
            sets: vec![BTreeSet::new()],
            ids: HashMap::from([(BTreeSet::new(), 0)]),
        }
    }

    fn intern(&mut self, set: BTreeSet<i32>) -> u32 {
        if let Some(&id) = self.ids.get(&set) {
            return id;
        }
        let id = self.sets.len() as u32;
        self.sets.push(set.clone());
        self.ids.insert(set, id);
        id
    }

    fn get(&self, id: u32) -> &BTreeSet<i32> {
        &self.sets[id as usize]
    }
}

/// One config that a successor set starts from: a rule-stop config that
/// reads EOF, or the config after a token transition.
#[derive(Clone, PartialEq, Eq, Hash)]
struct Step<'a> {
    stop: bool,
    config: ATNConfig<'a>,
    /// A copy of `config.reaches_into_outer_context`. The equality of
    /// `ATNConfig` ignores most bits of that field.
    outer: i32,
    taint: i32,
    /// The [`RootPool`] set of the guard roots of the step.
    roots: u32,
}

/// The configs produced by one closure root, in insertion order.
struct SetBuilder<'a> {
    configs: Vec<ATNConfig<'a>>,
    seen: HashSet<ATNConfig<'a>>,
    taint: Taint,
    roots: GuardRoots,
    /// The explored `(config, taint, chasing)` keys with the depth of their
    /// first exploration and the guard roots they were explored with.
    busy: HashMap<(ATNConfig<'a>, i32, bool), (i32, BTreeSet<i32>)>,
}

impl<'a> SetBuilder<'a> {
    fn new() -> Self {
        Self {
            configs: Vec::new(),
            seen: HashSet::new(),
            taint: Taint::new(),
            roots: GuardRoots::new(),
            busy: HashMap::new(),
        }
    }

    fn record(&mut self, config: &ATNConfig<'a>, taint: i32, roots: &BTreeSet<i32>) {
        let key = (config.get_state().get_state_number(), config.get_alt());
        let slot = self.taint.entry(key).or_insert(0);
        *slot |= taint;
        if taint & BOUNDARY_TAINT == 0 {
            // Remember that this config is reachable without popping the
            // decision boundary: a later boundary-pop path must not turn the
            // usage into "all configs crossed the boundary".
            *slot |= INTERIOR_TAINT;
        }
        if !roots.is_empty() {
            self.roots
                .entry(key)
                .or_default()
                .extend(roots.iter().copied());
        }
    }

    fn insert(&mut self, config: ATNConfig<'a>, taint: i32, roots: &BTreeSet<i32>) {
        self.record(&config, taint, roots);
        if self.seen.insert(config.clone()) {
            self.configs.push(config);
        }
    }

    fn into_closed_set(self) -> ClosedSet<'a> {
        ClosedSet {
            configs: self.configs,
            taint: self.taint,
            roots: self.roots,
        }
    }
}

/// The build-time closure of one ATN.
pub(super) struct Closure<'atn, 'a> {
    atn: &'atn ATN,
    scratch: &'a Bump,
    merge: MergeCache<'a>,
    pub(super) facts: ClosureFacts,
    precedence: Option<PrecedenceClass>,
    depth_cache: HashMap<usize, i32>,
    call_sites: &'a CallSites,
    /// Widening bound of the current attempt: `i32::MAX` for the default
    /// attempt, `0` for the fully widened one.
    depth_bound: i32,
    /// `true` while the start closure of a precedence class runs: precedence
    /// predicates there are evaluated against the class, not the context.
    precedence_start: bool,
    /// The operator-loop block of a precedence-class build: consumption by a
    /// boundary-popped configuration outside it is foreign to the loop (see
    /// [`LoopBlock`]).
    loop_block: Option<LoopBlock>,
    /// The optional-postfix shape of the decision, when it has one: skip
    /// consumption outside its discipline records guard roots.
    postfix: Option<PostfixShape>,
    /// The decision state of the build, set by [`Closure::start`].
    decision_state: ATNStateRef,
    /// Configs visited by this closure, across all roots of the attempt.
    visits: u64,
    /// The visited configs by the rule index of their ATN state.
    rule_visits: Vec<u64>,
    visit_budget: u64,
    /// Set when the visit budget ran out. The config sets that the closure
    /// builds after this are not complete. The attempt then escapes the state
    /// that it expands, or fails at the start state (see
    /// `DecisionBuild::run`).
    pub(super) exhausted: bool,
    /// The guard-root sets of the closure.
    roots: RootPool,
    /// The [`RootPool`] set of the closure root that runs now: every config
    /// that the root reaches gets its roots.
    current_roots: u32,
    /// `true` while the closure explores known configs again only to give
    /// them more guard roots.
    propagating_roots: bool,
}

impl<'atn, 'a> Closure<'atn, 'a> {
    #[expect(clippy::too_many_arguments)]
    pub(super) fn new(
        atn: &'atn ATN,
        call_sites: &'a CallSites,
        scratch: &'a Bump,
        depth_bound: i32,
        precedence: Option<PrecedenceClass>,
        loop_block: Option<LoopBlock>,
        postfix: Option<PostfixShape>,
        visit_budget: u64,
    ) -> Self {
        Self {
            atn,
            scratch,
            merge: MergeCache::new(scratch),
            facts: ClosureFacts::default(),
            precedence,
            depth_cache: HashMap::new(),
            call_sites,
            depth_bound,
            precedence_start: false,
            loop_block,
            postfix,
            decision_state: ATNStateRef::invalid(),
            visits: 0,
            rule_visits: vec![0; atn.rule_to_start_state.len()],
            visit_budget,
            exhausted: false,
            roots: RootPool::new(),
            current_roots: 0,
            propagating_roots: false,
        }
    }

    /// The operator-loop analysis of this precedence-class build, when the
    /// decision is a precedence loop.
    pub(super) fn loop_block(&self) -> Option<&LoopBlock> {
        self.loop_block.as_ref()
    }

    /// The configs this closure visited, at most the visit budget.
    pub(super) fn visits(&self) -> u64 {
        self.visits.min(self.visit_budget)
    }

    pub(super) fn remaining_visits(&self) -> u64 {
        self.visit_budget.saturating_sub(self.visits)
    }

    pub(super) fn successors_capped(
        &mut self,
        closed: &ClosedSet<'a>,
        max_call_visits: u64,
    ) -> (Vec<(IntervalSetBuf, ClosedSet<'a>)>, bool) {
        let global_budget = self.visit_budget;
        let remaining_global = global_budget.saturating_sub(self.visits);
        if max_call_visits >= remaining_global {
            let successors = self.successors(closed);
            return (successors, self.exhausted);
        }
        let capped_budget = self.visits.saturating_add(max_call_visits);
        self.visit_budget = capped_budget;
        let successors = self.successors(closed);
        let hit_cap = self.exhausted;
        self.visit_budget = global_budget;
        if hit_cap {
            self.visits = self.visits.min(capped_budget);
            self.exhausted = false;
        }
        (successors, hit_cap)
    }

    /// Runs `analysis` with `visits` more configs to visit, and then restores
    /// the facts, the visit counts, and the budget state of the closure. An
    /// analysis after the construction thus does not change what the attempt
    /// reports. Returns `None` when the analysis spends its visits.
    pub(super) fn sandbox<R>(
        &mut self,
        visits: u64,
        analysis: impl FnOnce(&mut Self) -> Option<R>,
    ) -> Option<R> {
        let facts = std::mem::take(&mut self.facts);
        let rule_visits = self.rule_visits.clone();
        let (saved_visits, budget, exhausted) = (self.visits, self.visit_budget, self.exhausted);
        self.visit_budget = saved_visits.saturating_add(visits);
        self.exhausted = false;
        let result = analysis(self);
        let spent = self.exhausted;
        self.facts = facts;
        self.rule_visits = rule_visits;
        self.visits = saved_visits;
        self.visit_budget = budget;
        self.exhausted = exhausted;
        if spent { None } else { result }
    }

    /// Moves out the visited configs by the rule index of their ATN state.
    pub(super) fn take_rule_visits(&mut self) -> Vec<u64> {
        std::mem::take(&mut self.rule_visits)
    }

    /// Closes the start configurations of `decision_state`: one config per
    /// alternative, each starting from the empty prediction context.
    pub(super) fn start(&mut self, decision_state: ATNStateRef) -> ClosedSet<'a> {
        self.start_in(decision_state, PredictionContextRef::new_empty())
    }

    /// Closes the start configurations of `decision_state` on the parse stack
    /// `context`: one config per alternative.
    pub(super) fn start_in(
        &mut self,
        decision_state: ATNStateRef,
        context: PredictionContextRef<'a>,
    ) -> ClosedSet<'a> {
        let mut out = SetBuilder::new();
        self.decision_state = decision_state;
        self.precedence_start = self.precedence.is_some();
        for (index, transition) in decision_state.get_transitions().iter().enumerate() {
            let config = ATNConfig::new(transition.get_target(), (index + 1) as i32, Some(context));
            self.current_roots = 0;
            self.closure(config, 0, 0, &mut out);
        }
        self.precedence_start = false;
        let closed = out.into_closed_set();
        match self.precedence {
            Some(_) => self.apply_precedence_filter(closed),
            None => closed,
        }
    }

    /// The configs of `closed` after they read `token`, closed.
    pub(super) fn step(&mut self, closed: &ClosedSet<'a>, token: i32) -> ClosedSet<'a> {
        let mut out = SetBuilder::new();
        for config in &closed.configs {
            let mut taint = closed.taint_of(config);
            if taint & BOUNDARY_TAINT != 0 {
                taint &= !INTERIOR_TAINT;
            }
            let state = config.get_state();
            if state.state_type() == ATNStateType::RuleStop {
                if token == EOF {
                    out.insert(config.clone(), taint, &BTreeSet::new());
                }
                continue;
            }
            for transition in state.get_transitions() {
                let reads = !transition.is_epsilon()
                    && transition.matches(
                        token,
                        TOKEN_MIN_USER_TOKEN_TYPE,
                        self.atn.max_token_type,
                    );
                if !reads {
                    continue;
                }
                let step = self.consume(config, transition.get_target(), taint, 0);
                self.current_roots = 0;
                self.closure(step.config, step.taint, 0, &mut out);
                if self.exhausted {
                    return out.into_closed_set();
                }
            }
        }
        self.current_roots = 0;
        out.into_closed_set()
    }

    /// The call sites of the ATN.
    pub(super) fn call_sites(&self) -> &'a CallSites {
        self.call_sites
    }

    /// The precedence class of the build, when it builds one.
    pub(super) fn precedence(&self) -> Option<PrecedenceClass> {
        self.precedence
    }

    /// Runs `analysis` with the widening bound `depth_bound`, and then
    /// restores the bound of the attempt.
    pub(super) fn with_depth_bound<R>(
        &mut self,
        depth_bound: i32,
        analysis: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let saved = std::mem::replace(&mut self.depth_bound, depth_bound);
        let result = analysis(self);
        self.depth_bound = saved;
        result
    }

    /// The parse stack that the follow states `follows` push, the innermost
    /// frame first, on an empty stack.
    pub(super) fn call_stack(&mut self, follows: &[i32]) -> PredictionContextRef<'a> {
        let mut context = PredictionContextRef::new_empty();
        for &follow in follows.iter().rev() {
            let follow_state = self.atn.make_state_ref(follow);
            context = PredictionContextRef::from(self.scratch.alloc(
                PredictionContext::new_singleton(Some(context), follow_state),
            ));
        }
        context
    }

    /// The labeled successors of one closed set: the token intervals that can
    /// be read next, each with the set of configs that survives them.
    ///
    /// The alphabet is partitioned into equivalence classes: every interval in
    /// one class enables the same set of configs, so one successor set serves
    /// the whole class. Classes that start from the same steps share one
    /// closure and one successor.
    pub(super) fn successors(
        &mut self,
        closed: &ClosedSet<'a>,
    ) -> Vec<(IntervalSetBuf, ClosedSet<'a>)> {
        let all_tokens = self.all_tokens();
        let mut labels: Vec<IntervalSetBuf> = Vec::new();
        let mut step_of: Vec<usize> = Vec::new();
        let mut steps: Vec<Step<'a>> = Vec::new();
        let mut step_numbers: HashMap<Step<'a>, usize> = HashMap::new();
        let mut add_step = |label: IntervalSetBuf, step: Step<'a>| {
            let number = match step_numbers.get(&step) {
                Some(&number) => number,
                None => {
                    let number = steps.len();
                    steps.push(step.clone());
                    step_numbers.insert(step, number);
                    number
                }
            };
            labels.push(label);
            step_of.push(number);
        };

        for config in &closed.configs {
            let mut taint = closed.taint_of(config);
            if taint & BOUNDARY_TAINT != 0 {
                // A path that popped the boundary stays a boundary path; only
                // the interior paths mark the config as mixed usage.
                taint &= !INTERIOR_TAINT;
            }
            let roots = match closed
                .roots
                .get(&(config.get_state().get_state_number(), config.get_alt()))
            {
                Some(roots) => self.roots.intern(roots.clone()),
                None => 0,
            };
            let state = config.get_state();
            if state.state_type() == ATNStateType::RuleStop {
                let mut eof = IntervalSetBuf::new();
                eof.add_one(EOF);
                add_step(
                    eof,
                    Step {
                        stop: true,
                        config: config.clone(),
                        outer: config.reaches_into_outer_context,
                        taint,
                        roots,
                    },
                );
                continue;
            }
            for transition in state.get_transitions() {
                if transition.is_epsilon() {
                    continue;
                }
                let label = match transition.transition_type() {
                    TransitionType::NotSet => {
                        let not_set = transition.try_as::<NotSetTransition>().unwrap();
                        not_set
                            .get_label()
                            .unwrap()
                            .complement(TOKEN_MIN_USER_TOKEN_TYPE, self.atn.max_token_type)
                    }
                    TransitionType::Wildcard => all_tokens.clone(),
                    _ => match transition.get_label() {
                        Some(set) => set.to_interval_set_buf(),
                        None => continue,
                    },
                };
                if label.as_interval_set().as_slice().is_empty() {
                    continue;
                }
                add_step(
                    label,
                    self.consume(config, transition.get_target(), taint, roots),
                );
            }
        }

        let mut boundaries: Vec<i32> = Vec::new();
        for label in &labels {
            for interval in label.as_interval_set().as_slice() {
                boundaries.push(interval.a);
                boundaries.push(interval.b.saturating_add(1));
            }
        }
        boundaries.sort_unstable();
        boundaries.dedup();

        let mut classes: Vec<(BitSet, IntervalSetBuf)> = Vec::new();
        for window in boundaries.windows(2) {
            let (lo, hi) = (window[0], window[1] - 1);
            let mut key = BitSet::new();
            for (index, label) in labels.iter().enumerate() {
                if label.as_interval_set().contains(lo) {
                    key.insert(index);
                }
            }
            if key.is_empty() {
                continue;
            }
            match classes.last_mut() {
                Some((known, label)) if *known == key => label.add_range(lo, hi),
                _ => {
                    let mut label = IntervalSetBuf::new();
                    label.add_range(lo, hi);
                    classes.push((key, label));
                }
            }
        }

        let mut successors: Vec<(IntervalSetBuf, ClosedSet<'a>)> =
            Vec::with_capacity(classes.len());
        let mut successor_of: HashMap<Vec<usize>, usize> = HashMap::new();
        let mut seen = BitSet::with_capacity(steps.len());
        for (class, label) in classes {
            if self.exhausted {
                break;
            }
            seen.clear();
            let sequence: Vec<usize> = class
                .iter()
                .map(|index| step_of[index])
                .filter(|&number| seen.insert(number))
                .collect();
            if let Some(&known) = successor_of.get(&sequence) {
                successors[known].0.add_set(&label);
                continue;
            }
            let mut out = SetBuilder::new();
            for &number in &sequence {
                let step = &steps[number];
                self.current_roots = step.roots;
                if step.stop {
                    out.insert(step.config.clone(), step.taint, self.roots.get(step.roots));
                } else {
                    self.closure(step.config.clone(), step.taint, 0, &mut out);
                }
            }
            self.current_roots = 0;
            successor_of.insert(sequence, successors.len());
            successors.push((label, out.into_closed_set()));
        }
        successors
    }

    /// Builds the step after `source` reads a token into `target`. The step
    /// keeps the guard roots of `source` (the [`RootPool`] set `roots`).
    fn consume(
        &mut self,
        source: &ATNConfig<'a>,
        target: ATNStateRef,
        mut taint: i32,
        roots: u32,
    ) -> Step<'a> {
        let sites = &self.call_sites.site_by_follow_state;
        let mut new_roots: BTreeSet<i32> = BTreeSet::new();
        // A boundary-popped configuration consumes on behalf of "some caller".
        // When that caller is an enclosing invocation of this loop, the
        // consumption is the loop's own and the enter/exit substitution still
        // applies. Otherwise the consumer is foreign, and the substitution must
        // not fire.
        if let Some(block) = self.loop_block.as_ref()
            && taint & BOUNDARY_TAINT != 0
            && !block.is_loop_consumption(source.get_state(), source.get_context(), taint)
        {
            let in_loop = taint & (FOREIGN_LINEAGE_TAINT | MIDWAY_TAINT) == 0;
            taint |= FOREIGN_CONSUME_TAINT;
            if source.get_alt() == ITERATE_EXIT_ALT && taint & ROOTED_TAINT == 0 {
                taint |= ROOTED_TAINT;
                collect_guard_roots(
                    source.get_state(),
                    source.get_context(),
                    &|state| in_loop && block.is_loop_state(state),
                    sites,
                    &mut new_roots,
                );
            }
        }
        if let Some(postfix) = self.postfix.as_ref()
            && source.get_alt() == POSTFIX_SKIP_ALT
            && taint & ROOTED_TAINT == 0
            && !postfix.skip_mirrors(source.get_state(), source.get_context(), taint)
        {
            let in_take = taint & (FOREIGN_LINEAGE_TAINT | MIDWAY_TAINT) == 0;
            taint |= ROOTED_TAINT;
            collect_guard_roots(
                source.get_state(),
                source.get_context(),
                &|state| in_take && state == postfix.block_end_state,
                sites,
                &mut new_roots,
            );
        }
        let roots = if new_roots.is_empty() {
            roots
        } else {
            new_roots.extend(self.roots.get(roots).iter().copied());
            self.roots.intern(new_roots)
        };
        Step {
            stop: false,
            config: source.clone().with_state(target),
            outer: source.reaches_into_outer_context,
            taint,
            roots,
        }
    }

    /// Rebuilds a closed set in canonical order (state number, then
    /// alternative) so equal sets compare equal regardless of the order the
    /// closure happened to produce them in.
    ///
    /// The runtime DFA identifies a state by its config set, and that
    /// comparison walks both sets in insertion order. The closure reaches the
    /// same set through many paths in different insertion orders, so without
    /// this step every path would intern a fresh DFA state and the subset
    /// construction would never terminate on grammars with loops.
    pub(super) fn canonical_set(&mut self, closed: ClosedSet<'a>) -> ClosedSet<'a> {
        let set = self.config_set(&closed.configs);
        let mut configs: Vec<ATNConfig<'a>> = set.into_iter().collect();
        configs.sort_by_key(|config| (config.get_state().get_state_number(), config.get_alt()));
        ClosedSet {
            configs,
            taint: closed.taint,
            roots: closed.roots,
        }
    }

    /// The merged, runtime-shaped config set of a closed set, for the conflict
    /// predicates and for interning.
    pub(super) fn merged_config_set(&mut self, closed: &ClosedSet<'a>) -> MutableATNConfigSet<'a> {
        self.config_set(&closed.configs)
    }

    fn all_tokens(&self) -> IntervalSetBuf {
        let mut set = IntervalSetBuf::new();
        if self.atn.max_token_type >= TOKEN_MIN_USER_TOKEN_TYPE {
            set.add_range(TOKEN_MIN_USER_TOKEN_TYPE, self.atn.max_token_type);
        }
        set
    }

    /// Merges a finished config list into a runtime config set: contexts of
    /// configs that share `(state, alt)` are merged here, once, exactly as the
    /// runtime's `ATNConfigSet::add` would.
    pub(super) fn config_set(&mut self, configs: &[ATNConfig<'a>]) -> MutableATNConfigSet<'a> {
        let mut set = MutableATNConfigSet::new(self.scratch, false);
        for config in configs {
            // The analysis taint stays in the side map: writing it into the
            // config would make `ATNConfigSet::dips_into_outer_context` part of
            // the DFA state identity, so the same config set reached with
            // different taint would intern as two states and the builder
            // would never see the second path.
            set.add_cached(config.clone(), &mut self.merge);
        }
        set
    }

    /// Closes one config into `out`, with the guard roots of the closure root
    /// that runs now.
    ///
    /// A config that the set already explored with the same taint is only
    /// explored again for the roots that it did not carry yet. The configs
    /// such a pass reaches are the configs that the first pass reached, so
    /// the pass does not count visits on configs that are already known.
    fn closure(&mut self, config: ATNConfig<'a>, taint: i32, depth: i32, out: &mut SetBuilder<'a>) {
        if self.exhausted {
            return;
        }
        let chasing = depth < 0;
        let current = self.roots.get(self.current_roots);
        let missing = match out.busy.get_mut(&(config.clone(), taint, chasing)) {
            None => {
                out.busy
                    .insert((config.clone(), taint, chasing), (depth, current.clone()));
                None
            }
            Some((first_depth, explored)) => {
                let missing: BTreeSet<i32> = current.difference(explored).copied().collect();
                explored.extend(missing.iter().copied());
                Some((*first_depth, missing))
            }
        };
        if missing.is_none() || !self.propagating_roots {
            self.visits = self.visits.saturating_add(1);
            if self.visits > self.visit_budget {
                self.exhausted = true;
                return;
            }
            if let Some(visits) = usize::try_from(config.get_state().get_rule_index())
                .ok()
                .and_then(|rule| self.rule_visits.get_mut(rule))
            {
                *visits += 1;
            }
        }
        match missing {
            None => self.closure_body(config, taint, depth, out),
            // The config is already explored with this taint and these roots.
            // The taint of the config is already recorded, or the config never
            // joins the set.
            Some((_, missing)) if missing.is_empty() => {}
            // The pass repeats the first exploration, at its depth, so that it
            // reaches the same configs.
            Some((first_depth, missing)) => {
                let saved = (self.current_roots, self.propagating_roots);
                self.current_roots = self.roots.intern(missing);
                self.propagating_roots = true;
                self.closure_body(config, taint, first_depth, out);
                (self.current_roots, self.propagating_roots) = saved;
            }
        }
    }

    fn closure_body(
        &mut self,
        config: ATNConfig<'a>,
        mut taint: i32,
        depth: i32,
        out: &mut SetBuilder<'a>,
    ) {
        let state = config.get_state();
        if taint & MIDWAY_TAINT != 0
            && state == self.decision_state
            && in_popped_frame(config.get_context())
        {
            // The enclosing invocation finished the alternative that the
            // boundary chase returned into, and is back at its decision.
            taint &= !MIDWAY_TAINT;
        }

        if state.state_type() == ATNStateType::RuleStop {
            let context = config.get_context().expect("config has a context");
            if !context.is_empty() {
                for i in 0..context.length() {
                    if context.get_return_state(i) == ATNStateRef::empty_return() {
                        let popped = config
                            .clone()
                            .with_prediction_context(Some(PredictionContextRef::new_empty()));
                        self.closure(popped, taint, depth, out);
                    } else {
                        let return_state = context.get_return_state(i);
                        let parent = context
                            .get_parent(i)
                            .unwrap_or_else(PredictionContextRef::new_empty);
                        let popped = config
                            .clone()
                            .with_state(return_state)
                            .with_prediction_context(Some(parent));
                        self.closure(popped, taint, depth - 1, out);
                    }
                }
                return;
            }
            // The config just left the decision: from here on its path crossed
            // the boundary, and it is no longer "inside". The FOLLOW chase
            // below inherits the taint, exactly like the runtime closure, where
            // the marker lives on the config that keeps being passed down.
            taint = (taint & !INTERIOR_TAINT) | BOUNDARY_TAINT;
            out.insert(config.clone(), taint, self.roots.get(self.current_roots));
        } else if !state.has_epsilon_only_transitions() {
            out.insert(config.clone(), taint, self.roots.get(self.current_roots));
        }

        let boundary_chase = state.state_type() == ATNStateType::RuleStop;
        for transition in state.get_transitions() {
            match transition.transition_type() {
                TransitionType::Rule => {
                    let rule_transition = transition.try_as::<RuleTransition>().unwrap();
                    self.enter_rule(&config, rule_transition, taint, depth, out);
                }
                TransitionType::PrecedencePredicate => {
                    let predicate = transition
                        .try_as::<PrecedencePredicateTransition>()
                        .unwrap();
                    self.cross_precedence_predicate(&config, predicate, taint, depth, out);
                }
                TransitionType::Predicate => {
                    let predicate = transition.try_as::<PredicateTransition>().unwrap();
                    if self.facts.first_predicate.is_none() {
                        self.facts.first_predicate =
                            Some((predicate.rule_index(), predicate.pred_index()));
                    }
                    let next = config.clone().with_state(predicate.get_target());
                    self.closure(next, taint | PRED_TAINT, depth, out);
                }
                _ if transition.is_epsilon() => {
                    if boundary_chase
                        && transition.get_target().get_rule_index() == state.get_rule_index()
                        && self.precedence_suppresses(transition.get_target(), depth)
                    {
                        continue;
                    }
                    let mut next = config.clone().with_state(transition.get_target());
                    let mut next_depth = depth;
                    let mut next_taint = taint;
                    if boundary_chase {
                        next_depth = (depth - 1).min(-1);
                        // A return into the middle of an alternative of an
                        // enclosing invocation that still owes input (after an
                        // operand, as in `e '?' e '-' ID`): that alternative owns
                        // the next tokens until the config reaches the decision
                        // again.
                        let target = transition.get_target();
                        let midway = match (&self.loop_block, &self.postfix) {
                            (Some(block), _) => block.is_midway(target),
                            (None, Some(postfix)) => postfix.is_midway(target),
                            (None, None) => false,
                        };
                        if midway {
                            next_taint |= MIDWAY_TAINT;
                        }
                        if self.precedence_start
                            && self
                                .precedence
                                .is_some_and(|class| state.get_rule_index() == class.rule_index)
                            && self.precedence_starts_self_call(transition.get_target())
                        {
                            next.set_precedence_filter_suppressed(true);
                        }
                    }
                    self.closure(next, next_taint, next_depth, out);
                }
                _ => {}
            }
        }
    }

    fn enter_rule(
        &mut self,
        config: &ATNConfig<'a>,
        transition: &RuleTransition,
        taint: i32,
        depth: i32,
        out: &mut SetBuilder<'a>,
    ) {
        let follow_state = transition.follow_state;
        let follow_state_number = follow_state.get_state_number();
        let context = config.get_context().expect("config has a context");
        let (new_context, widened) = if self.depth_bound == 0 {
            (PredictionContextRef::new_empty(), true)
        } else if self.context_depth(context) >= self.depth_bound
            || has_return_state(context, follow_state_number)
        {
            let joint =
                PredictionContextRef::from(self.scratch.alloc(PredictionContext::new_singleton(
                    Some(PredictionContextRef::new_empty()),
                    follow_state,
                )));
            (joint, true)
        } else {
            let pushed = PredictionContextRef::from(self.scratch.alloc(
                PredictionContext::new_singleton(Some(context), follow_state),
            ));
            (pushed, false)
        };

        let callee = config
            .clone()
            .with_state(transition.get_target())
            .with_prediction_context(Some(new_context));
        let mut callee_taint = taint;
        if widened {
            callee_taint |= WIDENED_TAINT;
        }
        let foreign_call = taint & BOUNDARY_TAINT != 0
            && (taint & MIDWAY_TAINT != 0
                || match (&self.loop_block, &self.postfix) {
                    (Some(block), _) => {
                        block.is_foreign_call(config.get_state(), config.get_context())
                    }
                    (None, Some(postfix)) => {
                        postfix.is_foreign_call(config.get_state(), config.get_context())
                    }
                    (None, None) => false,
                });
        if foreign_call {
            callee_taint |= FOREIGN_LINEAGE_TAINT;
        }
        let next_depth = if depth >= 0 { depth + 1 } else { depth };
        self.closure(callee, callee_taint, next_depth, out);
    }

    fn cross_precedence_predicate(
        &mut self,
        config: &ATNConfig<'a>,
        predicate: &PrecedencePredicateTransition,
        taint: i32,
        depth: i32,
        out: &mut SetBuilder<'a>,
    ) {
        let value = predicate.precedence();
        if let Some(class) = self.precedence
            && self.precedence_start
            && depth == 0
        {
            if value >= class.eval_value {
                let next = config.clone().with_state(predicate.get_target());
                self.closure(next, taint, depth, out);
            }
            return;
        }
        let context = config.get_context().expect("config has a context");
        let rule_index = config.get_state().get_rule_index();
        if let Some(passes) = self.evaluate_precedence_from_context(context, rule_index, value) {
            if passes {
                let next = config.clone().with_state(predicate.get_target());
                self.closure(next, taint, depth, out);
            }
            return;
        }
        let next = config.clone().with_state(predicate.get_target());
        self.closure(next, taint | PRECPRED_TAINT, depth, out);
    }

    fn precedence_suppresses(&self, target: ATNStateRef, depth: i32) -> bool {
        let Some(class) = self.precedence else {
            return false;
        };
        if depth < 0 {
            return false;
        }
        self.call_info(target.get_state_number())
            .is_some_and(|call| {
                call.target_rule_index == class.rule_index
                    && (call.precedence < class.lo || call.precedence > class.hi)
            })
    }

    fn precedence_starts_self_call(&self, target: ATNStateRef) -> bool {
        let Some(class) = self.precedence else {
            return false;
        };
        self.call_info(target.get_state_number())
            .is_some_and(|call| call.precedence == 0 && call.target_rule_index == class.rule_index)
    }

    fn call_info(&self, follow_state_number: i32) -> Option<CallInfo> {
        self.call_sites
            .call_by_follow_state
            .get(&follow_state_number)
            .copied()
    }

    /// Evaluates a precedence predicate from the call sites recorded on the
    /// context path: `None` when the path does not pin it down.
    fn evaluate_precedence_from_context(
        &self,
        context: PredictionContextRef<'_>,
        rule: i32,
        value: i32,
    ) -> Option<bool> {
        if context.is_empty() {
            return None;
        }
        let mut agreed = None;
        for i in 0..context.length() {
            let return_state = context.get_return_state(i);
            if return_state == ATNStateRef::empty_return() {
                return None;
            }
            let call = self.call_info(return_state.get_state_number())?;
            if call.target_rule_index != rule {
                return None;
            }
            let outcome = value >= call.precedence;
            match agreed {
                None => agreed = Some(outcome),
                Some(previous) if previous != outcome => return None,
                Some(_) => {}
            }
        }
        agreed
    }

    fn context_depth(&mut self, context: PredictionContextRef<'a>) -> i32 {
        if context.is_empty() {
            return 0;
        }
        let pointer = context.as_ref() as *const PredictionContext<'_> as usize;
        if let Some(&cached) = self.depth_cache.get(&pointer) {
            return cached;
        }
        let mut max_depth = 0;
        for i in 0..context.length() {
            if context.get_return_state(i) == ATNStateRef::empty_return() {
                continue;
            }
            let depth = match context.get_parent(i) {
                Some(parent) => 1 + self.context_depth(parent),
                None => 1,
            };
            max_depth = max_depth.max(depth);
        }
        self.depth_cache.insert(pointer, max_depth);
        max_depth
    }

    /// The precedence filter of a precedence-loop start state: an alternative
    /// that would consume the loop while a higher-precedence alternative
    /// already reached the same state with the same context is dropped.
    ///
    /// The filter keeps a config when one of the two configs has a widened
    /// context. Equal widened contexts can stand for different real stacks,
    /// so the dropped config can be the only viable one.
    fn apply_precedence_filter(&mut self, closed: ClosedSet<'a>) -> ClosedSet<'a> {
        // Merge the contexts first (as the reference Java tool does): the
        // filter compares alternative 1's context against every other
        // alternative's, so it has to see the same merged contexts the runtime
        // start state would hold.
        let closed = self.canonical_set(closed);
        let mut states_from_alt1: HashMap<i32, PredictionContextRef<'a>> = HashMap::new();
        for config in &closed.configs {
            if config.get_alt() == 1 {
                states_from_alt1.insert(
                    config.get_state().get_state_number(),
                    config.get_context().expect("config has a context"),
                );
            }
        }

        let mut out = SetBuilder::new();
        for config in closed.configs {
            let state_number = config.get_state().get_state_number();
            let widened = (taint_of(&closed.taint, &config)
                | closed.taint.get(&(state_number, 1)).copied().unwrap_or(0))
                & WIDENED_TAINT
                != 0;
            if config.get_alt() != 1
                && !config.is_precedence_filter_suppressed()
                && !widened
                && states_from_alt1.get(&state_number) == config.get_context().as_ref()
            {
                continue;
            }
            let mut kept = config;
            kept.set_precedence_filter_suppressed(false);
            let key = (kept.get_state().get_state_number(), kept.get_alt());
            let taint = closed.taint.get(&key).copied().unwrap_or(0);
            let roots = closed.roots.get(&key).cloned().unwrap_or_default();
            out.insert(kept, taint, &roots);
        }
        out.into_closed_set()
    }
}

/// `true` when `return_state_number` appears on the context path.
fn has_return_state(mut context: PredictionContextRef<'_>, return_state_number: i32) -> bool {
    while !context.is_empty() {
        if context.length() != 1 {
            let mut visited = HashSet::new();
            return has_return_state_in_dag(context, return_state_number, &mut visited);
        }
        let return_state = context.get_return_state(0);
        if return_state.get_state_number() == return_state_number {
            return true;
        }
        if return_state == ATNStateRef::empty_return() {
            return false;
        }
        match context.get_parent(0) {
            Some(parent) => context = parent,
            None => return false,
        }
    }
    false
}

fn has_return_state_in_dag(
    context: PredictionContextRef<'_>,
    return_state_number: i32,
    visited: &mut HashSet<usize>,
) -> bool {
    if context.is_empty() {
        return false;
    }
    let pointer = context.as_ref() as *const PredictionContext<'_> as usize;
    if !visited.insert(pointer) {
        return false;
    }
    for i in 0..context.length() {
        let return_state = context.get_return_state(i);
        if return_state.get_state_number() == return_state_number {
            return true;
        }
        if return_state != ATNStateRef::empty_return()
            && context
                .get_parent(i)
                .is_some_and(|parent| has_return_state_in_dag(parent, return_state_number, visited))
        {
            return true;
        }
    }
    false
}