lexigram-core 0.10.2

Library required by the lexer/parser source code generated by lexigram
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
// Copyright (c) 2026 Redglyph (@gmail.com). All Rights Reserved.

use std::fmt::{Display, Formatter};
use std::marker::PhantomData;
use crate::{AltId, CollectJoin, TokenId, VarId};
use crate::fixed_sym_table::{FixedSymTable, SymInfoTable};
use crate::lexer::{Pos, PosSpan};
use crate::log::LogMsg;
use crate::parser::{terminal_to_str_type, Call, ListenerWrapper, ParserError, ParserToken, Symbol, Terminate, RecoveryNt};

/// State index
pub type LRStateId = u16;

#[derive(Clone, Copy, Default, PartialEq, Debug)]
pub enum LRAction {
    #[default]
    Error,
    Shift(LRStateId),
    ShiftHook(LRStateId),
    Reduce(AltId),
    Accept,
}

impl LRAction {
    pub fn is_hook(&self) -> bool {
        matches!(self, LRAction::ShiftHook(_))
    }

    pub fn is_action(&self) -> bool {
        match self {
            LRAction::Error => false,
            LRAction::Shift(_)
            | LRAction::ShiftHook(_)
            | LRAction::Reduce(_)
            | LRAction::Accept => true,
        }
    }
}

impl Display for LRAction {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            LRAction::Error => write!(f, "-"),
            LRAction::Shift(s) => write!(f, "s{s}"),
            LRAction::ShiftHook(s) => write!(f, "${s}"),
            LRAction::Reduce(a) => write!(f, "r{a}"),
            LRAction::Accept => write!(f, "acc"),
        }
    }
}

pub trait WrapperLRErrorRecovery {
    /// Requests the wrapper to pop a nonterminal value. Some intermediate nonterminal values may have to be
    /// dropped when the parser is trying to recover from a syntax error.
    ///
    /// The wrapper may want to store the latest dropped value, in case [`push_nt_recovery_value`] is
    /// called immediately after to request a recovery value. In most cases, the latest dropped value is
    /// a good candidate, especially if it's a loop nonterminal.
    fn pop_nt_value(&mut self) {}

    /// Requests the wrapper to push a nonterminal value to resynchronize its stack in case of error recovery.
    ///
    /// The wrapper should ideally requires a value to the user through the listener interface, knowing this value
    /// is used to recover from a syntax error.
    ///
    /// Returns
    /// * [RecoveryNt::Done] if the stack could be resynchronized.
    /// * [RecoveryNt::Skip] if the value couldn't be created and another recover point should be found.
    /// * [RecoveryNt::Abort] if the wrapper can't be resynchronized. The parser will continue parsing the text
    ///   to detect other parsing errors, but it won't call the wrapper any more, except to intercept tokens.
    #[allow(unused_variables)]
    fn push_nt_recovery_value(&mut self, nt: VarId, err_span: &PosSpan) -> RecoveryNt { RecoveryNt::Abort }

    /// Notifies the wrapper that the parser has recovered from the syntax error. It can be used to forward
    /// the notification to the listener.
    fn syntax_error_recovered(&mut self) {}
}

/// Parser object. The [new(...)](LRParser::new) method creates a new instance.
pub struct LRParser<'a, T> {
    num_nt: usize,                          // doesn't include the goal NT
    num_t_full: usize,                      // includes the end symbol
    action: &'a [LRAction],
    goto: &'a [LRStateId],
    alt_nt_len: &'a [(VarId, u16, u16)],    // alt_id -> (nt, # symbols in alt, # terminals in alt)
    symbol_table: FixedSymTable,            // must include terminals <$> and <empty> at the end
    init_hook: bool,                        // first terminal must be intercepted
    state_symbol: &'a [Symbol],
    nt_value: &'a [bool],
    _phantom: PhantomData<T>,
}

impl<'a, T> LRParser<'a, T> {
    pub const MAX_NBR_PARSER_ERRORS: u32 = 5;
    pub const MAX_NBR_LEXER_ERRORS: u32 = 3;

    pub fn new(
        num_nt: usize,
        num_t_full: usize,
        action: &'a [LRAction],
        goto: &'a [LRStateId],
        alt_nt_len: &'a [(VarId, u16, u16)],
        symbol_table: FixedSymTable,
        init_hook: bool,
        state_symbol: &'a [Symbol],
        nt_value: &'a [bool],
    ) -> Self {
        LRParser { num_nt, num_t_full, action, goto, alt_nt_len, symbol_table, init_hook, state_symbol, nt_value, _phantom: PhantomData }
    }

    fn t_to_string(&self, t: TokenId) -> String {
        if self.num_t_full - 1 > t as usize {
            Symbol::T(t as TokenId).to_str_quote(Some(&self.symbol_table))
        } else {
            "<EOF>".to_string()
        }
    }

    /// Parses the entire `stream`, calling the (listener) [wrapper](ListenerWrapper) with the
    /// [actions](Call) that correspond to the parser events.
    ///
    /// Returns `Ok(())` if the whole stream could be successfully parsed, or an
    /// [error](ParserError) if it couldn't.
    ///
    /// All errors are reported in the wrapper's log. Usually, the wrapper simply transmits the
    /// reports to the user listener's log (done in the generated code).
    pub fn parse_stream<I, L>(&mut self, wrapper: &mut L, mut stream: I) -> Result<(), ParserError>
        where I: Iterator<Item=ParserToken>,
              L: ListenerWrapper + WrapperLRErrorRecovery,
    {
        const VERBOSE: bool = false;
        const BEFORE: &str = "\u{1b}[33m";
        const AFTER : &str = "\u{1b}[0m";
        let sym_table: Option<&FixedSymTable> = Some(&self.symbol_table);
        let token_error = self.num_t_full as TokenId;
        let token_eof = token_error - 1;
        let mut error = None;
        let mut nbr_parser_errors = 0;
        let mut nbr_lexer_errors = 0;
        let mut state: LRStateId = 0;
        let mut stack_state = vec![state];
        let mut stack_t = vec![];
        let mut advance_stream = true;
        let mut stream_pos = None;
        let mut stream_span = PosSpan::empty();
        let mut stream_sym = TokenId::default();
        let mut stream_str = String::default();
        let mut call_wrapper = true;
        let mut hook = self.init_hook;
        loop {
            if advance_stream {
                (stream_sym, stream_str) = if let Some((t, s, span)) = stream.next() {
                    stream_pos = Some(span.first_forced());
                    stream_span = span;
                    if !hook {
                        let new_t = wrapper.intercept_token(t, &s, &stream_span);
                        (new_t, s)
                    } else {
                        hook = false;
                        let new_t = if nbr_parser_errors == 0 {
                            let new_t = wrapper.hook(t, s.as_str(), &stream_span);
                            if VERBOSE {
                                println!(
                                    "{BEFORE}hook changed {} to {}{AFTER}",
                                    Symbol::T(t).to_str(Some(&self.symbol_table)), Symbol::T(new_t).to_str(Some(&self.symbol_table)))
                            }
                            new_t
                        } else {
                            t
                        };
                        (new_t, s)
                    }
                } else {
                    if let Some((_t, s, _span)) = stream.next() {
                        // an error code after the end means an unrecognized sequence: we may try to continue
                        wrapper.report(Some(&stream_span), LogMsg::Error(format!("lexical error: {s}")));
                        nbr_lexer_errors += 1;
                        if nbr_lexer_errors <= Self::MAX_NBR_LEXER_ERRORS {
                            continue;
                        }
                        error = Some(ParserError::TooManyErrors);
                        break;
                    } else {
                        // end of stream
                        (token_eof, String::new())
                    }
                };
                advance_stream = false;
            }
            if VERBOSE {
                println!(
                    "{BEFORE}states [{}] {state}, stack_t [{}], input: {} ({stream_str:?}){AFTER}",
                    stack_state.iter().map(|s| s.to_string()).join(" "),
                    stack_t.iter().map(|s| format!("{s:?}")).join(", "),
                    Symbol::T(stream_sym).to_str(sym_table)
                );
            }
            let action = self.action[stream_sym as usize + state as usize * self.num_t_full];
            match action {
                LRAction::Shift(new_state) | LRAction::ShiftHook(new_state) => {
                    hook = action.is_hook();
                    if VERBOSE { println!("{BEFORE}- shift({new_state}){AFTER}"); }
                    stack_state.push(new_state);
                    if self.symbol_table.is_token_data(stream_sym) {
                        stack_t.push(std::mem::take(&mut stream_str));
                    }
                    if call_wrapper { wrapper.push_span(stream_span.take()); }
                    state = new_state;
                    advance_stream = true;
                }
                LRAction::Reduce(alt) => {
                    // alt: s -> ω
                    let (nt, alt_len, nbr_t) = self.alt_nt_len[alt as usize];   // s
                    stack_state.drain(stack_state.len() - alt_len as usize..);  // pop |ω| states
                    let pop_state = *stack_state.last().unwrap();
                    state = self.goto[nt as usize + pop_state as usize * self.num_nt];
                    stack_state.push(state);
                    if VERBOSE { println!("{BEFORE}- reduce({alt}) -> state {pop_state} -> goto {state}{AFTER}"); }
                    let t_data = stack_t.drain(stack_t.len() - nbr_t as usize..).to_vec();
                    if call_wrapper { wrapper.switch(Call::Exit, nt, alt, Some(t_data)); }
                }
                LRAction::Accept => {
                    if VERBOSE { println!("{BEFORE}- accept{AFTER}"); }
                    if call_wrapper { wrapper.switch(Call::End(Terminate::None), 0, 0, None); }
                    stack_state.pop();
                    stack_state.pop();
                    break;
                }
                LRAction::Error => {
                    let expected = (0..self.num_t_full)
                        .filter(|t| self.action[*t + state as usize * self.num_t_full].is_action())
                        .map(|t| self.t_to_string(t as TokenId))
                        .join(", ");
                    let sym_str = if stream_sym == token_eof {
                        "end of stream".to_string()
                    } else {
                        format!("input {}", terminal_to_str_type(stream_sym, sym_table, &stream_str))
                    };
                    let msg = format!(
                        "syntax error: unexpected {sym_str}{}{}",
                        if expected.is_empty() { String::new() } else { format!(" instead of {expected}") },
                        if let Some(Pos(line, col)) = stream_pos { format!(", line {line}, col {col}") } else { String::new() }
                    );
                    wrapper.report(Some(&stream_span), LogMsg::Error(msg));
                    nbr_parser_errors += 1;
                    if nbr_parser_errors > Self::MAX_NBR_PARSER_ERRORS {
                        error = Some(ParserError::TooManyErrors);
                        break;
                    }
                    let prev_call_wrapper = call_wrapper;
                    if let Some(new_state) = self.recover(
                        &mut stream,
                        &mut stream_sym,
                        &mut stream_str,
                        &mut stream_pos,
                        &mut stream_span,
                        wrapper,
                        &mut stack_state,
                        &mut stack_t,
                        &mut call_wrapper
                    ) {
                        let pos = if let Some(pos) = stream_pos { format!(" at {pos}") } else { String::new() };
                        wrapper.report(None, LogMsg::Note(format!("resynchronized from syntax error on {}{pos}", self.t_to_string(stream_sym))));
                        if prev_call_wrapper && !call_wrapper {
                            wrapper.report(None, LogMsg::Note("the rest of the stream will be parsed, but the listener interface can't be used any more".to_string()));
                        }
                        state = new_state;
                        stack_state.push(state);
                        if call_wrapper {
                            wrapper.syntax_error_recovered();
                        }
                    } else {
                        if VERBOSE { println!("couldn't recover\n- states {stack_state:?}"); }
                        error = Some(ParserError::SyntaxError);
                        break;
                    }
                }
            }
            match wrapper.check_abort_request() {
                Terminate::None => {}
                terminate @ (Terminate::Abort | Terminate::Conclude) => {
                    if VERBOSE { println!("{BEFORE}detected {terminate:?}{AFTER}"); }
                    stack_state.clear();
                    wrapper.abort();
                    wrapper.switch(Call::End(terminate), 0, 0, None);
                    if terminate == Terminate::Abort {
                        return Err(ParserError::AbortRequest);
                    } else {
                        break;
                    }
                }
            }
        }
        if nbr_parser_errors == 0 && nbr_lexer_errors == 0 && error.is_none() {
            assert!(stack_t.is_empty(), "stack_t: {}", stack_t.join(", "));
            assert!(stack_state.is_empty(), "stack_state: {}", stack_state.iter().map(LRStateId::to_string).collect::<Vec<_>>().join(", "));
            assert!(wrapper.is_stack_empty(), "symbol stack isn't empty");
            assert!(wrapper.is_stack_t_empty(), "text stack isn't empty");
            assert!(wrapper.is_stack_span_empty(), "span stack isn't empty");
            Ok(())
        } else {
            let err = error.unwrap_or(ParserError::EncounteredErrors);
            wrapper.abort();
            Err(err)
        }
    }

    /// Returns the symbol on the left of the dot and whether it has a value.
    fn get_state_symbol_and_value(&self, state: LRStateId) -> (Symbol, bool) {
        let sym = self.state_symbol[state as usize];
        let has_value = match sym {
            Symbol::T(t) => self.symbol_table.is_token_data(t),
            Symbol::NT(nt) => self.nt_value[nt as usize],
            Symbol::Empty => false,
            Symbol::End => panic!(),
        };
        (sym, has_value)
    }

    fn recover<I, L>(
        &self,
        stream: &mut I,
        stream_sym: &mut u16,
        stream_str: &mut String,
        stream_pos: &mut Option<Pos>,
        stream_span: &mut PosSpan,
        wrapper: &mut L,
        stack_state: &mut Vec<LRStateId>,
        stack_t: &mut Vec<String>,
        call_wrapper: &mut bool
    ) -> Option<LRStateId>
    where
        I: Iterator<Item=ParserToken>,
        L: ListenerWrapper + WrapperLRErrorRecovery,
    {
        const VERBOSE: bool = false;
        const BEFORE_ANSI: &str = "\u{1b}[31m";
        const AFTER_ANSI : &str = "\u{1b}[0m";
        if VERBOSE { println!("{BEFORE_ANSI}parser panic-mode recovery:{AFTER_ANSI}"); }
        let mut err_span = PosSpan::empty();
        // finds a state with a GOTO, but don't pop the start state
        while let Some(state) = stack_state.pop() {
            if VERBOSE { println!("{BEFORE_ANSI}- states {stack_state:?} {state}{AFTER_ANSI}"); }
            let goto_state = state;
            let goto_row = state as usize * self.num_nt;
            // check the available GOTO states:
            let candidates = self.goto.iter().skip(goto_row).take(self.num_nt).enumerate()
                .map(|(v, s)| (v as VarId, *s)).filter(|(_, s)| *s > 0)
                .to_vec();
            if VERBOSE {
                println!(
                    "{BEFORE_ANSI}- goto_state {goto_state}, candidates = {}, err_span {err_span}{AFTER_ANSI}",
                    candidates.iter().map(|(v, st)| format!("({}, {st})", Symbol::NT(*v).to_str(Some(&self.symbol_table)))).join(", ")
                );
            }
            if candidates.is_empty() {
                if *call_wrapper {
                    err_span += &wrapper.pop_span();
                }
                let (sym, has_value) = self.get_state_symbol_and_value(state);
                match sym {
                    Symbol::T(_) => {
                        if has_value { stack_t.pop(); }
                    }
                    Symbol::NT(_) => {
                        if has_value && *call_wrapper { wrapper.pop_nt_value(); }
                    }
                    _ => panic!()
                }
            }
            if VERBOSE {
                println!(
                    "{BEFORE_ANSI}- candidates = {}, err_span {err_span}{AFTER_ANSI}",
                    candidates.iter().map(|(v, st)| format!("({}, {st})", Symbol::NT(*v).to_str(Some(&self.symbol_table)))).join(", "));
            }
            let token_error = self.num_t_full as TokenId;
            let token_eof = token_error - 1;
            let mut skip = candidates.is_empty();
            while !skip {
                if VERBOSE { println!("{BEFORE_ANSI}  - states {stack_state:?} {state}, err_span {err_span}{AFTER_ANSI}"); }
                for &(var, state) in &candidates {
                    let action = &self.action[*stream_sym as usize + state as usize * self.num_t_full];
                    if action.is_action() {
                        if VERBOSE { println!("{BEFORE_ANSI}- symbol {} is fine for state {state}{AFTER_ANSI}", self.t_to_string(*stream_sym)); }
                        // if the wrapper is called, it can skip the recovery of the current nonterminal and
                        // recover at a higher level
                        let recovery_result = if *call_wrapper { wrapper.push_nt_recovery_value(var, &err_span) } else { RecoveryNt::Abort };
                        *call_wrapper &= recovery_result != RecoveryNt::Abort;
                        skip = *call_wrapper && recovery_result == RecoveryNt::Skip;
                        if !skip {
                            // we put back the goto_state on the stack because it will be required after the action
                            stack_state.push(goto_state);
                            if *call_wrapper {
                                wrapper.push_span(err_span);
                                if VERBOSE {
                                    println!("{BEFORE_ANSI}{}{AFTER_ANSI}", wrapper.get_status().join("\n"));
                                    println!("{BEFORE_ANSI}- states {stack_state:?}{AFTER_ANSI}");
                                }
                            }
                            return Some(state);
                        } else if *call_wrapper {
                            // removes the span corresponding to the skipped state and accumulates it
                            err_span += &wrapper.pop_span();
                        }
                        if VERBOSE { println!("{BEFORE_ANSI}skipping this recovery point{AFTER_ANSI}"); }
                    }
                }
                if !skip {
                    (*stream_sym, *stream_str) = loop {
                        if let Some((t, s, span)) = stream.next() {
                            *stream_pos = Some(span.first_forced());
                            // accumulates the position of the dropped token
                            err_span += stream_span;
                            *stream_span = span;
                            // we can't say which interception to use, so we call both
                            let t1 = wrapper.intercept_token(t, &s, stream_span);
                            let t2 = wrapper.hook(t1, s.as_str(), stream_span);
                            break (t2, s);
                        } else {
                            *stream_pos = None;
                            if let Some((_t, s, _span)) = stream.next() {
                                // an error code after the end means an unrecognized sequence: we may try to continue,
                                // but we don't count the max lexical errors here for the sake of simplicity
                                wrapper.report(Some(stream_span), LogMsg::Error(format!("lexical error: {s}")));
                                continue;
                            } else {
                                // end of stream
                                break (token_eof, String::new());
                            }
                        }
                    };
                    if *stream_sym == token_eof { return None; }
                    if VERBOSE { println!("{BEFORE_ANSI}- no symbol was compatible, scanning new symbol {}{AFTER_ANSI}", self.t_to_string(*stream_sym)); }
                }
            }
        }
        None
    }
}