parlex-calc 0.4.1

Parlex example: simple calculator
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
//! # Calculator Parser
//!
//! This module couples the generated SLR(1) parser tables with calculator-
//! specific semantic actions. It exposes:
//!
//! - [`parser_data`]: generated automaton, productions, and IDs,
//! - [`CalcParserDriver`]: semantic hooks for reductions and ambiguities,
//! - [`CalcParser`]: a thin adapter that pulls tokens from the lexer and
//!   yields fully reduced results.
//!
//! The parser consumes tokens produced by [`CalcLexer`] and uses a mutable
//! [`SymTab`] as shared context (for interning identifiers and storing values).
//!
//! ## Behavior highlights
//! - **Operator precedence & associativity** are enforced via the ambiguity
//!   resolver: **shift** on higher-precedence lookahead, otherwise **reduce**.
//!   All binary operators in this grammar are left-associative; the prefix
//!   unary minus is handled separately and does not introduce conflicts.
//! - **Assignments** store the value in the symbol table and evaluate to the
//!   assigned value.
//! - **Empty statements** (a bare `;`) are emitted as a `Stat` token with
//!   [`TokenValue::None`].

use crate::{CalcLexer, CalcToken, SymTab, TokenID, TokenValue};
use parlex::{
    LexerStats, ParlexError, Parser, ParserAction, ParserData, ParserDriver, ParserStats, Token,
};
use parser_data::{AmbigID, ParData, ProdID, StateID};
use std::marker::PhantomData;
use try_next::TryNextWithContext;

/// Includes the generated SLR parser tables and definitions.
///
/// This file (`parser_data.rs`) is produced by the **parlex-gen** [`aslr`] tool
/// during the build process. It defines the parsing automaton, rule metadata,
/// and associated enum types used by the [`CalcParser`].
pub mod parser_data {
    include!(concat!(env!("OUT_DIR"), "/parser_data.rs"));
}

/// A driver that defines semantic actions for the calculator parser.
///
/// The [`CalcParserDriver`] type implements [`ParserDriver`] and acts as the
/// bridge between the parser engine ([`Parser`]) and calculator-specific
/// semantic logic.
///
/// It provides the behavior for grammar reductions and ambiguity resolution
/// during parsing. Each reduction corresponds to a grammar production rule
/// in [`ParData`], and is responsible for building or evaluating partial
/// results (e.g., computing arithmetic expressions, populating the symbol
/// table), constructing AST, etc.
///
/// # Type Parameters
///
/// - `I`: The input source (the lexer) that yields [`CalcToken`]s and maintains a
///   contextual [`SymTab`]. Must implement
///   [`TryNextWithContext<SymTab, Item = CalcToken>`].
///
/// # Associated Types
///
/// - `ParserData = ParData`:
///   Generated parser metadata containing grammar rules, production IDs,
///   and ambiguity identifiers.
/// - `Token = CalcToken`:
///   The token type produced by the lexer and consumed by this parser.
/// - `Parser = Parser<I, Self, SymTab>`:
///   The parser engine parameterized by this driver and context.
/// - `Error = CalcError`:
///   Unified error type propagated during parsing.
/// - `Context = SymTab`:
///   Externally supplied context.
///
/// # Responsibilities
///
/// The parser driver performs calculator-specific actions:
///
/// - **`resolve_ambiguity`** — invoked when the grammar allows multiple valid
///   interpretations of a token sequence. The driver chooses which parse path
///   to follow by returning an appropriate [`ParserAction`].
/// - **`reduce`** — executed when a grammar production completes. The driver
///   can perform semantic actions such as arithmetic evaluation, updating the
///   symbol table, or producing intermediate values.
///
/// # Notes
///
/// - The driver may be stateless (`_marker` only), or store intermediate
///   evaluation state if needed.
/// - Ambiguities can be resolved dynamically based on the current parse state
///   or the next lookahead token.
/// - The `reduce` method corresponds to grammar rules such as:
///   ```text
///   Expr → Expr '+' Expr
///   Expr → NUMBER
///   ```
///   allowing the driver to fold numerical operations or emit results or
///   result  nodes.
pub struct CalcParserDriver<I> {
    /// Marker to associate the driver with its input type `I`.
    _marker: PhantomData<I>,
}

impl<I> ParserDriver for CalcParserDriver<I>
where
    I: TryNextWithContext<SymTab, LexerStats, Item = CalcToken, Error: std::fmt::Display + 'static>,
{
    /// Parser metadata generated from the calculator grammar.
    type ParserData = ParData;

    /// Token type consumed by the parser.
    type Token = CalcToken;

    /// Concrete parser engine type.
    type Parser = Parser<I, Self, Self::Context>;

    /// Context (symbol table or shared state).
    type Context = SymTab;

    /// Resolves grammar ambiguities when multiple parse actions are valid.
    ///
    /// The driver can inspect the parser conflict (`ambig`) and the upcoming
    /// token (`token`) to decide which parse branch to follow. This method
    /// returns the selected [`ParserAction`].
    ///
    /// By default, most calculator grammars are unambiguous, so this method
    /// may simply return a default action or be left unimplemented.
    ///
    /// # Shift/Reduce Conflicts
    ///
    /// In practice, this hook is primarily used to resolve **Shift/Reduce**
    /// conflicts — cases where the parser can either:
    /// - **Reduce** using a completed production rule, or
    /// - **Shift** the next incoming token (`token`).
    ///
    /// Other types of conflicts (such as **Reduce/Reduce**) are much more
    /// difficult to handle programmatically and usually require modifying
    /// the grammar itself to eliminate ambiguity.
    ///
    /// In a typical arithmetic grammar, you can use operator precedence and
    /// associativity to decide whether to shift or reduce. For example:
    ///
    /// ```text
    /// Expr -> Expr '+' Expr
    /// ```
    ///
    /// When the incoming token is `*`, the driver can compare the precedence
    /// of `'+'` (lower) vs. `'*'` (higher) and decide to **Shift**, allowing
    /// the parser to defer reduction until the higher-precedence operation
    /// (`*`) is parsed first.
    ///
    /// This strategy ensures that the resulting parse tree respects the
    /// intended operator precedence and associativity rules.
    fn resolve_ambiguity(
        &mut self,
        _parser: &mut Self::Parser,
        _context: &mut Self::Context,
        ambig: <Self::ParserData as ParserData>::AmbigID,
        token: &Self::Token,
    ) -> Result<ParserAction<StateID, ProdID, AmbigID>, ParlexError> {
        let ambig_tab = ParData::lookup_ambig(ambig);
        let shift = ambig_tab[0];
        let reduce = ambig_tab[1];
        let ParserAction::Shift(_) = shift else {
            panic!("expected shift");
        };
        let ParserAction::Reduce(prod_id) = reduce else {
            panic!("expected reduce");
        };
        let CalcToken { token_id, .. } = token;

        match prod_id {
            ProdID::Expr3 | ProdID::Expr4 => {
                // Expr -> Expr + Expr | Expr - Expr
                match token_id {
                    TokenID::Plus | TokenID::Minus => Ok(reduce), // `+` and `-` are left-associative; `-` can't be unary in this context
                    TokenID::Asterisk | TokenID::Slash => Ok(shift), // `*` and `/` have higher precedence than `+` and `-`
                    _ => unreachable!(),
                }
            }
            ProdID::Expr5 | ProdID::Expr6 => {
                // Expr -> Expr * Expr | Expr / Expr
                Ok(reduce) // the lookahead `-` can't be unary; therefore, we reduce either by higher precedence or left associativity
            }
            ProdID::Expr7 => {
                // Expr -> - Expr
                Ok(reduce) // unary `-` has higher precedence than anything else
            }
            _ => panic!("unexpected prod in ambiguity"),
        }
    }

    /// Performs semantic reduction for a completed grammar production.
    ///
    /// This is the main hook for calculator logic: each time the parser
    /// recognizes a rule (identified by `prod_id`), the driver can evaluate
    /// or construct the corresponding result, possibly updating the context.
    ///
    /// For example, when reducing:
    /// ```text
    /// Expr -> Expr '+' Expr
    /// ```
    /// the driver may pop the right-hand values from the parser stack, perform
    /// addition, and push the result back.
    fn reduce(
        &mut self,
        parser: &mut Self::Parser,
        context: &mut Self::Context,
        prod_id: <Self::ParserData as ParserData>::ProdID,
        token: &Self::Token,
    ) -> Result<(), ParlexError> {
        match prod_id {
            ProdID::Start => {
                // Start -> Stat
                // Accept - does not get reduced
                unreachable!()
            }
            ProdID::Stat1 => {
                // Stat ->
                parser.tokens_push(CalcToken {
                    token_id: TokenID::Stat,
                    span: token.span(),
                    value: TokenValue::None,
                });
            }
            ProdID::Stat2 => {
                // Stat -> comment Stat
                let mut stat = parser.tokens_pop();
                let comment_tok = parser.tokens_pop();
                let TokenValue::Comment(comment) = comment_tok.value else {
                    unreachable!()
                };
                stat.to_statement(Some(comment));
                stat.merge_span(&comment_tok.span);
                parser.tokens_push(stat);
            }
            ProdID::Stat3 => {
                // Stat -> Expr
                let mut expr = parser.tokens_pop();
                expr.token_id = TokenID::Stat;
                parser.tokens_push(expr);
            }
            ProdID::Stat4 => {
                // Stat -> ident = Expr
                let mut expr = parser.tokens_pop();
                let TokenValue::Number(value) = expr.value else {
                    unreachable!()
                };
                parser.tokens_pop();
                let ident = parser.tokens_pop();
                let TokenValue::Ident(index) = ident.value else {
                    unreachable!()
                };
                context
                    .set(index, value)
                    .map_err(|e| ParlexError::from_err(e, ident.span()))?; //TODO: fix span
                expr.token_id = TokenID::Stat;
                expr.merge_span(&ident.span);
                parser.tokens_push(expr);
            }
            ProdID::Expr1 => {
                // Expr -> number
                let mut number = parser.tokens_pop();
                number.token_id = TokenID::Expr;
                parser.tokens_push(number);
            }
            ProdID::Expr2 => {
                // Expr -> ident
                let mut tok = parser.tokens_pop();
                tok.token_id = TokenID::Expr;
                let TokenValue::Ident(index) = tok.value else {
                    unreachable!()
                };
                tok.value = TokenValue::Number(
                    context
                        .get(index)
                        .map_err(|e| ParlexError::from_err(e, tok.span()))?,
                );
                parser.tokens_push(tok);
            }
            ProdID::Expr3 => {
                // Expr -> Expr + Expr
                let expr2 = parser.tokens_pop();
                parser.tokens_pop();
                let mut expr1 = parser.tokens_pop();
                let TokenValue::Number(value1) = expr1.value else {
                    unreachable!()
                };
                let TokenValue::Number(value2) = expr2.value else {
                    unreachable!()
                };
                expr1.value = TokenValue::Number(value1 + value2);
                expr1.merge_span(&expr2.span);
                parser.tokens_push(expr1);
            }
            ProdID::Expr4 => {
                // Expr -> Expr - Expr
                let expr2 = parser.tokens_pop();
                parser.tokens_pop();
                let mut expr1 = parser.tokens_pop();
                let TokenValue::Number(value1) = expr1.value else {
                    unreachable!()
                };
                let TokenValue::Number(value2) = expr2.value else {
                    unreachable!()
                };
                expr1.value = TokenValue::Number(value1 - value2);
                expr1.merge_span(&expr2.span);
                parser.tokens_push(expr1);
            }
            ProdID::Expr5 => {
                // Expr -> Expr * Expr
                let expr2 = parser.tokens_pop();
                parser.tokens_pop();
                let mut expr1 = parser.tokens_pop();
                let TokenValue::Number(value1) = expr1.value else {
                    unreachable!()
                };
                let TokenValue::Number(value2) = expr2.value else {
                    unreachable!()
                };
                expr1.value = TokenValue::Number(value1 * value2);
                expr1.merge_span(&expr2.span);
                parser.tokens_push(expr1);
            }
            ProdID::Expr6 => {
                // Expr -> Expr / Expr
                let expr2 = parser.tokens_pop();
                parser.tokens_pop();
                let mut expr1 = parser.tokens_pop();
                let TokenValue::Number(value1) = expr1.value else {
                    unreachable!()
                };
                let TokenValue::Number(value2) = expr2.value else {
                    unreachable!()
                };
                expr1.value = TokenValue::Number(value1 / value2);
                expr1.merge_span(&expr2.span);
                parser.tokens_push(expr1);
            }
            ProdID::Expr7 => {
                // Expr -> - Expr
                let mut expr = parser.tokens_pop();
                let minus = parser.tokens_pop();
                let TokenValue::Number(value) = expr.value else {
                    unreachable!()
                };
                expr.value = TokenValue::Number(-value);
                expr.merge_span(&minus.span);
                parser.tokens_push(expr);
            }
            ProdID::Expr8 => {
                // Expr -> ( Expr )
                let left_paren = parser.tokens_pop();
                let mut expr = parser.tokens_pop();
                let right_paren = parser.tokens_pop();
                expr.merge_span(&left_paren.span);
                expr.merge_span(&right_paren.span);
                parser.tokens_push(expr);
            }
        }
        Ok(())
    }
}

/// The calculator parser, a wrapper that couples:
/// - the calculator lexer ([`CalcLexer`]) producing [`CalcToken`]s, and
/// - the calculator parser driver ([`CalcParserDriver`]) implementing reductions
///   and ambiguity resolution for the calculator grammar.
///
/// `CalcParser<I>` exposes an iterator-like interface via
/// [`TryNextWithContext`], yielding completed parse results (e.g., one per
/// “sentence” or top-level expression) while using a shared [`SymTab`] as
/// context. Internally it owns a generic [`Parser`] that pulls tokens
/// from `CalcLexer` and executes semantic actions in `CalcParserDriver`.
///
/// # Input / Output
///
/// - **Input**: any byte stream `I` implementing
///   [`TryNextWithContext<SymTab, Item = u8>`].
/// - **Output**: completed parsing units as [`CalcToken`] values (typically
///   grammar-level results like expressions/statements).
///
/// # End Tokens and Multiple Sentences
///
/// The underlying lexer typically emits an explicit [`TokenID::End`] token at
/// the end of a *parsing unit* (end of “sentence” or expression). The parser
/// uses this to finalize and emit one result. If the input contains multiple
/// independent sentences, you will receive multiple results — one per `End` —
/// and `None` only after all input is consumed.
///
/// # Empty Statements
///
/// The calculator grammar also accepts an *empty* statement, which is returned
/// as a token with [`TokenValue::None`].
/// This occurs, for example, when the last statement in the input is terminated
/// by a semicolon (`;`) but followed by no further expression. In that case:
///
/// 1. The parser first emits the token for the preceding completed statement.
/// 2. It then emits an additional token representing the empty statement
///    (`TokenValue::None`).
/// 3. Finally, it returns `None`, indicating the end of the input stream.
///
/// This design allows the parser to fully reflect the structure of the input,
/// including empty or separator-only statements.
///
/// # Errors
///
/// All failures are surfaced through a composed
/// [`ParserError<LexerError<I::Error, CalcError>, CalcError, CalcToken>`]:
/// - `I::Error` — errors from the input source,
/// - [`CalcError`] — lexical/semantic errors (e.g., UTF-8, integer parsing,
///   symbol-table issues).
///
/// # Example
///
/// ```rust
/// # use parlex_calc::{CalcToken, CalcParser, SymTab, TokenID, TokenValue};
/// # use try_next::{IterInput, TryNextWithContext};
/// let mut symtab = SymTab::new();
/// let input = IterInput::from("hello = 1;\n foo =\n 5 + 3 * 2;\n (world + hello + 10) * -2;\n\n1000 - - -123".bytes());
/// let mut parser = CalcParser::try_new(input).unwrap();
/// let vs = parser.try_collect_with_context(&mut symtab).unwrap();
/// assert_eq!(vs.len(), 4);
/// assert_eq!(symtab.len(), 3);
/// ```
pub struct CalcParser<I>
where
    I: TryNextWithContext<SymTab, Item = u8, Error: std::fmt::Display + 'static>,
{
    parser: Parser<CalcLexer<I>, CalcParserDriver<CalcLexer<I>>, SymTab>,
}

impl<I> CalcParser<I>
where
    I: TryNextWithContext<SymTab, Item = u8, Error: std::fmt::Display + 'static>,
{
    pub fn try_new(input: I) -> Result<Self, ParlexError> {
        let lexer = CalcLexer::try_new(input)?;
        let driver = CalcParserDriver {
            _marker: PhantomData,
        };
        let parser = Parser::new(lexer, driver);
        Ok(Self { parser })
    }
}
impl<I> TryNextWithContext<SymTab, (LexerStats, ParserStats)> for CalcParser<I>
where
    I: TryNextWithContext<SymTab, Item = u8, Error: std::fmt::Display + 'static>,
{
    type Item = CalcToken;
    type Error = ParlexError;

    /// Returns the next fully reduced unit (`Stat`), or `None` at end of input.
    ///
    /// The underlying lexer typically emits an explicit [`TokenID::End`] at
    /// unit boundaries (e.g., semicolon-terminated statements). The parser
    /// finalizes and yields one `Stat` per such boundary.
    fn try_next_with_context(
        &mut self,
        context: &mut SymTab,
    ) -> Result<Option<CalcToken>, ParlexError> {
        self.parser.try_next_with_context(context)
    }

    fn stats(&self) -> (LexerStats, ParserStats) {
        self.parser.stats()
    }
}

#[cfg(test)]
mod tests {
    use crate::{CalcParser, CalcToken, SymTab, TokenID, TokenValue};
    use parlex::span;
    use try_next::{IterInput, TryNextWithContext};

    #[test]
    fn parses_four_stats() {
        let _ = env_logger::builder().is_test(true).try_init();
        let mut symtab = SymTab::new();
        let input = IterInput::from(
            "hello = 1;\n 1 + 2;\n (world + hello + 10) * -2;\n\n1000 - - -123;".bytes(),
        );
        let mut parser = CalcParser::try_new(input).unwrap();
        assert!(matches!(
            parser.try_next_with_context(&mut symtab).unwrap(),
            Some(CalcToken {
                token_id: TokenID::Stat,
                span: span!(0, 0, 0, 9),
                value: TokenValue::Number(1)
            }),
        ));
        assert!(matches!(
            parser.try_next_with_context(&mut symtab).unwrap(),
            Some(CalcToken {
                token_id: TokenID::Stat,
                span: span!(1, 1, 1, 6),
                value: TokenValue::Number(3)
            }),
        ));
        assert!(matches!(
            parser.try_next_with_context(&mut symtab).unwrap(),
            Some(CalcToken {
                token_id: TokenID::Stat,
                span: span!(2, 1, 2, 26),
                value: TokenValue::Number(-22)
            }),
        ));
        assert!(matches!(
            parser.try_next_with_context(&mut symtab).unwrap(),
            Some(CalcToken {
                token_id: TokenID::Stat,
                span: span!(4, 0, 4, 13),
                value: TokenValue::Number(877)
            }),
        ));
        assert!(matches!(
            parser.try_next_with_context(&mut symtab).unwrap(),
            Some(CalcToken {
                token_id: TokenID::Stat,
                span: span!(4, 14, 4, 14),
                value: TokenValue::None
            }),
        ));
        assert!(matches!(
            parser.try_next_with_context(&mut symtab).unwrap(),
            None,
        ));
        assert!(matches!(
            parser.try_next_with_context(&mut symtab).unwrap(),
            None,
        ));
    }

    #[test]
    fn parses_assignment_and_reference() {
        // x = 2; x + 3;
        let _ = env_logger::builder().is_test(true).try_init();
        let mut symtab = SymTab::new();
        let input = IterInput::from("x = 2;\n x + 3;".bytes());
        let mut parser = CalcParser::try_new(input).unwrap();

        // x = 2;
        let t1 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t1,
            CalcToken {
                token_id: TokenID::Stat,
                span: span!(0, 0, 0, 5),
                value: TokenValue::Number(2)
            }
        ));

        // x + 3;
        let t2 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t2,
            CalcToken {
                token_id: TokenID::Stat,
                span: span!(1, 1, 1, 6),
                value: TokenValue::Number(5)
            }
        ));

        // empty
        let t3 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t3,
            CalcToken {
                token_id: TokenID::Stat,
                span: span!(1, 7, 1, 7),
                value: TokenValue::None
            }
        ));

        // EOF
        assert!(parser.try_next_with_context(&mut symtab).unwrap().is_none());
        // symbol table contains one identifier
        assert_eq!(symtab.len(), 1);
    }

    #[test]
    fn respects_operator_precedence_and_unary_minus() {
        // 1 + 2 * 3;  -(1 + 2) * 3;
        let _ = env_logger::builder().is_test(true).try_init();
        let mut symtab = SymTab::new();
        let input = IterInput::from("1 + 2 * 3;\n-(1 + 2) * 3".bytes());
        let mut parser = CalcParser::try_new(input).unwrap();

        // 1 + 2 * 3 => 7
        let t1 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        dbg!(parser.stats());
        assert!(matches!(
            t1,
            CalcToken {
                token_id: TokenID::Stat,
                span: span!(0, 0, 0, 9),
                value: TokenValue::Number(7)
            }
        ));

        // -(1 + 2) * 3 => -9
        let t2 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t2,
            CalcToken {
                token_id: TokenID::Stat,
                span: span!(1, 0, 1, 12),
                value: TokenValue::Number(-9)
            }
        ));

        assert!(parser.try_next_with_context(&mut symtab).unwrap().is_none());
    }

    #[test]
    fn emits_empty_statement_as_none() {
        // 1; ;
        let _ = env_logger::builder().is_test(true).try_init();
        let mut symtab = SymTab::new();
        let input = IterInput::from("1; ;".bytes());
        let mut parser = CalcParser::try_new(input).unwrap();

        // 1;
        let t1 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t1,
            CalcToken {
                token_id: TokenID::Stat,
                value: TokenValue::Number(1),
                ..
            }
        ));

        // empty ;
        let t2 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t2,
            CalcToken {
                token_id: TokenID::Stat,
                value: TokenValue::None,
                ..
            }
        ));

        // empty EOF
        let t3 = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t3,
            CalcToken {
                token_id: TokenID::Stat,
                value: TokenValue::None,
                ..
            }
        ));

        // EOF
        assert!(parser.try_next_with_context(&mut symtab).unwrap().is_none());
    }

    #[test]
    fn parentheses_override_precedence() {
        // (1 + 2) * 3 => 9
        let _ = env_logger::builder().is_test(true).try_init();
        let mut symtab = SymTab::new();
        let input = IterInput::from("(1 + 2) * 3".bytes());
        let mut parser = CalcParser::try_new(input).unwrap();

        let t = parser.try_next_with_context(&mut symtab).unwrap().unwrap();
        assert!(matches!(
            t,
            CalcToken {
                token_id: TokenID::Stat,
                value: TokenValue::Number(9),
                ..
            }
        ));

        assert!(parser.try_next_with_context(&mut symtab).unwrap().is_none());
    }
}