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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
// Copyright (C) 2019-2024 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use super::*;
use leo_errors::{ParserError, Result};

use leo_span::sym;
use snarkvm::console::{account::Address, network::Network};

const INT_TYPES: &[Token] = &[
    Token::I8,
    Token::I16,
    Token::I32,
    Token::I64,
    Token::I128,
    Token::U8,
    Token::U16,
    Token::U32,
    Token::U64,
    Token::U128,
    Token::Field,
    Token::Group,
    Token::Scalar,
];

impl<N: Network> ParserContext<'_, N> {
    /// Returns an [`Expression`] AST node if the next token is an expression.
    /// Includes struct init expressions.
    pub(crate) fn parse_expression(&mut self) -> Result<Expression> {
        // Store current parser state.
        let prior_fuzzy_state = self.disallow_struct_construction;

        // Allow struct init expressions.
        self.disallow_struct_construction = false;

        // Parse expression.
        let result = self.parse_conditional_expression();

        // Restore prior parser state.
        self.disallow_struct_construction = prior_fuzzy_state;

        result
    }

    /// Returns an [`Expression`] AST node if the next tokens represent
    /// a ternary expression. May or may not include struct init expressions.
    ///
    /// Otherwise, tries to parse the next token using [`parse_boolean_or_expression`].
    pub(super) fn parse_conditional_expression(&mut self) -> Result<Expression> {
        // Try to parse the next expression. Try BinaryOperation::Or.
        let mut expr = self.parse_boolean_or_expression()?;

        // Parse the rest of the ternary expression.
        if self.eat(&Token::Question) {
            let if_true = self.parse_expression()?;
            self.expect(&Token::Colon)?;
            let if_false = self.parse_expression()?;
            expr = Expression::Ternary(TernaryExpression {
                span: expr.span() + if_false.span(),
                condition: Box::new(expr),
                if_true: Box::new(if_true),
                if_false: Box::new(if_false),
                id: self.node_builder.next_id(),
            });
        }
        Ok(expr)
    }

    /// Constructs a binary expression `left op right`.
    fn bin_expr(node_builder: &NodeBuilder, left: Expression, right: Expression, op: BinaryOperation) -> Expression {
        Expression::Binary(BinaryExpression {
            span: left.span() + right.span(),
            op,
            left: Box::new(left),
            right: Box::new(right),
            id: node_builder.next_id(),
        })
    }

    /// Parses a left-associative binary expression `<left> token <right>` using `f` for left/right.
    /// The `token` is translated to `op` in the AST.
    fn parse_bin_expr(
        &mut self,
        tokens: &[Token],
        mut f: impl FnMut(&mut Self) -> Result<Expression>,
    ) -> Result<Expression> {
        let mut expr = f(self)?;
        while let Some(op) = self.eat_bin_op(tokens) {
            expr = Self::bin_expr(self.node_builder, expr, f(self)?, op);
        }
        Ok(expr)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent
    /// a binary OR expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_boolean_and_expression`].
    fn parse_boolean_or_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::Or], Self::parse_boolean_and_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// binary AND expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_equality_expression`].
    fn parse_boolean_and_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::And], Self::parse_equality_expression)
    }

    /// Eats one of binary operators matching any in `tokens`.
    fn eat_bin_op(&mut self, tokens: &[Token]) -> Option<BinaryOperation> {
        self.eat_any(tokens).then(|| match &self.prev_token.token {
            Token::Eq => BinaryOperation::Eq,
            Token::NotEq => BinaryOperation::Neq,
            Token::Lt => BinaryOperation::Lt,
            Token::LtEq => BinaryOperation::Lte,
            Token::Gt => BinaryOperation::Gt,
            Token::GtEq => BinaryOperation::Gte,
            Token::Add => BinaryOperation::Add,
            Token::Sub => BinaryOperation::Sub,
            Token::Mul => BinaryOperation::Mul,
            Token::Div => BinaryOperation::Div,
            Token::Rem => BinaryOperation::Rem,
            Token::Or => BinaryOperation::Or,
            Token::And => BinaryOperation::And,
            Token::BitOr => BinaryOperation::BitwiseOr,
            Token::BitAnd => BinaryOperation::BitwiseAnd,
            Token::Pow => BinaryOperation::Pow,
            Token::Shl => BinaryOperation::Shl,
            Token::Shr => BinaryOperation::Shr,
            Token::BitXor => BinaryOperation::Xor,
            _ => unreachable!("`eat_bin_op` shouldn't produce this"),
        })
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// binary relational expression: less than, less than or equals, greater than, greater than or equals.
    ///
    /// Otherwise, tries to parse the next token using [`parse_additive_expression`].
    fn parse_ordering_expression(&mut self) -> Result<Expression> {
        let mut expr = self.parse_bitwise_exclusive_or_expression()?;
        if let Some(op) = self.eat_bin_op(&[Token::Lt, Token::LtEq, Token::Gt, Token::GtEq]) {
            let right = self.parse_bitwise_exclusive_or_expression()?;
            expr = Self::bin_expr(self.node_builder, expr, right, op);
        }
        Ok(expr)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// binary equals or not equals expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_ordering_expression`].
    fn parse_equality_expression(&mut self) -> Result<Expression> {
        let mut expr = self.parse_ordering_expression()?;
        if let Some(op) = self.eat_bin_op(&[Token::Eq, Token::NotEq]) {
            let right = self.parse_ordering_expression()?;
            expr = Self::bin_expr(self.node_builder, expr, right, op);
        }
        Ok(expr)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// bitwise exclusive or expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_bitwise_inclusive_or_expression`].
    fn parse_bitwise_exclusive_or_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::BitXor], Self::parse_bitwise_inclusive_or_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// bitwise inclusive or expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_bitwise_and_expression`].
    fn parse_bitwise_inclusive_or_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::BitOr], Self::parse_bitwise_and_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// bitwise and expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_shift_expression`].
    fn parse_bitwise_and_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::BitAnd], Self::parse_shift_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// shift left or a shift right expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_additive_expression`].
    fn parse_shift_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::Shl, Token::Shr], Self::parse_additive_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// binary addition or subtraction expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_mul_div_pow_expression`].
    fn parse_additive_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::Add, Token::Sub], Self::parse_multiplicative_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// binary multiplication, division, or a remainder expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_exponential_expression`].
    fn parse_multiplicative_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::Mul, Token::Div, Token::Rem], Self::parse_exponential_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// binary exponentiation expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_cast_expression`].
    fn parse_exponential_expression(&mut self) -> Result<Expression> {
        self.parse_bin_expr(&[Token::Pow], Self::parse_cast_expression)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// cast expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_unary_expression`].
    fn parse_cast_expression(&mut self) -> Result<Expression> {
        let mut expr = self.parse_unary_expression()?;
        if self.eat(&Token::As) {
            let (type_, end_span) = self.parse_primitive_type()?;
            let span = expr.span() + end_span;
            expr = Expression::Cast(CastExpression {
                expression: Box::new(expr),
                type_,
                span,
                id: self.node_builder.next_id(),
            });
        }

        Ok(expr)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// unary not, negate, or bitwise not expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_postfix_expression`].
    pub(super) fn parse_unary_expression(&mut self) -> Result<Expression> {
        let mut ops = Vec::new();
        while self.eat_any(&[Token::Not, Token::Sub]) {
            let operation = match self.prev_token.token {
                Token::Not => UnaryOperation::Not,
                Token::Sub => UnaryOperation::Negate,
                _ => unreachable!("parse_unary_expression_ shouldn't produce this"),
            };
            ops.push((operation, self.prev_token.span));
        }

        let mut inner = self.parse_postfix_expression()?;

        // If the last operation is a negation and the inner expression is a literal, then construct a negative literal.
        if let Some((UnaryOperation::Negate, _)) = ops.last() {
            match inner {
                Expression::Literal(Literal::Integer(integer_type, string, span, id)) => {
                    // Remove the negation from the operations.
                    // Note that this unwrap is safe because there is at least one operation in `ops`.
                    let (_, op_span) = ops.pop().unwrap();
                    // Construct a negative integer literal.
                    inner =
                        Expression::Literal(Literal::Integer(integer_type, format!("-{string}"), op_span + span, id));
                }
                Expression::Literal(Literal::Field(string, span, id)) => {
                    // Remove the negation from the operations.
                    // Note that
                    let (_, op_span) = ops.pop().unwrap();
                    // Construct a negative field literal.
                    inner = Expression::Literal(Literal::Field(format!("-{string}"), op_span + span, id));
                }
                Expression::Literal(Literal::Group(group_literal)) => {
                    // Remove the negation from the operations.
                    let (_, op_span) = ops.pop().unwrap();
                    // Construct a negative group literal.
                    // Note that we only handle the case where the group literal is a single integral value.
                    inner = Expression::Literal(Literal::Group(Box::new(match *group_literal {
                        GroupLiteral::Single(string, span, id) => {
                            GroupLiteral::Single(format!("-{string}"), op_span + span, id)
                        }
                        GroupLiteral::Tuple(tuple) => GroupLiteral::Tuple(tuple),
                    })));
                }
                Expression::Literal(Literal::Scalar(string, span, id)) => {
                    // Remove the negation from the operations.
                    let (_, op_span) = ops.pop().unwrap();
                    // Construct a negative scalar literal.
                    inner = Expression::Literal(Literal::Scalar(format!("-{string}"), op_span + span, id));
                }
                _ => (), // Do nothing.
            }
        }

        // Apply the operations in reverse order, constructing a unary expression.
        for (op, op_span) in ops.into_iter().rev() {
            inner = Expression::Unary(UnaryExpression {
                span: op_span + inner.span(),
                op,
                receiver: Box::new(inner),
                id: self.node_builder.next_id(),
            });
        }

        Ok(inner)
    }

    // TODO: Parse method call expressions directly and later put them into a canonical form.
    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// method call expression.
    fn parse_method_call_expression(&mut self, receiver: Expression, method: Identifier) -> Result<Expression> {
        // Parse the argument list.
        let (mut args, _, span) = self.parse_expr_tuple()?;
        let span = receiver.span() + span;

        if let (true, Some(op)) = (args.is_empty(), UnaryOperation::from_symbol(method.name)) {
            // Found an unary operator and the argument list is empty.
            Ok(Expression::Unary(UnaryExpression {
                span,
                op,
                receiver: Box::new(receiver),
                id: self.node_builder.next_id(),
            }))
        } else if let (1, Some(op)) = (args.len(), BinaryOperation::from_symbol(method.name)) {
            // Found a binary operator and the argument list contains a single argument.
            Ok(Expression::Binary(BinaryExpression {
                span,
                op,
                left: Box::new(receiver),
                right: Box::new(args.swap_remove(0)),
                id: self.node_builder.next_id(),
            }))
        } else if let (2, Some(CoreFunction::SignatureVerify)) =
            (args.len(), CoreFunction::from_symbols(sym::signature, method.name))
        {
            Ok(Expression::Access(AccessExpression::AssociatedFunction(AssociatedFunction {
                variant: Identifier::new(sym::signature, self.node_builder.next_id()),
                name: method,
                arguments: {
                    let mut arguments = vec![receiver];
                    arguments.extend(args);
                    arguments
                },
                span,
                id: self.node_builder.next_id(),
            })))
        } else if let (0, Some(CoreFunction::FutureAwait)) =
            (args.len(), CoreFunction::from_symbols(sym::Future, method.name))
        {
            Ok(Expression::Access(AccessExpression::AssociatedFunction(AssociatedFunction {
                variant: Identifier::new(sym::Future, self.node_builder.next_id()),
                name: method,
                arguments: vec![receiver],
                span,
                id: self.node_builder.next_id(),
            })))
        } else {
            // Attempt to parse the method call as a mapping operation.
            match (args.len(), CoreFunction::from_symbols(sym::Mapping, method.name)) {
                (1, Some(CoreFunction::MappingGet))
                | (2, Some(CoreFunction::MappingGetOrUse))
                | (2, Some(CoreFunction::MappingSet))
                | (1, Some(CoreFunction::MappingRemove))
                | (1, Some(CoreFunction::MappingContains)) => {
                    // Found an instance of `<mapping>.get`, `<mapping>.get_or_use`, `<mapping>.set`, `<mapping>.remove`, or `<mapping>.contains`.
                    Ok(Expression::Access(AccessExpression::AssociatedFunction(AssociatedFunction {
                        variant: Identifier::new(sym::Mapping, self.node_builder.next_id()),
                        name: method,
                        arguments: {
                            let mut arguments = vec![receiver];
                            arguments.extend(args);
                            arguments
                        },
                        span,
                        id: self.node_builder.next_id(),
                    })))
                }
                _ => {
                    // Either an invalid unary/binary operator, or more arguments given.
                    self.emit_err(ParserError::invalid_method_call(receiver, method, args.len(), span));
                    Ok(Expression::Err(ErrExpression { span, id: self.node_builder.next_id() }))
                }
            }
        }
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// static access expression.
    fn parse_associated_access_expression(&mut self, module_name: Expression) -> Result<Expression> {
        // Ensure that the preceding expression is an identifier (a named type).
        let variant = if let Expression::Identifier(ident) = module_name {
            ident
        } else {
            return Err(ParserError::invalid_associated_access(&module_name, module_name.span()).into());
        };

        // Parse the constant or function name.
        let member_name = self.expect_identifier()?;

        // Check if there are arguments.
        Ok(Expression::Access(if self.check(&Token::LeftParen) {
            // Parse the arguments
            let (args, _, end) = self.parse_expr_tuple()?;

            // Return the associated function.
            AccessExpression::AssociatedFunction(AssociatedFunction {
                span: module_name.span() + end,
                variant,
                name: member_name,
                arguments: args,
                id: self.node_builder.next_id(),
            })
        } else {
            // Return the associated constant.
            AccessExpression::AssociatedConstant(AssociatedConstant {
                span: module_name.span() + member_name.span(),
                ty: Type::Identifier(variant),
                name: member_name,
                id: self.node_builder.next_id(),
            })
        }))
    }

    /// Parses a tuple of `Expression` AST nodes.
    pub(crate) fn parse_expr_tuple(&mut self) -> Result<(Vec<Expression>, bool, Span)> {
        self.parse_paren_comma_list(|p| p.parse_expression().map(Some))
    }

    /// Parses an external function call `credits.aleo/transfer()` or locator `token.aleo/accounts`.
    ///
    /// In the ABNF grammar,
    /// an external function call is one of the two kinds of free function calls,
    /// namely the one that uses a locator to designate the function;
    /// a locator is a kind of primary expression.
    fn parse_external_resource(&mut self, expr: Expression, network_span: Span) -> Result<Expression> {
        // Parse `/`.
        self.expect(&Token::Div)?;

        // Parse name.
        let name = self.expect_identifier()?;

        // Ensure the preceding expression is a (program) identifier.
        let program: Identifier = match expr {
            Expression::Identifier(identifier) => identifier,
            _ => unreachable!("Function called must be preceded by a program identifier."),
        };

        // Parsing a '{' means that user is trying to illegally define an external record.
        if self.token.token == Token::LeftCurly {
            return Err(ParserError::cannot_define_external_record(expr.span() + name.span()).into());
        }

        // If there is no parenthesis, then it is a locator.
        if self.token.token != Token::LeftParen {
            // Parse an external resource locator.
            return Ok(Expression::Locator(LocatorExpression {
                program: ProgramId {
                    name: program,
                    network: Identifier { name: sym::aleo, span: network_span, id: self.node_builder.next_id() },
                },
                name: name.name,
                span: expr.span() + name.span(),
                id: self.node_builder.next_id(),
            }));
        }

        // Parse the function call.
        let (arguments, _, span) = self.parse_paren_comma_list(|p| p.parse_expression().map(Some))?;

        Ok(Expression::Call(CallExpression {
            span: expr.span() + span,
            function: Box::new(Expression::Identifier(name)),
            program: Some(program.name),
            arguments,
            id: self.node_builder.next_id(),
        }))
    }

    /// Returns an [`Expression`] AST node if the next tokens represent an
    /// array access, struct member access, tuple access, or method call expression.
    ///
    /// Otherwise, tries to parse the next token using [`parse_primary_expression`].
    /// Note that, as mentioned in [`parse_primary_expression`],
    /// this function also completes the parsing of some primary expressions
    /// (as defined in the ABNF grammar),
    /// which [`parse_primary_expression`] only starts to parse.
    fn parse_postfix_expression(&mut self) -> Result<Expression> {
        // We don't directly parse named types and identifiers in associated constants and functions
        // here as the ABNF states. Rather, those named types and identifiers are parsed
        // as primary expressions, and combined to form associated constants and functions here.
        let mut expr = self.parse_primary_expression()?;
        loop {
            if self.eat(&Token::Dot) {
                if self.check_int() {
                    // Eat a tuple member access.
                    let (index, span) = self.eat_whole_number()?;
                    expr = Expression::Access(AccessExpression::Tuple(TupleAccess {
                        tuple: Box::new(expr),
                        index,
                        span,
                        id: self.node_builder.next_id(),
                    }))
                } else if self.eat(&Token::Leo) {
                    return Err(ParserError::only_aleo_external_calls(expr.span()).into());
                } else if self.eat(&Token::Aleo) {
                    if self.token.token == Token::Div {
                        expr = self.parse_external_resource(expr, self.prev_token.span)?;
                    } else {
                        // Parse as address literal, e.g. `hello.aleo`.
                        if !matches!(expr, Expression::Identifier(_)) {
                            self.emit_err(ParserError::unexpected(expr.to_string(), "an identifier", expr.span()))
                        }

                        expr = Expression::Literal(Literal::Address(
                            format!("{}.aleo", expr),
                            expr.span(),
                            self.node_builder.next_id(),
                        ))
                    }
                } else {
                    // Parse instances of `self.address`.
                    if let Expression::Identifier(id) = expr {
                        if id.name == sym::SelfLower && self.token.token == Token::Address {
                            let span = self.expect(&Token::Address)?;
                            // Convert `self.address` to the current program name. TODO: Move this conversion to canonicalization pass when the new pass is added.
                            // Note that the unwrap is safe as in order to get to this stage of parsing a program name must have already been parsed.
                            return Ok(Expression::Literal(Literal::Address(
                                format!("{}.aleo", self.program_name.unwrap()),
                                expr.span() + span,
                                self.node_builder.next_id(),
                            )));
                        }
                    }

                    // Parse identifier name.
                    let name = self.expect_identifier()?;

                    if self.check(&Token::LeftParen) {
                        // Eat a method call on a type
                        expr = self.parse_method_call_expression(expr, name)?
                    } else {
                        // Eat a struct member access.
                        expr = Expression::Access(AccessExpression::Member(MemberAccess {
                            span: expr.span() + name.span(),
                            inner: Box::new(expr),
                            name,
                            id: self.node_builder.next_id(),
                        }))
                    }
                }
            } else if self.eat(&Token::DoubleColon) {
                // Eat a core associated constant or core associated function call.
                expr = self.parse_associated_access_expression(expr)?;
            } else if self.eat(&Token::LeftSquare) {
                // Eat an array access.
                let index = self.parse_expression()?;
                // Eat the closing bracket.
                let span = self.expect(&Token::RightSquare)?;
                expr = Expression::Access(AccessExpression::Array(ArrayAccess {
                    span: expr.span() + span,
                    array: Box::new(expr),
                    index: Box::new(index),
                    id: self.node_builder.next_id(),
                }))
            } else if self.check(&Token::LeftParen) {
                // Check that the expression is an identifier.
                if !matches!(expr, Expression::Identifier(_)) {
                    self.emit_err(ParserError::unexpected(expr.to_string(), "an identifier", expr.span()))
                }
                // Parse a function call that's by itself.
                let (arguments, _, span) = self.parse_paren_comma_list(|p| p.parse_expression().map(Some))?;
                expr = Expression::Call(CallExpression {
                    span: expr.span() + span,
                    function: Box::new(expr),
                    program: self.program_name,
                    arguments,
                    id: self.node_builder.next_id(),
                });
            }
            // Stop parsing the postfix expression unless a dot or square bracket follows.
            if !(self.check(&Token::Dot) || self.check(&Token::LeftSquare)) {
                break;
            }
        }
        Ok(expr)
    }

    /// Returns an [`Expression`] AST node if the next tokens represent
    /// a parenthesized expression or a unit expression
    /// or a tuple initialization expression or an affine group literal.
    fn parse_tuple_expression(&mut self) -> Result<Expression> {
        if let Some(gt) = self.eat_group_partial().transpose()? {
            return Ok(Expression::Literal(Literal::Group(Box::new(GroupLiteral::Tuple(gt)))));
        }

        let (mut elements, trailing, span) = self.parse_expr_tuple()?;

        match elements.len() {
            // If the tuple expression is empty, return a `UnitExpression`.
            0 => Ok(Expression::Unit(UnitExpression { span, id: self.node_builder.next_id() })),
            1 => match trailing {
                // If there is one element in the tuple but no trailing comma, e.g `(foo)`, return the element.
                false => Ok(elements.swap_remove(0)),
                // If there is one element in the tuple and a trailing comma, e.g `(foo,)`, emit an error since tuples must have at least two elements.
                true => Err(ParserError::tuple_must_have_at_least_two_elements("expression", span).into()),
            },
            // Otherwise, return a tuple expression.
            // Note: This is the only place where `TupleExpression` is constructed in the parser.
            _ => Ok(Expression::Tuple(TupleExpression { elements, span, id: self.node_builder.next_id() })),
        }
    }

    /// Returns an [`Expression`] AST node if the next tokens represent an array initialization expression.
    fn parse_array_expression(&mut self) -> Result<Expression> {
        let (elements, _, span) = self.parse_bracket_comma_list(|p| p.parse_expression().map(Some))?;

        match elements.is_empty() {
            // If the array expression is empty, return an error.
            true => Err(ParserError::array_must_have_at_least_one_element("expression", span).into()),
            // Otherwise, return an array expression.
            // Note: This is the only place where `ArrayExpression` is constructed in the parser.
            false => Ok(Expression::Array(ArrayExpression { elements, span, id: self.node_builder.next_id() })),
        }
    }

    /// Returns a reference to the next token if it is a [`GroupCoordinate`], or [None] if
    /// the next token is not a [`GroupCoordinate`].
    fn peek_group_coordinate(&self, dist: &mut usize) -> Option<GroupCoordinate> {
        let (advanced, gc) = self.look_ahead(*dist, |t0| match &t0.token {
            Token::Add => Some((1, GroupCoordinate::SignHigh)),
            Token::Sub => self.look_ahead(*dist + 1, |t1| match &t1.token {
                Token::Integer(value) => Some((2, GroupCoordinate::Number(format!("-{value}"), t1.span))),
                _ => Some((1, GroupCoordinate::SignLow)),
            }),
            Token::Underscore => Some((1, GroupCoordinate::Inferred)),
            Token::Integer(value) => Some((1, GroupCoordinate::Number(value.clone(), t0.span))),
            _ => None,
        })?;
        *dist += advanced;
        Some(gc)
    }

    /// Attempts to parse an affine group literal, if present.
    /// If absent, returns [None].
    fn eat_group_partial(&mut self) -> Option<Result<GroupTuple>> {
        assert!(self.check(&Token::LeftParen)); // `(`.

        // Peek at first group coordinate.
        let start_span = &self.token.span;
        let mut dist = 1; // 0th is `(` so 1st is first group coordinate's start.
        let first_gc = self.peek_group_coordinate(&mut dist)?;

        let check_ahead = |d, token: &_| self.look_ahead(d, |t| (&t.token == token).then_some(t.span));

        // Peek at `,`.
        check_ahead(dist, &Token::Comma)?;
        dist += 1; // Standing at `,` so advance one for next gc's start.

        // Peek at second group coordinate.
        let second_gc = self.peek_group_coordinate(&mut dist)?;

        // Peek at `)`.
        let right_paren_span = check_ahead(dist, &Token::RightParen)?;
        dist += 1; // Standing at `)` so advance one for 'group'.

        // Peek at `group`.
        let end_span = check_ahead(dist, &Token::Group)?;
        dist += 1; // Standing at `)` so advance one for 'group'.

        let gt =
            GroupTuple { span: start_span + &end_span, x: first_gc, y: second_gc, id: self.node_builder.next_id() };

        // Eat everything so that this isn't just peeking.
        for _ in 0..dist {
            self.bump();
        }

        // Ensure that the ending `)` and `group` are treated as one token `)group` as in the ABNF grammar:
        if let Err(e) = assert_no_whitespace(right_paren_span, end_span, &format!("({},{})", gt.x, gt.y), "group") {
            return Some(Err(e));
        }

        Some(Ok(gt))
    }

    fn parse_struct_member(&mut self) -> Result<StructVariableInitializer> {
        let identifier = self.expect_identifier()?;

        let (expression, span) = if self.eat(&Token::Colon) {
            // Parse individual struct variable declarations.
            let expression = self.parse_expression()?;
            let span = identifier.span + expression.span();
            (Some(expression), span)
        } else {
            (None, identifier.span)
        };

        Ok(StructVariableInitializer { identifier, expression, id: self.node_builder.next_id(), span })
    }

    /// Returns an [`Expression`] AST node if the next tokens represent a
    /// struct initialization expression.
    /// let foo = Foo { x: 1u8 };
    pub fn parse_struct_init_expression(&mut self, identifier: Identifier) -> Result<Expression> {
        let (members, _, end) =
            self.parse_list(Delimiter::Brace, Some(Token::Comma), |p| p.parse_struct_member().map(Some))?;

        Ok(Expression::Struct(StructExpression {
            span: identifier.span + end,
            name: identifier,
            members,
            id: self.node_builder.next_id(),
        }))
    }

    /// Returns an [`Expression`] AST node if the next token is a primary expression:
    /// - Literals: field, group, unsigned integer, signed integer, boolean, address, string
    /// - Aggregate type constructors: array, tuple, structs
    /// - Identifiers: variables, keywords
    ///
    /// This function only parses some of the primary expressions defined in the ABNF grammar;
    /// for the others, it parses their initial parts,
    /// leaving it to the [self.parse_postfix_expression] function to complete the parsing.
    /// For example, of the primary expression `u8::c`, this function only parses the `u8` part,
    /// leaving it to [self.parse_postfix_expression] to parse the `::c` part.
    /// So technically the expression returned by this function may not quite be
    /// an expression as defined in the ABNF grammar,
    /// but it is only a temporary expression that is combined into a larger one
    /// by [self.parse_postfix_expression], yielding an actual expression according to the grammar.
    ///
    /// Returns an expression error if the token cannot be matched.
    fn parse_primary_expression(&mut self) -> Result<Expression> {
        if let Token::LeftParen = self.token.token {
            return self.parse_tuple_expression();
        } else if let Token::LeftSquare = self.token.token {
            return self.parse_array_expression();
        }

        let SpannedToken { token, span } = self.token.clone();
        self.bump();

        Ok(match token {
            Token::Integer(value) => {
                let suffix_span = self.token.span;
                let full_span = span + suffix_span;
                let assert_no_whitespace = |x| assert_no_whitespace(span, suffix_span, &value, x);
                match self.eat_any(INT_TYPES).then_some(&self.prev_token.token) {
                    // Literal followed by `field`, e.g., `42field`.
                    Some(Token::Field) => {
                        assert_no_whitespace("field")?;
                        Expression::Literal(Literal::Field(value, full_span, self.node_builder.next_id()))
                    }
                    // Literal followed by `group`, e.g., `42group`.
                    Some(Token::Group) => {
                        assert_no_whitespace("group")?;
                        Expression::Literal(Literal::Group(Box::new(GroupLiteral::Single(
                            value,
                            full_span,
                            self.node_builder.next_id(),
                        ))))
                    }
                    // Literal followed by `scalar` e.g., `42scalar`.
                    Some(Token::Scalar) => {
                        assert_no_whitespace("scalar")?;
                        Expression::Literal(Literal::Scalar(value, full_span, self.node_builder.next_id()))
                    }
                    // Literal followed by other type suffix, e.g., `42u8`.
                    Some(suffix) => {
                        assert_no_whitespace(&suffix.to_string())?;
                        let int_ty = Self::token_to_int_type(suffix).expect("unknown int type token");
                        Expression::Literal(Literal::Integer(int_ty, value, full_span, self.node_builder.next_id()))
                    }
                    None => return Err(ParserError::implicit_values_not_allowed(value, span).into()),
                }
            }
            Token::True => Expression::Literal(Literal::Boolean(true, span, self.node_builder.next_id())),
            Token::False => Expression::Literal(Literal::Boolean(false, span, self.node_builder.next_id())),
            Token::AddressLit(address_string) => {
                if address_string.parse::<Address<N>>().is_err() {
                    self.emit_err(ParserError::invalid_address_lit(&address_string, span));
                }
                Expression::Literal(Literal::Address(address_string, span, self.node_builder.next_id()))
            }
            Token::StaticString(value) => {
                Expression::Literal(Literal::String(value, span, self.node_builder.next_id()))
            }
            Token::Identifier(name) => {
                let ident = Identifier { name, span, id: self.node_builder.next_id() };
                if !self.disallow_struct_construction && self.check(&Token::LeftCurly) {
                    // Parse struct and records inits as struct expressions.
                    // Enforce struct or record type later at type checking.
                    self.parse_struct_init_expression(ident)?
                } else {
                    Expression::Identifier(ident)
                }
            }
            Token::SelfLower => {
                Expression::Identifier(Identifier { name: sym::SelfLower, span, id: self.node_builder.next_id() })
            }
            Token::Block => {
                Expression::Identifier(Identifier { name: sym::block, span, id: self.node_builder.next_id() })
            }
            Token::Future => {
                Expression::Identifier(Identifier { name: sym::Future, span, id: self.node_builder.next_id() })
            }
            Token::Network => {
                Expression::Identifier(Identifier { name: sym::network, span, id: self.node_builder.next_id() })
            }
            t if crate::type_::TYPE_TOKENS.contains(&t) => Expression::Identifier(Identifier {
                name: t.keyword_to_symbol().unwrap(),
                span,
                id: self.node_builder.next_id(),
            }),
            token => {
                return Err(ParserError::unexpected_str(token, "expression", span).into());
            }
        })
    }
}

fn assert_no_whitespace(left_span: Span, right_span: Span, left: &str, right: &str) -> Result<()> {
    if left_span.hi != right_span.lo {
        let error_span = Span::new(left_span.hi, right_span.lo); // The span between them.
        return Err(ParserError::unexpected_whitespace(left, right, error_span).into());
    }

    Ok(())
}