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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! `--static-dfa-only` resolution of the escape states of decision tables.
//!
//! A partial table escapes to the adaptive simulation where the static
//! construction stopped. Without that fallback, each escape state gets a
//! static verdict:
//!
//! - A guarded state keeps its runtime stack guard. When the guard defers, the
//!   state returns the skip of its optional postfix or the exit of its
//!   precedence loop instead of the adaptive simulation. The guard walks only
//!   the parse stack, so this needs no ATN simulation. This is also a guess:
//!   the guard sees the guard roots on the stack, but not the input after the
//!   lookahead of the table. The guard groups rank by their stack-hijack
//!   hazard (see `hazard`).
//! - A state with an SLL conflict (a conflict escape) accepts its minimum
//!   conflicting alternative. This is the choice of the SLL prediction mode.
//! - A state where the lookahead budget stopped the construction accepts its
//!   minimum viable alternative. This is a guess: if the input continues in
//!   a different alternative, the parse reports a syntax error later.
//!   Grammars usually put the specific alternatives before the general ones,
//!   so the guess is usually right.
//! - A predicated state becomes a dead end without edges or fallback, so the
//!   walk reports a syntax error. The table cannot evaluate the predicate.

use super::hazard::{HazardLevel, HijackVerdict, StackHijackVerdict, StateHazard};
use super::{CONFLICT_ESCAPE, DecisionKind, DecisionOutcome, ESCAPE, GUARDED, StaticDfaTable};

/// How `--static-dfa-only` replaced one escape state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum EscapeResolution {
    /// The state keeps its stack guard, and returns its defer alternative
    /// when the guard defers.
    Guarded,
    /// The state accepts its minimum conflicting alternative.
    MinAlt,
    /// The lookahead budget stopped the construction at the state. The state
    /// accepts its minimum viable alternative.
    MinViableAlt,
    /// A predicate made the state undecidable. The state reports a syntax
    /// error.
    SyntaxError,
}

/// The escape states that `--static-dfa-only` resolved in the tables of one
/// decision.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct EscapeResolutions {
    /// The number of guarded states that return their defer alternative when
    /// the guard defers.
    pub(crate) guarded: usize,
    /// The number of states that accept their minimum conflicting alternative.
    pub(crate) min_alt: usize,
    /// The number of states that accept their minimum viable alternative.
    pub(crate) min_viable_alt: usize,
    /// The number of states that report a syntax error.
    pub(crate) syntax_error: usize,
    /// A shortest lookahead path to a [`EscapeResolution::Guarded`] state.
    pub(crate) guarded_witness: Option<Vec<i32>>,
    /// The danger set of the guard group of the state at the end of
    /// [`Self::guarded_witness`]: the sorted invoking states where its guard
    /// defers.
    pub(crate) guarded_danger: Vec<i32>,
    /// A shortest lookahead path to a [`EscapeResolution::MinAlt`] state.
    pub(crate) min_alt_witness: Option<Vec<i32>>,
    /// A shortest lookahead path to a [`EscapeResolution::MinViableAlt`]
    /// state.
    pub(crate) min_viable_alt_witness: Option<Vec<i32>>,
    /// A shortest lookahead path to a [`EscapeResolution::SyntaxError`] state.
    pub(crate) syntax_error_witness: Option<Vec<i32>>,
    /// The states that resolved to one alternative over others, grouped by
    /// the chosen alternative and the dropped alternatives. The most harmful
    /// groups come first, then the groups with the most states.
    pub(crate) tie_breaks: Vec<TieBreak>,
    /// The guarded states, grouped by the danger set of their guard. The
    /// most harmful groups come first, then the groups with the most states.
    pub(crate) guard_groups: Vec<GuardGroup>,
}

/// The guarded states of one decision whose guards have one danger set.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct GuardGroup {
    /// The sorted invoking states where the guards defer.
    pub(crate) danger: Vec<i32>,
    /// The number of states.
    pub(crate) states: usize,
    /// A shortest lookahead path to one of the states.
    pub(crate) witness: Option<Vec<i32>>,
    /// The most harmful stack-hijack hazard of the states of the group, when
    /// the analysis ran for one of them.
    pub(crate) hazard: Option<StackHijackVerdict>,
}

impl GuardGroup {
    /// The level that orders the groups: a group without an analysis counts
    /// as [`HazardLevel::Medium`].
    pub(crate) fn level(&self) -> HazardLevel {
        self.hazard
            .as_ref()
            .map_or(HazardLevel::Medium, StackHijackVerdict::level)
    }

    /// Adds `other` to the group: the states, the shorter witness, and the
    /// worse hazard.
    fn absorb(&mut self, other: Self) {
        self.states += other.states;
        self.hazard = worse_stack(self.hazard.take(), other.hazard);
        let shorter = match (&self.witness, &other.witness) {
            (None, Some(_)) => true,
            (Some(known), Some(new)) => new.len() < known.len(),
            _ => false,
        };
        if shorter {
            self.witness = other.witness;
        }
    }
}

/// Whether the stack-hijack verdict `left` is more harmful than `right`: a
/// higher level, then a shorter hijack path, then a lower danger caller.
fn stack_outranks(left: &StackHijackVerdict, right: &StackHijackVerdict) -> bool {
    let rank = |verdict: &StackHijackVerdict| match verdict {
        StackHijackVerdict::Hijack { caller, extension } => (
            verdict.level(),
            std::cmp::Reverse(extension.len()),
            std::cmp::Reverse(*caller),
        ),
        _ => (verdict.level(), std::cmp::Reverse(0), std::cmp::Reverse(0)),
    };
    rank(left) > rank(right)
}

/// The same verdict, unknown instead of covered: a state of the group was
/// not analyzed.
fn partial_stack(verdict: StackHijackVerdict) -> StackHijackVerdict {
    match verdict {
        StackHijackVerdict::Covered => StackHijackVerdict::Unknown,
        verdict => verdict,
    }
}

/// The more harmful of two stack-hijack verdicts. A side without an analysis
/// makes a covered verdict unknown.
fn worse_stack(
    left: Option<StackHijackVerdict>,
    right: Option<StackHijackVerdict>,
) -> Option<StackHijackVerdict> {
    match (left, right) {
        (Some(left), Some(right)) => Some(if stack_outranks(&right, &left) {
            right
        } else {
            left
        }),
        (Some(known), None) | (None, Some(known)) => Some(partial_stack(known)),
        (None, None) => None,
    }
}

/// Adds `group` to `groups`, merged into the group with the same danger set.
fn add_guard_group(groups: &mut Vec<GuardGroup>, group: GuardGroup) {
    match groups.iter_mut().find(|known| known.danger == group.danger) {
        Some(known) => known.absorb(group),
        None => groups.push(group),
    }
}

/// Orders guard groups: the most harmful first, then the most states, then
/// by danger set.
fn sort_guard_groups(groups: &mut [GuardGroup]) {
    groups.sort_by(|left, right| {
        right
            .level()
            .cmp(&left.level())
            .then_with(|| right.states.cmp(&left.states))
            .then_with(|| left.danger.cmp(&right.danger))
    });
}

/// The states of one decision where `--static-dfa-only` chose one
/// alternative over other viable or conflicting alternatives.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct TieBreak {
    /// The alternative that the states predict.
    pub(crate) chosen: i32,
    /// The sorted alternatives that the states drop.
    pub(crate) dropped: Vec<i32>,
    /// The number of states.
    pub(crate) states: usize,
    /// A shortest lookahead path to one of the states.
    pub(crate) witness: Option<Vec<i32>>,
    /// The most harmful prefix-hijack hazard of the states of the group, when
    /// the analysis ran for one of them.
    pub(crate) hazard: Option<GroupHazard>,
}

/// The prefix-hijack hazard of a tie-break group.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct GroupHazard {
    pub(crate) level: HazardLevel,
    /// For a hijack, the extension is the whole lookahead path from the start
    /// of the decision.
    pub(crate) verdict: HijackVerdict,
    pub(crate) greedy: bool,
}

impl GroupHazard {
    /// The hazard of `state`, with the hijack path from the start state of
    /// `table`. A hijack at a state that the start state does not reach has
    /// no path, so it counts as unknown.
    fn of(table: &StaticDfaTable, state: usize, hazard: &StateHazard) -> Self {
        let unknown = StateHazard {
            verdict: HijackVerdict::Unknown,
            greedy: hazard.greedy,
        };
        let (verdict, hazard) = match (&hazard.verdict, table.witness(state)) {
            (HijackVerdict::Hijack { alt, extension }, Some(path)) => (
                HijackVerdict::Hijack {
                    alt: *alt,
                    extension: path.into_iter().chain(extension.iter().copied()).collect(),
                },
                hazard,
            ),
            (HijackVerdict::Hijack { .. }, None) => (HijackVerdict::Unknown, &unknown),
            (verdict, _) => (verdict.clone(), hazard),
        };
        Self {
            level: hazard.level(),
            verdict,
            greedy: hazard.greedy,
        }
    }

    /// The same hazard, unknown instead of covered: a state of the group was
    /// not analyzed.
    fn partial(mut self) -> Self {
        if self.verdict == HijackVerdict::Covered {
            self.verdict = HijackVerdict::Unknown;
            self.level = StateHazard {
                verdict: HijackVerdict::Unknown,
                greedy: self.greedy,
            }
            .level();
        }
        self
    }

    /// Whether `self` is more harmful than `other`: a higher level, then a
    /// worse verdict, then a shorter hijack path.
    fn outranks(&self, other: &Self) -> bool {
        let rank = |hazard: &Self| match &hazard.verdict {
            HijackVerdict::Hijack { extension, .. } => (2, std::cmp::Reverse(extension.len())),
            HijackVerdict::Unknown => (1, std::cmp::Reverse(0)),
            HijackVerdict::Covered => (0, std::cmp::Reverse(0)),
        };
        (self.level, rank(self)) > (other.level, rank(other))
    }
}

/// The more harmful of two group hazards. A side without an analysis makes a
/// covered verdict unknown.
fn worse(left: Option<GroupHazard>, right: Option<GroupHazard>) -> Option<GroupHazard> {
    match (left, right) {
        (Some(left), Some(right)) => Some(if right.outranks(&left) { right } else { left }),
        (Some(known), None) | (None, Some(known)) => Some(known.partial()),
        (None, None) => None,
    }
}

impl TieBreak {
    fn key(&self) -> (i32, &[i32]) {
        (self.chosen, &self.dropped)
    }

    /// The level that orders the groups: a group without an analysis counts
    /// as [`HazardLevel::Medium`].
    pub(crate) fn level(&self) -> HazardLevel {
        self.hazard
            .as_ref()
            .map_or(HazardLevel::Medium, |hazard| hazard.level)
    }

    /// Adds `other` to the group: the states, the shorter witness, and the
    /// worse hazard.
    fn absorb(&mut self, other: Self) {
        self.states += other.states;
        self.hazard = worse(self.hazard.take(), other.hazard.clone());
        let shorter = match (&self.witness, &other.witness) {
            (None, Some(_)) => true,
            (Some(known), Some(new)) => new.len() < known.len(),
            _ => false,
        };
        if shorter {
            self.witness = other.witness;
        }
    }
}

/// A tie-break group while `resolve_escapes` builds it: the group, its
/// shallowest state, and the hazards of its analyzed states.
type GroupBuild = (TieBreak, usize, Vec<(usize, StateHazard)>);

/// Adds `group` to `groups`, merged into the group with the same key.
fn add_tie_break(groups: &mut Vec<TieBreak>, group: TieBreak) {
    match groups.iter_mut().find(|known| known.key() == group.key()) {
        Some(known) => known.absorb(group),
        None => groups.push(group),
    }
}

/// Orders tie-break groups: the most harmful first, then the most states,
/// then by alternatives.
fn sort_tie_breaks(groups: &mut [TieBreak]) {
    groups.sort_by(|left, right| {
        right
            .level()
            .cmp(&left.level())
            .then_with(|| right.states.cmp(&left.states))
            .then_with(|| left.chosen.cmp(&right.chosen))
            .then_with(|| left.dropped.cmp(&right.dropped))
    });
}

impl EscapeResolutions {
    fn merge(&mut self, other: Self) {
        self.guarded += other.guarded;
        self.min_alt += other.min_alt;
        self.min_viable_alt += other.min_viable_alt;
        self.syntax_error += other.syntax_error;
        if self.guarded_witness.is_none() {
            self.guarded_witness = other.guarded_witness;
            self.guarded_danger = other.guarded_danger;
        }
        if self.min_alt_witness.is_none() {
            self.min_alt_witness = other.min_alt_witness;
        }
        if self.min_viable_alt_witness.is_none() {
            self.min_viable_alt_witness = other.min_viable_alt_witness;
        }
        if self.syntax_error_witness.is_none() {
            self.syntax_error_witness = other.syntax_error_witness;
        }
        for group in other.tie_breaks {
            add_tie_break(&mut self.tie_breaks, group);
        }
        sort_tie_breaks(&mut self.tie_breaks);
        for group in other.guard_groups {
            add_guard_group(&mut self.guard_groups, group);
        }
        sort_guard_groups(&mut self.guard_groups);
        self.show_stack_hijack();
    }

    /// Shows the guard group of a stack hijack in the guarded witness and
    /// danger set, when the most harmful guard group is a hijack.
    fn show_stack_hijack(&mut self) {
        if let Some(group) = self.guard_groups.first()
            && matches!(group.hazard, Some(StackHijackVerdict::Hijack { .. }))
            && group.witness.is_some()
        {
            self.guarded_witness.clone_from(&group.witness);
            self.guarded_danger.clone_from(&group.danger);
        }
    }

    /// The guard groups with a high stack-hijack hazard.
    pub(crate) fn stack_hijacks(&self) -> impl Iterator<Item = &GuardGroup> {
        self.guard_groups
            .iter()
            .filter(|group| group.level() == HazardLevel::High)
    }
}

impl StaticDfaTable {
    /// Gives every escape state a static verdict and every guarded state a
    /// defer alternative, so that the table never defers to the adaptive
    /// simulation.
    pub(crate) fn resolve_escapes(&mut self) -> EscapeResolutions {
        let mut resolutions = EscapeResolutions::default();
        let mut first_guarded = None;
        let mut first_min_alt = None;
        let mut first_min_viable_alt = None;
        let mut first_syntax_error = None;
        let depths = self.depths();
        // The tie-break groups, each with the shallowest state that is in it
        // and the hazards of its analyzed states.
        let mut groups: Vec<GroupBuild> = Vec::new();
        // The guard groups by group index, each with its shallowest state, the
        // number of its states, and the verdicts of its analyzed states.
        let mut guards: Vec<(u32, usize, usize, Vec<StackHijackVerdict>)> = Vec::new();
        for (index, state) in self.states.iter_mut().enumerate() {
            if !matches!(state.accept, ESCAPE | CONFLICT_ESCAPE | GUARDED) {
                continue;
            }
            if state.accept == GUARDED && state.guarded_alt > 0 && state.guard_defer_alt > 0 {
                state.resolution = Some(EscapeResolution::Guarded);
                resolutions.guarded += 1;
                first_guarded.get_or_insert(index);
                let verdict = state.stack_hazard.take();
                match guards
                    .iter_mut()
                    .find(|(group, ..)| *group == state.guard_group)
                {
                    Some((_, shallowest, states, verdicts)) => {
                        *states += 1;
                        if depths[index] < depths[*shallowest] {
                            *shallowest = index;
                        }
                        verdicts.extend(verdict);
                    }
                    None => {
                        guards.push((state.guard_group, index, 1, verdict.into_iter().collect()))
                    }
                }
                continue;
            }
            let conflict_alt = if state.accept == GUARDED && state.guarded_alt > 0 {
                // The guarded alternative is the take or iterate branch,
                // which is the minimum alternative of the pair.
                Some(state.guarded_alt)
            } else {
                state.conflicts.iter().copied().filter(|alt| *alt > 0).min()
            };
            let viable_alt = if state.predicated {
                None
            } else {
                state.viable_alts.first().copied()
            };
            let mut dropped: Vec<i32> = if conflict_alt.is_some() {
                state.conflicts.clone()
            } else {
                state.viable_alts.clone()
            };
            let resolution = if let Some(alt) = conflict_alt {
                state.accept = alt;
                resolutions.min_alt += 1;
                first_min_alt.get_or_insert(index);
                EscapeResolution::MinAlt
            } else if let Some(alt) = viable_alt {
                state.accept = alt;
                resolutions.min_viable_alt += 1;
                first_min_viable_alt.get_or_insert(index);
                EscapeResolution::MinViableAlt
            } else {
                state.accept = 0;
                state.fallback = 0;
                state.edges.clear();
                resolutions.syntax_error += 1;
                first_syntax_error.get_or_insert(index);
                EscapeResolution::SyntaxError
            };
            state.resolution = Some(resolution);
            dropped.retain(|alt| *alt > 0 && *alt != state.accept);
            dropped.sort_unstable();
            dropped.dedup();
            if resolution != EscapeResolution::SyntaxError && !dropped.is_empty() {
                let hazard = state.hazard.as_ref().map(|hazard| (index, hazard.clone()));
                let group = TieBreak {
                    chosen: state.accept,
                    dropped,
                    states: 1,
                    witness: None,
                    hazard: None,
                };
                match groups
                    .iter_mut()
                    .find(|(known, ..)| known.key() == group.key())
                {
                    Some((known, shallowest, hazards)) => {
                        known.states += 1;
                        if depths[index] < depths[*shallowest] {
                            *shallowest = index;
                        }
                        hazards.extend(hazard);
                    }
                    None => groups.push((group, index, hazard.into_iter().collect())),
                }
            }
            state.conflict_min_alt = 0;
            state.guarded_alt = 0;
            state.guard_defer_alt = 0;
            state.guard_group = 0;
            state.continuation = None;
            state.hazard = None;
            state.stack_hazard = None;
        }
        if resolutions.guarded == 0 {
            self.guard_groups.clear();
            self.guard_pass.clear();
        }
        resolutions.guarded_witness = first_guarded.and_then(|state| self.witness(state));
        if resolutions.guarded_witness.is_some() {
            resolutions.guarded_danger = first_guarded
                .and_then(|state| {
                    self.guard_groups
                        .get(self.states[state].guard_group as usize)
                })
                .cloned()
                .unwrap_or_default();
        }
        resolutions.min_alt_witness = first_min_alt.and_then(|state| self.witness(state));
        resolutions.min_viable_alt_witness =
            first_min_viable_alt.and_then(|state| self.witness(state));
        resolutions.syntax_error_witness = first_syntax_error.and_then(|state| self.witness(state));
        resolutions.tie_breaks = groups
            .into_iter()
            .map(|(mut group, shallowest, hazards)| {
                group.witness = self.witness(shallowest);
                let analyzed = hazards.len();
                group.hazard = hazards
                    .iter()
                    .map(|(state, hazard)| GroupHazard::of(self, *state, hazard))
                    .reduce(|known, hazard| {
                        if hazard.outranks(&known) {
                            hazard
                        } else {
                            known
                        }
                    })
                    .map(|hazard| {
                        if analyzed < group.states {
                            hazard.partial()
                        } else {
                            hazard
                        }
                    });
                group
            })
            .collect();
        sort_tie_breaks(&mut resolutions.tie_breaks);
        for (group, shallowest, states, verdicts) in guards {
            let analyzed = verdicts.len();
            let hazard = verdicts
                .into_iter()
                .reduce(|known, verdict| {
                    if stack_outranks(&verdict, &known) {
                        verdict
                    } else {
                        known
                    }
                })
                .map(|verdict| {
                    if analyzed < states {
                        partial_stack(verdict)
                    } else {
                        verdict
                    }
                });
            add_guard_group(
                &mut resolutions.guard_groups,
                GuardGroup {
                    danger: self
                        .guard_groups
                        .get(group as usize)
                        .cloned()
                        .unwrap_or_default(),
                    states,
                    witness: self.witness(shallowest),
                    hazard,
                },
            );
        }
        sort_guard_groups(&mut resolutions.guard_groups);
        resolutions.show_stack_hijack();
        resolutions
    }
}

impl DecisionOutcome {
    /// Resolves the escape states of every table of the decision for
    /// `--static-dfa-only` and records the result in
    /// [`DecisionOutcome::static_only`].
    ///
    /// Returns `false` and changes nothing when the generated parser still
    /// needs `adaptive_predict` for the decision. This is the case when the
    /// decision has no table, when a precedence class has no table, and for a
    /// non-greedy decision.
    pub(crate) fn resolve_static_only(&mut self) -> bool {
        let mut resolutions = EscapeResolutions::default();
        match self.kind {
            DecisionKind::Ll1 => {}
            DecisionKind::Adaptive => return false,
            DecisionKind::Static | DecisionKind::Hybrid => {
                if let Some(precedence) = &mut self.precedence {
                    if precedence.adaptive_classes > 0 {
                        return false;
                    }
                    for table in precedence.tables.iter_mut().flatten() {
                        resolutions.merge(table.resolve_escapes());
                    }
                    precedence.escapes = 0;
                } else if let Some(table) = &mut self.table {
                    resolutions.merge(table.resolve_escapes());
                } else {
                    return false;
                }
            }
        }
        self.escapes = 0;
        self.static_only = Some(resolutions);
        true
    }
}

#[cfg(test)]
mod tests {
    use super::{EscapeResolutions, GuardGroup, StackHijackVerdict, TieBreak};

    fn group(chosen: i32, dropped: &[i32], states: usize, witness: &[i32]) -> TieBreak {
        TieBreak {
            chosen,
            dropped: dropped.to_vec(),
            states,
            witness: Some(witness.to_vec()),
            hazard: None,
        }
    }

    /// The tie-break groups of several tables, such as the precedence
    /// classes of one decision, merge by alternatives. A merged group keeps
    /// the shorter witness, and the largest group comes first.
    #[test]
    fn tie_break_groups_merge_over_tables() {
        let mut resolutions = EscapeResolutions {
            tie_breaks: vec![group(1, &[2], 2, &[5, 6, 7]), group(3, &[4], 1, &[8])],
            ..EscapeResolutions::default()
        };
        resolutions.merge(EscapeResolutions {
            tie_breaks: vec![group(1, &[2], 3, &[5]), group(1, &[3], 4, &[9])],
            ..EscapeResolutions::default()
        });
        assert_eq!(
            resolutions.tie_breaks,
            [
                group(1, &[2], 5, &[5]),
                group(1, &[3], 4, &[9]),
                group(3, &[4], 1, &[8]),
            ]
        );
    }

    fn guard(
        danger: &[i32],
        states: usize,
        witness: &[i32],
        hazard: Option<StackHijackVerdict>,
    ) -> GuardGroup {
        GuardGroup {
            danger: danger.to_vec(),
            states,
            witness: Some(witness.to_vec()),
            hazard,
        }
    }

    /// The guard groups of several tables merge by danger set. A merged group
    /// keeps its worst verdict, and a covered group with an unanalyzed side
    /// is unknown. A stack hijack comes first, and the guarded witness and
    /// danger set show it.
    #[test]
    fn guard_groups_merge_over_tables() {
        let hijack = StackHijackVerdict::Hijack {
            caller: 9,
            extension: vec![5, 2],
        };
        let mut resolutions = EscapeResolutions {
            guarded_witness: Some(vec![3]),
            guarded_danger: vec![4],
            guard_groups: vec![
                guard(&[4], 3, &[3], Some(StackHijackVerdict::Covered)),
                guard(&[9], 1, &[5, 6], Some(StackHijackVerdict::Covered)),
            ],
            ..EscapeResolutions::default()
        };
        resolutions.merge(EscapeResolutions {
            guard_groups: vec![
                guard(&[4], 2, &[7], None),
                guard(&[9], 1, &[5], Some(hijack.clone())),
            ],
            ..EscapeResolutions::default()
        });
        assert_eq!(
            resolutions.guard_groups,
            [
                guard(&[9], 2, &[5], Some(hijack)),
                guard(&[4], 5, &[3], Some(StackHijackVerdict::Unknown)),
            ]
        );
        assert_eq!(resolutions.guarded_witness, Some(vec![5]));
        assert_eq!(resolutions.guarded_danger, [9]);
        assert_eq!(resolutions.stack_hijacks().count(), 1);
    }
}