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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! The operator-loop block of a left-recursive rule, and the token
//! obligations of its positions.
//!
//! A precedence-class table predicts the iterate/exit conflict of a
//! left-recursive rule's loop. The builder resolves that conflict to
//! *iterate* without exactness. The argument: every exit derivation of a
//! sentence maps onto an iterate derivation of the same sentence. In the exit
//! reading, an enclosing invocation of this same loop consumes the next
//! operator. If the inner loop iterates instead, it consumes that operator and
//! then leaves through the free loop exit into the same caller continuation.
//!
//! That argument only holds while the exit lineage's tokens are the loop's own
//! tokens. Four facts decide it:
//!
//! - **Operator loop** ([`LoopBlock::is_loop_consumption`]): the loop
//!   decision, the operator alternatives, and the follow states of their
//!   operands. A boundary-popped configuration is in the frame that it popped
//!   into, or in an invocation that it started from that frame. In the popped
//!   frame, consumption at an operator-loop position belongs to an enclosing
//!   invocation of the loop. In an invocation that an operator-loop position
//!   started (an operand descent), consumption also belongs to the loop. All
//!   other consumption is *foreign*, and the substitution does not apply.
//!   - A new invocation of the rule after the exit is foreign: in
//!     `s : e e ';'` the second `e` can read the `'-'` that the first `e` reads
//!     as an operator.
//!   - A base alternative of an enclosing invocation is foreign too: in
//!     `e : ... | 'pair' e e` the second `e` of `pair` can read that `'-'`.
//!
//!   [`LoopBlock::is_foreign_call`] marks the call that starts such an
//!   invocation with [`FOREIGN_LINEAGE_TAINT`], because widening and merged
//!   contexts can remove its frame later.
//! - **Pending obligations**: positions that cannot reach the loop decision by
//!   epsilon alone. Such a position owes a token of the current alternative. A
//!   frame in the exit lineage that owes a token of an operator alternative
//!   that the iterate reading does not also owe vetoes the substitution. A
//!   frame that the iterate reading shares (such as the `']'` after the index
//!   of `e '[' e ']'`) or that belongs to a foreign invocation already rooted
//!   by [`FOREIGN_CONSUME_TAINT`] does not veto it.
//! - **Midway returns**: the boundary chase can return a configuration into
//!   the middle of an alternative of an enclosing invocation, with no frame
//!   left. In `e '?' e '-' ID` the middle operand returns before `'-'`, and in
//!   `e '?' e ('-' ID)?` before an optional suffix. That alternative owns the
//!   next tokens. The chase marks the configuration with [`MIDWAY_TAINT`],
//!   and the mark stays until the configuration reaches the loop decision
//!   again. A return that leads straight back to the loop decision, as after
//!   the right operand of `e '-' e`, gets no mark.
//! - **Simple guarded alternatives** ([`LoopBlock::guards_are_simple`]): at
//!   most one rule invocation, and no internal iteration, between the
//!   precedence predicate and the loop end. The substitution maps "operator
//!   consumed, operand in progress" onto the inner loop's iterate. That map is
//!   valid only while the operand completes the recursive structure of the
//!   alternative. A compound alternative breaks it: `expr (',' expr)* '>>'
//!   expr` would complete an inner construct as a list element and then fail.
use std::collections::HashSet;

use dbt_antlr_runtime::analysis::{
    ATN, ATNConfig, ATNStateRef, ATNStateType, BitSet, FOREIGN_CONSUME_TAINT,
    FOREIGN_LINEAGE_TAINT, MIDWAY_TAINT, PrecedencePredicateTransition, PredictionContextRef,
    RuleTransition, WIDENED_TAINT,
};

use super::closure::{Taint, in_popped_frame, positions_owing_input, rule_positions, taint_of};

/// The alternative of the loop's iterate branch.
pub(super) const ITERATE_ALT: i32 = 1;

/// The alternative of the loop's exit branch.
pub(super) const EXIT_ALT: i32 = 2;

/// The exit lineage consumed a token outside the operator loop.
pub(super) const EXIT_FOREIGN: i32 = 1;
/// The exit lineage holds a frame that owes tokens the iterate reading does
/// not also owe.
pub(super) const EXIT_OBLIGATED: i32 = 2;
/// Iterate viability is attested by a configuration that is neither widened
/// nor foreign.
pub(super) const ITERATE_REAL: i32 = 4;

/// The operator loop of one left-recursive rule, and the token obligations of
/// its positions.
#[derive(Clone, Debug)]
pub(super) struct LoopBlock {
    rule_index: i32,
    /// Positions of the operator loop: the loop decision, the operator
    /// alternatives, and the follow states of their operands.
    operator_states: BitSet,
    /// Rule-local positions that cannot epsilon-reach the loop decision, and
    /// so owe a token of the current alternative.
    pending_states: BitSet,
    /// Rule-local positions from which the current alternative can consume or
    /// call before an epsilon path reaches the loop decision.
    midway_states: BitSet,
    /// Whether every guarded (precedence-bearing) alternative is simple: at
    /// most one rule invocation and no internal iteration.
    simple: bool,
}

impl LoopBlock {
    /// Analyses the loop block of the rule owning `decision_state`.
    pub(super) fn of(atn: &ATN, decision_state: ATNStateRef) -> Self {
        let rule_index = decision_state.get_rule_index();
        let operator_states = operator_states(decision_state);
        let pending_states = pending_states(atn, decision_state, rule_index);
        let midway_states = positions_owing_input(atn, rule_index, decision_state);
        let simple = guards_are_simple(atn, decision_state, rule_index);
        Self {
            rule_index,
            operator_states,
            pending_states,
            midway_states,
            simple,
        }
    }

    /// The iterate/exit substitution attestations of one conflict set (see
    /// [`EXIT_FOREIGN`], [`EXIT_OBLIGATED`] and [`ITERATE_REAL`]).
    ///
    /// The substitution resolves to iterate only when the result is exactly
    /// [`ITERATE_REAL`]: the exit lineage stayed inside the loop and owes
    /// nothing the iterate reading does not owe, and iterate viability is
    /// attested by a configuration that is neither widened nor foreign.
    pub(super) fn iterate_exit_attestation(&self, configs: &[ATNConfig<'_>], taint: &Taint) -> i32 {
        let mut iterate_pending = BitSet::new();
        for config in configs {
            if config.get_alt() == ITERATE_ALT
                && let Some(context) = config.get_context()
            {
                let mut visited = HashSet::new();
                self.collect_pending(&context, &mut visited, &mut iterate_pending);
            }
        }
        let mut attestation = 0;
        for config in configs {
            let taint = taint_of(taint, config);
            if config.get_alt() == EXIT_ALT {
                let foreign = taint & FOREIGN_CONSUME_TAINT != 0;
                if foreign {
                    attestation |= EXIT_FOREIGN;
                }
                if self.has_unshared_obligation(config.get_context(), &iterate_pending, foreign) {
                    attestation |= EXIT_OBLIGATED;
                }
            }
            if config.get_alt() == ITERATE_ALT
                && taint & (WIDENED_TAINT | FOREIGN_CONSUME_TAINT) == 0
            {
                attestation |= ITERATE_REAL;
            }
        }
        attestation
    }

    /// Whether the iterate lineage of a frontier state covers its exit
    /// lineage, so that the substitution to iterate stays sound when the
    /// construction stops before the alternatives separate.
    ///
    /// In a higher precedence class, the iterate lineage drops the operators
    /// of a lower precedence. The exit lineage pops the recursive invocation
    /// and can enter these operators again. A multi-token operator, or a
    /// shared operator rule, can then keep both lineages at the same ATN state
    /// with different stacks. So each call-stack path of an exit config must
    /// also be a path of a real iterate config at the same state. For a
    /// foreign exit config, only the paths that return into the operator loop
    /// count: the stack guard decides the other paths. A widened exit config
    /// does not show its paths, and its guard roots can be in a frame that the
    /// widening removed, so it is never covered.
    pub(super) fn iterate_covers_exit(&self, configs: &[ATNConfig<'_>], taint: &Taint) -> bool {
        let mut budget = PATH_BUDGET;
        configs
            .iter()
            .filter(|config| config.get_alt() == EXIT_ALT)
            .all(|exit| {
                let exit_taint = taint_of(taint, exit);
                if exit_taint & WIDENED_TAINT != 0 {
                    return false;
                }
                let iterate: Vec<_> = configs
                    .iter()
                    .filter(|config| {
                        config.get_alt() == ITERATE_ALT
                            && config.get_state() == exit.get_state()
                            && taint_of(taint, config) & (WIDENED_TAINT | FOREIGN_CONSUME_TAINT)
                                == 0
                    })
                    .map(ATNConfig::get_context)
                    .collect();
                let walk = PathWalk {
                    block: self,
                    state: exit.get_state(),
                    loop_only: exit_taint & FOREIGN_CONSUME_TAINT != 0,
                };
                walk.covered(exit.get_context(), iterate, None, &mut budget)
            })
    }

    /// Whether every guarded alternative of the rule is simple (see the module
    /// documentation).
    pub(super) fn guards_are_simple(&self) -> bool {
        self.simple
    }

    /// Whether a token that a boundary-popped configuration consumes at
    /// `state` belongs to the operator loop (see the module documentation).
    ///
    /// A context with an empty path puts the configuration in the frame that
    /// it popped into, so the position decides. Any other context puts it in
    /// an invocation that it started from that frame. That invocation belongs
    /// to the loop unless `taint` holds [`FOREIGN_LINEAGE_TAINT`]. A
    /// configuration with [`MIDWAY_TAINT`] consumes for an enclosing
    /// alternative.
    pub(super) fn is_loop_consumption(
        &self,
        state: ATNStateRef,
        context: Option<PredictionContextRef<'_>>,
        taint: i32,
    ) -> bool {
        if taint & (FOREIGN_LINEAGE_TAINT | MIDWAY_TAINT) != 0 {
            return false;
        }
        !in_popped_frame(context)
            || self
                .operator_states
                .contains(state.get_state_number() as usize)
    }

    /// Whether a rule call of a boundary-popped configuration at `state`
    /// starts an invocation that is foreign to the loop: the call leaves the
    /// frame that the configuration popped into from a position outside the
    /// operator loop.
    pub(super) fn is_foreign_call(
        &self,
        state: ATNStateRef,
        context: Option<PredictionContextRef<'_>>,
    ) -> bool {
        in_popped_frame(context)
            && !self
                .operator_states
                .contains(state.get_state_number() as usize)
    }

    /// Whether the context holds a same-rule return into a pending position
    /// that the iterate reading does not also owe.
    fn has_unshared_obligation(
        &self,
        context: Option<PredictionContextRef<'_>>,
        iterate_pending: &BitSet,
        foreign: bool,
    ) -> bool {
        let Some(context) = context else {
            return false;
        };
        let mut visited = HashSet::new();
        self.obligation_in(&context, iterate_pending, foreign, &mut visited)
    }

    /// Whether a boundary chase that returns into `state` lands in the middle
    /// of an alternative that can still consume or call before it reaches the
    /// loop decision (see the module documentation).
    pub(super) fn is_midway(&self, state: ATNStateRef) -> bool {
        self.midway_states
            .contains(state.get_state_number() as usize)
    }

    /// Whether a return into `state` is realizable through the loop's own
    /// discipline (the mirror set of the guard-root analysis).
    pub(super) fn is_loop_state(&self, state: ATNStateRef) -> bool {
        self.operator_states
            .contains(state.get_state_number() as usize)
    }

    /// Whether `state` is a rule-local position that owes a token of the
    /// current alternative.
    pub(super) fn is_pending(&self, state: ATNStateRef) -> bool {
        self.pending_states
            .contains(state.get_state_number() as usize)
    }

    fn collect_pending(
        &self,
        context: &PredictionContextRef<'_>,
        visited: &mut HashSet<*const ()>,
        out: &mut BitSet,
    ) {
        if context.is_empty() || !visited.insert(pointer_key(context)) {
            return;
        }
        for index in 0..context.length() {
            let return_state = context.get_return_state(index);
            if return_state == ATNStateRef::empty_return() {
                continue;
            }
            if return_state.get_rule_index() == self.rule_index && self.is_pending(return_state) {
                out.insert(return_state.get_state_number() as usize);
            }
            if let Some(parent) = context.get_parent(index) {
                self.collect_pending(&parent, visited, out);
            }
        }
    }

    fn obligation_in(
        &self,
        context: &PredictionContextRef<'_>,
        iterate_pending: &BitSet,
        foreign: bool,
        visited: &mut HashSet<*const ()>,
    ) -> bool {
        if context.is_empty() || !visited.insert(pointer_key(context)) {
            return false;
        }
        for index in 0..context.length() {
            let return_state = context.get_return_state(index);
            if return_state == ATNStateRef::empty_return() {
                continue;
            }
            if return_state.get_rule_index() == self.rule_index
                && self.is_pending(return_state)
                && (!foreign || self.is_loop_state(return_state))
                && !iterate_pending.contains(return_state.get_state_number() as usize)
            {
                return true;
            }
            let Some(parent) = context.get_parent(index) else {
                continue;
            };
            if self.obligation_in(&parent, iterate_pending, foreign, visited) {
                return true;
            }
        }
        false
    }
}

/// Whether a set of live alternatives is exactly the iterate/exit pair of a
/// loop decision.
pub(super) fn is_iterate_exit_pair(alts: &BitSet) -> bool {
    alts.len() == 2 && alts.contains(ITERATE_ALT as usize) && alts.contains(EXIT_ALT as usize)
}

/// The path steps that [`LoopBlock::iterate_covers_exit`] can take for one
/// frontier state. A context node that many paths share counts once for each
/// path. Past this limit, the exit lineage is not covered.
const PATH_BUDGET: usize = 4096;

/// A walk over the call-stack paths of one exit config.
struct PathWalk<'b> {
    block: &'b LoopBlock,
    /// The ATN state of the exit config.
    state: ATNStateRef,
    /// Only the paths that return into the operator loop count.
    loop_only: bool,
}

impl PathWalk<'_> {
    /// Whether each path of `exit` that counts is also a path of one of
    /// `iterate`. All contexts start below the same frames, and `last` is the
    /// return state of the lowest of these frames.
    fn covered<'a>(
        &self,
        exit: Option<PredictionContextRef<'a>>,
        iterate: Vec<Option<PredictionContextRef<'a>>>,
        last: Option<ATNStateRef>,
        budget: &mut usize,
    ) -> bool {
        let Some(left) = budget.checked_sub(1) else {
            return false;
        };
        *budget = left;
        let Some(exit) = exit.filter(|context| !context.is_empty()) else {
            return self.path_end_covered(&iterate, last);
        };
        for index in 0..exit.length() {
            let return_state = exit.get_return_state(index);
            if return_state == ATNStateRef::empty_return() {
                if !self.path_end_covered(&iterate, last) {
                    return false;
                }
                continue;
            }
            let next = iterate
                .iter()
                .flatten()
                .filter(|context| !context.is_empty())
                .flat_map(|context| {
                    (0..context.length())
                        .filter(move |&other| context.get_return_state(other) == return_state)
                        .map(move |other| context.get_parent(other))
                })
                .collect();
            if !self.covered(exit.get_parent(index), next, Some(return_state), budget) {
                return false;
            }
        }
        true
    }

    /// Whether a path that ends below the frame of `last` either does not
    /// count or also ends in one of `iterate`.
    fn path_end_covered(
        &self,
        iterate: &[Option<PredictionContextRef<'_>>],
        last: Option<ATNStateRef>,
    ) -> bool {
        let counts = !self.loop_only || self.block.is_loop_state(last.unwrap_or(self.state));
        !counts
            || iterate.iter().any(|context| {
                context
                    .as_ref()
                    .is_none_or(|context| context.has_empty_path())
            })
    }
}

/// A context node's identity, for cycle-safe recursion over a shared DAG.
fn pointer_key(context: &PredictionContextRef<'_>) -> *const () {
    context.as_ref() as *const _ as *const ()
}

/// Every position of the operator loop: the loop decision, the operator
/// alternatives, and the follow states of their operands. Rule references
/// contribute their follow state, never the callee's body - an operand runs
/// with an operator-loop frame in its context, so its own consumption is
/// attributed by [`LoopBlock::is_loop_consumption`]. The base alternatives are
/// not part of the loop: an enclosing invocation that continues a base
/// alternative (`'(' e ')'`, `'pair' e e`) consumes for that alternative, not
/// for the loop.
fn operator_states(decision_state: ATNStateRef) -> BitSet {
    rule_positions(decision_state, None)
}

/// Rule-local positions that cannot reach the loop decision by epsilon alone.
///
/// Such a position owes a token of the current alternative; the complement
/// owes nothing, because it can step onto the decision and let the lookahead
/// decide (an optional trailing token like DuckDB's `'(+)'?` is not an
/// obligation, but `Send`'s `'>>'` is).
fn pending_states(atn: &ATN, decision_state: ATNStateRef, rule_index: i32) -> BitSet {
    let states_count = atn.states_count();
    let mut reverse_epsilon: Vec<Vec<ATNStateRef>> = vec![Vec::new(); states_count];
    for state in atn.iter_states() {
        if state.get_rule_index() != rule_index {
            continue;
        }
        for transition in state.get_transitions() {
            if !transition.is_epsilon()
                || transition.try_as::<RuleTransition>().is_some()
                || transition.get_target().get_rule_index() != rule_index
            {
                continue;
            }
            let target = transition.get_target().get_state_number() as usize;
            reverse_epsilon[target].push(atn.make_state_ref(state.get_state_number()));
        }
    }

    let mut skips: BitSet = BitSet::new();
    let mut work: Vec<ATNStateRef> = vec![decision_state];
    skips.insert(decision_state.get_state_number() as usize);
    while let Some(state) = work.pop() {
        for predecessor in &reverse_epsilon[state.get_state_number() as usize] {
            if skips.insert(predecessor.get_state_number() as usize) {
                work.push(*predecessor);
            }
        }
    }

    let mut pending = BitSet::new();
    for state in atn.iter_states() {
        if state.get_rule_index() != rule_index || state.state_type() == ATNStateType::RuleStop {
            continue;
        }
        if !skips.contains(state.get_state_number() as usize) {
            pending.insert(state.get_state_number() as usize);
        }
    }
    pending
}

/// Whether every guarded alternative is simple: at most one rule invocation
/// and no internal iteration between its precedence predicate and the loop end.
fn guards_are_simple(atn: &ATN, decision_state: ATNStateRef, rule_index: i32) -> bool {
    let mut pending: Vec<ATNStateRef> = Vec::new();
    for state in atn.iter_states() {
        if state.get_rule_index() != rule_index {
            continue;
        }
        for transition in state.get_transitions() {
            if transition
                .try_as::<PrecedencePredicateTransition>()
                .is_some()
            {
                pending.push(transition.get_target());
            }
        }
    }

    while let Some(start) = pending.pop() {
        let mut visited: HashSet<i32> = HashSet::new();
        let mut invocations = 0;
        let mut work: Vec<ATNStateRef> = vec![start];
        while let Some(current) = work.pop() {
            if current == decision_state
                || current.get_rule_index() != rule_index
                || !visited.insert(current.get_state_number())
            {
                continue;
            }
            if matches!(
                current.state_type(),
                ATNStateType::StarBlockStart | ATNStateType::PlusBlockStart
            ) {
                return false;
            }
            for transition in current.get_transitions() {
                match transition.try_as::<RuleTransition>() {
                    Some(rule) => {
                        invocations += 1;
                        if invocations > 1 {
                            return false;
                        }
                        work.push(rule.follow_state);
                    }
                    None => work.push(transition.get_target()),
                }
            }
        }
    }
    true
}