dbt-antlr4 1.3.6

Dbt fork of ANTLR4 runtime for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Error types
use crate::atn_simulator::IATNSimulator;
use crate::interval_set::IntervalSet;
use crate::parser::Parser;
use crate::rule_context::states_stack;
use crate::token::{OwningToken, Token};
use crate::token_factory::TokenFactory;
use crate::transition::PredicateTransition;
use crate::tree::TreeNode;
use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::fmt::Formatter;
use std::fmt::{Debug, Display};
use std::ops::Deref;
use std::sync::Arc;

/// Main ANTLR4 Rust runtime error
#[derive(Debug, Clone)]
pub enum ANTLRErrorKind {
    /// Returned from Lexer when it fails to find matching token type for current input
    ///
    /// Usually Lexers contain last rule that captures all invalid tokens like:
    /// ```text
    /// ERROR_TOKEN: . ;
    /// ```
    /// to prevent lexer from throwing errors and have all error handling in parser.
    LexerNoAltError {
        /// Index at which error has happened
        start_index: isize,
    },

    /// Indicates that the parser could not decide which of two or more paths
    /// to take based upon the remaining input. It tracks the starting token
    /// of the offending input and also knows where the parser was
    /// in the various paths when the error. Reported by reportNoViableAlternative()
    NoAltError(NoViableAltError),

    /// This signifies any kind of mismatched input exceptions such as
    /// when the current input does not match the expected token.
    InputMismatchError(InputMisMatchError),

    /// A semantic predicate failed during validation. Validation of predicates
    /// occurs when normally parsing the alternative just like matching a token.
    /// Disambiguating predicate evaluation occurs when we test a predicate during
    /// prediction.
    PredicateError(FailedPredicateError),

    /// Internal error. Or user provided type returned data that is
    /// incompatible with current parser state
    IllegalStateError(String),

    CustomError(String),

    /// Unrecoverable error. Indicates that error should not be processed by parser/error strategy
    /// and it should abort parsing and immediately return to caller.
    FallThrough(Arc<dyn Error + Send + Sync + 'static>),

    /// Potentially recoverable error.
    /// Used to allow user to emit his own errors from parser actions or from custom error strategy.
    /// Parser will try to recover with provided `ErrorStrategy`
    OtherError(Arc<dyn Error + Send + Sync + 'static>),
}

#[derive(Debug, Clone)]
pub struct ANTLRError(pub Box<ANTLRErrorKind>);

impl Display for ANTLRError {
    fn fmt(&self, _f: &mut Formatter<'_>) -> fmt::Result {
        match self.0.as_ref() {
            ANTLRErrorKind::FallThrough(err) | ANTLRErrorKind::OtherError(err) => {
                write!(_f, "{}", err)
            }
            _ => <Self as Debug>::fmt(self, _f),
        }
    }
}

impl Error for ANTLRError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self.0.as_ref() {
            ANTLRErrorKind::FallThrough(x) => Some(x.as_ref()),
            ANTLRErrorKind::OtherError(x) => Some(x.as_ref()),
            _ => None,
        }
    }
}

impl From<ANTLRErrorKind> for ANTLRError {
    fn from(value: ANTLRErrorKind) -> Self {
        ANTLRError(Box::new(value))
    }
}

impl From<Box<dyn Error + Send + Sync + 'static>> for ANTLRError {
    fn from(value: Box<dyn Error + Send + Sync + 'static>) -> Self {
        ANTLRErrorKind::OtherError(Arc::from(value)).into()
    }
}

impl AsRef<ANTLRErrorKind> for ANTLRError {
    fn as_ref(&self) -> &ANTLRErrorKind {
        self.0.as_ref()
    }
}

impl Deref for ANTLRError {
    type Target = ANTLRErrorKind;

    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}

impl ANTLRError {
    pub fn custom_error(msg: String) -> Self {
        ANTLRErrorKind::CustomError(msg).into()
    }

    pub fn lexer_no_alt(start_index: isize) -> Self {
        ANTLRErrorKind::LexerNoAltError { start_index }.into()
    }

    pub fn illegal_state(msg: String) -> Self {
        ANTLRErrorKind::IllegalStateError(msg).into()
    }

    pub fn fall_through<E: Error + Send + Sync + 'static>(err: E) -> Self {
        ANTLRErrorKind::FallThrough(Arc::new(err)).into()
    }

    pub fn arena_allocation_limit_exceeded(
        allocation_limit_bytes: usize,
        allocated_bytes: usize,
    ) -> Self {
        ANTLRErrorKind::FallThrough(Arc::new(ArenaAllocationLimitExceededError {
            allocation_limit_bytes,
            allocated_bytes,
        }))
        .into()
    }

    pub fn dfa_cache_limit_exceeded(
        allocation_limit_bytes: usize,
        context_cache_bytes: usize,
        dfa_cache_bytes: usize,
    ) -> Self {
        ANTLRErrorKind::FallThrough(Arc::new(DFACacheLimitExceededError {
            allocation_limit_bytes,
            context_cache_bytes,
            dfa_cache_bytes,
        }))
        .into()
    }

    pub fn recursion_limit_exceeded(recursion_limit: u32) -> Self {
        ANTLRErrorKind::FallThrough(Arc::new(RecursionLimitExceededError { recursion_limit }))
            .into()
    }

    pub fn no_alt<'input, 'arena, TF, P>(recog: &mut P) -> Self
    where
        'input: 'arena,
        TF: TokenFactory<'input, 'arena> + 'arena,
        P: Parser<'input, 'arena, TF>,
    {
        ANTLRErrorKind::NoAltError(NoViableAltError {
            base: BaseRecognitionError {
                message: "".to_string(),
                offending_token: OwningToken::from(recog.get_current_token() as &dyn Token),
                offending_state: recog.get_state(),
                // ctx: recog.get_parser_rule_context().clone(),
                states_stack: states_stack(recog.get_current_context()).collect(),
            },
            start_token: OwningToken::from(recog.get_current_token() as &dyn Token),
            //            ctx: recog.get_parser_rule_context().clone()
        })
        .into()
    }

    pub fn no_alt_full<'input, 'arena, TF, P>(
        recog: &mut P,
        start_token: OwningToken,
        offending_token: OwningToken,
    ) -> Self
    where
        'input: 'arena,
        TF: TokenFactory<'input, 'arena> + 'arena,
        P: Parser<'input, 'arena, TF>,
    {
        ANTLRErrorKind::NoAltError(NoViableAltError {
            base: BaseRecognitionError {
                message: "".to_string(),
                offending_token,
                offending_state: recog.get_state(),
                states_stack: states_stack(recog.get_current_context()).collect(), // ctx: recog.get_parser_rule_context().clone(),
            },
            start_token,
            //            ctx
        })
        .into()
    }

    pub fn input_mismatch<'input, 'arena, TF, P>(recognizer: &mut P) -> Self
    where
        'input: 'arena,
        TF: TokenFactory<'input, 'arena> + 'arena,
        P: Parser<'input, 'arena, TF>,
    {
        ANTLRErrorKind::InputMismatchError(InputMisMatchError {
            base: BaseRecognitionError::new(recognizer),
        })
        .into()
    }

    pub fn input_mismatch_with_state<'input, 'arena, TF, P>(
        recognizer: &mut P,
        offending_state: i32,
        ctx: &'arena TreeNode<'input, 'arena, P::Node, TF::Tok>,
    ) -> Self
    where
        'input: 'arena,
        TF: TokenFactory<'input, 'arena> + 'arena,
        P: Parser<'input, 'arena, TF>,
    {
        let mut a = InputMisMatchError {
            base: BaseRecognitionError::new(recognizer),
        };
        // a.base.ctx = ctx;
        a.base.offending_state = offending_state;
        a.base.states_stack = states_stack(ctx).collect();
        ANTLRErrorKind::InputMismatchError(a).into()
    }

    pub fn failed_predicate<'input, 'arena, TF, P>(
        recog: &mut P,
        predicate: Option<String>,
        msg: Option<String>,
    ) -> Self
    where
        'input: 'arena,
        TF: TokenFactory<'input, 'arena> + 'arena,
        P: Parser<'input, 'arena, TF>,
    {
        let tr = recog
            .get_interpreter()
            .atn()
            .get_state(recog.get_state())
            .get_transitions()
            .first()
            .unwrap();
        let (rule_index, _) = if let Some(pr) = tr.try_as::<PredicateTransition>() {
            (pr.rule_index(), pr.pred_index())
        } else {
            (0, 0)
        };

        ANTLRErrorKind::PredicateError(FailedPredicateError {
            base: BaseRecognitionError {
                message: msg.unwrap_or_else(|| {
                    format!(
                        "failed predicate: {}",
                        predicate.as_deref().unwrap_or("None")
                    )
                }),
                offending_token: OwningToken::from(recog.get_current_token() as &dyn Token),
                offending_state: recog.get_state(),
                states_stack: states_stack(recog.get_current_context()).collect(), // ctx: recog.get_parser_rule_context().clone()
            },
            rule_index,
            predicate: predicate.unwrap_or_default(),
        })
        .into()
    }

    pub fn is_recoverable(&self) -> bool {
        !matches!(self.0.as_ref(), ANTLRErrorKind::FallThrough(_))
    }

    /// Returns first token that caused parser to fail.
    pub fn get_offending_token(&self) -> Option<&OwningToken> {
        Some(match self.0.as_ref() {
            ANTLRErrorKind::NoAltError(e) => &e.base.offending_token,
            ANTLRErrorKind::InputMismatchError(e) => &e.base.offending_token,
            ANTLRErrorKind::PredicateError(e) => &e.base.offending_token,
            _ => return None,
        })
    }
}

#[derive(Debug, Clone)]
pub struct ArenaAllocationLimitExceededError {
    pub allocation_limit_bytes: usize,
    pub allocated_bytes: usize,
}

impl Display for ArenaAllocationLimitExceededError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Arena allocation exceeded limit of {}B: total allocated size {}B",
            self.allocation_limit_bytes, self.allocated_bytes
        )
    }
}

impl Error for ArenaAllocationLimitExceededError {}

#[derive(Debug, Clone)]
pub struct DFACacheLimitExceededError {
    pub context_cache_bytes: usize,
    pub dfa_cache_bytes: usize,
    pub allocation_limit_bytes: usize,
}

impl Display for DFACacheLimitExceededError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Memory limit of {}B exceeded: total allocated Antlr cache size {}B\
            (context cache {}B/DFA {}B)",
            self.allocation_limit_bytes,
            self.context_cache_bytes + self.dfa_cache_bytes,
            self.context_cache_bytes,
            self.dfa_cache_bytes
        )
    }
}

impl Error for DFACacheLimitExceededError {}

#[derive(Debug, Clone)]
pub struct RecursionLimitExceededError {
    pub recursion_limit: u32,
}

impl Display for RecursionLimitExceededError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "Recursion limit of {} exceeded", self.recursion_limit)
    }
}

impl Error for RecursionLimitExceededError {}

/// Common part of ANTLR parser errors
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct BaseRecognitionError {
    pub message: String,
    //    recognizer: Box<Recognizer>,
    pub offending_token: OwningToken,
    pub offending_state: i32,
    states_stack: Vec<i32>, // ctx: Rc<dyn ParserRuleContext>
                            //    input: Box<IntStream>
}

impl BaseRecognitionError {
    /// Returns tokens that were expected by parser in error place
    pub fn get_expected_tokens<'a, 'input, 'arena, TF, P>(
        &'a self,
        recognizer: &P,
    ) -> Cow<'a, IntervalSet>
    where
        'input: 'arena,
        TF: TokenFactory<'input, 'arena> + 'arena,
        P: Parser<'input, 'arena, TF>,
    {
        recognizer
            .get_interpreter()
            .atn()
            .get_expected_tokens::<TF::Tok>(self.offending_state, self.states_stack.iter().copied())
    }

    fn new<'input, 'arena, TF, P>(recog: &mut P) -> BaseRecognitionError
    where
        'input: 'arena,
        TF: TokenFactory<'input, 'arena> + 'arena,
        P: Parser<'input, 'arena, TF>,
    {
        BaseRecognitionError {
            message: "".to_string(),
            offending_token: OwningToken::from(recog.get_current_token() as &dyn Token),
            offending_state: recog.get_state(),
            // ctx: recog.get_parser_rule_context().clone(),
            states_stack: states_stack(recog.get_current_context()).collect(),
        }
    }
}

/// See `ANTLRError::NoAltError`
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct NoViableAltError {
    pub base: BaseRecognitionError,
    pub start_token: OwningToken,
    //    ctx: Rc<dyn ParserRuleContext>,
    //    dead_end_configs: BaseATNConfigSet,
}

/// See `ANTLRError::InputMismatchError`
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct InputMisMatchError {
    pub base: BaseRecognitionError,
}

/// See `ANTLRError::PredicateError`
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct FailedPredicateError {
    pub base: BaseRecognitionError,
    pub rule_index: i32,
    pub predicate: String,
}