swamp_parser/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/swamp
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5pub mod prelude;
6
7use pest::error::{Error, ErrorVariant, InputLocation};
8use pest::iterators::{Pair, Pairs};
9use pest::{Parser, Position};
10use pest_derive::Parser;
11use std::iter::Peekable;
12use std::str::Chars;
13use swamp_ast::Function;
14use swamp_ast::LiteralKind;
15use swamp_ast::{
16    AssignmentOperatorKind, BinaryOperatorKind, CompoundOperator, CompoundOperatorKind,
17    EnumVariantLiteral, ExpressionKind, FieldExpression, FieldName, ForPattern, ForVar,
18    ImportItems, IterableExpression, LocalConstantIdentifier,
19    LocalTypeIdentifierWithOptionalTypeVariables, Mod, NamedStructDef, PatternElement,
20    QualifiedIdentifier, RangeMode, SpanWithoutFileId, StructTypeField, TypeForParameter,
21    TypeVariable, VariableBinding, prelude::*,
22};
23use swamp_ast::{Postfix, PostfixChain};
24use tracing::error;
25
26pub struct ParseResult<'a> {
27    #[allow(dead_code)]
28    script: String, // Pairs are referencing the script
29    pairs: pest::iterators::Pairs<'a, Rule>,
30}
31
32pub struct GeneralError {
33    pub description: String,
34}
35
36#[derive(Debug)]
37pub enum SpecificError {
38    CouldNotMoveDown,
39    CouldNotMoveRight,
40    General(String),
41    ExpectingTypeIdentifier,
42    ExpectingInnerPair,
43    UnexpectedTypeRule(String),
44    ExpectedTypeIdentifier(String),
45    ExpectedLocalTypeIdentifier(String),
46    UnexpectedRuleInParseScript(String),
47    ExpectedControlStatement(String),
48    ExpectedStatement(String),
49    ExpectedIfOrElse(String),
50    MissingFunctionSignature,
51    MissingFunctionBody,
52    ExpectedStatementBlock,
53    ExpectedFunctionDefinition,
54    ExpectedParameter,
55    ExpectedImplItem,
56    ExpectedMemberSignature,
57    ExpectedBlockInWhileLoop,
58    UnexpectedExpressionType(String),
59    UnexpectedAccessType(String),
60    UnknownAssignmentOperator(String),
61    CompoundOperatorCanNotContainMut,
62    InvalidAssignmentTarget,
63    CompoundOperatorCanNotHaveMultipleVariables,
64    ExpectedExpressionAfterPrefixOperator,
65    UnknownOperator(String),
66    UnexpectedPostfixOperator,
67    UnexpectedUnaryOperator(String),
68    InvalidMemberCall,
69    UnknownMatchType,
70    UnexpectedElementInPatternList,
71    InvalidPrecisionValue,
72    InvalidPrecisionType,
73    ExpectedTypeIdentifierAfterPath,
74    UnexpectedPatternListElement(String),
75    MustHaveAtLeastOneArm,
76    UnexpectedMatchArmRule(String),
77    UnknownEnumVariant(String),
78    UnknownLiteral,
79    UnknownPrimary(String),
80    InvalidFormatSpecifier,
81    UnexpectedVariantField,
82    MutOnlyForVariables,
83    UnexpectedTokenInFunctionCall,
84    ExpectedExpressionInInterpolation,
85    UnexpectedRuleInInterpolation,
86    ExpectedForPattern,
87    ExpectedBlock,
88    InvalidForPattern,
89    UnexpectedRuleInElse(String),
90    ExpectedLocationExpression,
91    ExpectedImportPath,
92    ExpectedIdentifier,
93    ExpectedIdentifierAfterPath,
94    ExpectedFieldOrRest,
95    UnknownEscapeCharacter(char),
96    UnfinishedEscapeSequence,
97    InvalidUnicodeEscape,
98    InvalidHexEscape,
99    InvalidUtf8Sequence,
100    MissingTypeName,
101    UnknownTerm(String),
102    UnknownExpr(String),
103    UnexpectedTokenInMutableExpression,
104}
105
106#[derive(Debug)]
107pub struct ParseError {
108    pub span: SpanWithoutFileId,
109    pub specific: SpecificError,
110}
111
112#[derive(Parser)]
113#[grammar = "grammar.pest"]
114pub struct ScriptParser;
115
116pub const UNKNOWN_FILE_ID: u16 = 0xffff;
117
118pub struct AstParser;
119
120impl From<Error<Rule>> for ParseError {
121    fn from(value: Error<Rule>) -> Self {
122        let span = match value.location {
123            InputLocation::Pos(pos) => SpanWithoutFileId {
124                offset: pos as u32,
125                length: 1,
126            },
127            InputLocation::Span((start, end)) => SpanWithoutFileId {
128                offset: start as u32,
129                length: (end - start) as u16,
130            },
131        };
132        Self {
133            span,
134            specific: SpecificError::General(value.variant.to_string()),
135        }
136    }
137}
138
139impl AstParser {
140    fn next_pair<'a>(
141        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
142    ) -> Result<Pair<'a, Rule>, ParseError> {
143        Ok(pairs.next().ok_or_else(|| {
144            Error::new_from_pos(
145                ErrorVariant::CustomError {
146                    message: "Expected more tokens".into(),
147                },
148                Position::from_start(""),
149            )
150        })?)
151    }
152
153    fn expect_next<'a>(
154        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
155        expected_rule: Rule,
156    ) -> Result<Pair<'a, Rule>, ParseError> {
157        let pair = Self::next_pair(pairs)?;
158        if pair.as_rule() != expected_rule {
159            return Err(Error::new_from_span(
160                ErrorVariant::CustomError {
161                    message: format!("Expected {:?}, found {:?}", expected_rule, pair.as_rule()),
162                },
163                pair.as_span(),
164            ))?;
165        }
166        Ok(pair)
167    }
168
169    fn expect_identifier_next<'a>(
170        &self,
171        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
172    ) -> Result<LocalIdentifier, ParseError> {
173        let pair = Self::expect_next(pairs, Rule::identifier)?;
174        Ok(LocalIdentifier::new(self.to_node(&pair)))
175    }
176
177    fn expect_function_identifier_next<'a>(
178        &self,
179        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
180    ) -> Result<LocalIdentifier, ParseError> {
181        let pair = Self::expect_next(pairs, Rule::function_identifier)?;
182        Ok(LocalIdentifier::new(self.to_node(&pair)))
183    }
184
185    fn expect_constant_identifier_next<'a>(
186        &self,
187        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
188    ) -> Result<LocalConstantIdentifier, ParseError> {
189        let pair = Self::expect_next(pairs, Rule::constant_identifier)?;
190        Ok(LocalConstantIdentifier(self.to_node(&pair)))
191    }
192
193    fn _expect_variable_next<'a>(
194        &self,
195        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
196    ) -> Result<Variable, ParseError> {
197        let identifier = self.expect_identifier_next(pairs)?;
198        Ok(Variable {
199            name: identifier.0,
200            is_mutable: None,
201        })
202    }
203
204    fn expect_field_label_next<'a>(
205        &self,
206        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
207    ) -> Result<FieldName, ParseError> {
208        let field_label_pair = Self::expect_next(pairs, Rule::field_label)?;
209        let mut inner = field_label_pair.clone().into_inner();
210        let ident_pair = inner.next().ok_or_else(|| {
211            self.create_error_pair(SpecificError::ExpectedIdentifier, &field_label_pair)
212        })?;
213
214        Ok(FieldName(self.to_node(&ident_pair)))
215    }
216
217    fn parse_dot_identifier<'a>(&self, pair: &Pair<Rule>) -> Result<FieldName, ParseError> {
218        debug_assert_eq!(pair.as_rule(), Rule::dot_identifier);
219        let mut inner = pair.clone().into_inner();
220        let ident_pair = inner
221            .next()
222            .ok_or_else(|| self.create_error_pair(SpecificError::ExpectedIdentifier, &pair))?;
223
224        Ok(FieldName(self.to_node(&ident_pair)))
225    }
226
227    fn expect_local_type_identifier_next<'a>(
228        &self,
229        pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
230    ) -> Result<LocalTypeIdentifier, ParseError> {
231        let pair = Self::expect_next(pairs, Rule::type_identifier)?;
232        Ok(LocalTypeIdentifier::new(self.to_node(&pair)))
233    }
234
235    /*
236    fn expect_qualified_type_identifier_next<'a>(
237        &self,
238        inner_pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
239    ) -> Result<QualifiedTypeIdentifier, ParseError> {
240        let first = Self::next_pair(inner_pairs)?;
241        match first.as_rule() {
242            Rule::module_segments => {
243                let module_path = self.parse_module_segments(first.clone());
244                let type_id = inner_pairs.next().ok_or_else(|| {
245                    self.create_error_pair(SpecificError::ExpectedTypeIdentifierAfterPath, &first)
246                })?;
247
248                let type_identifier = self.parse_local_type_identifier(&type_id)?;
249                Ok(QualifiedTypeIdentifier::new(type_identifier, module_path))
250            }
251            Rule::type_identifier => Ok(QualifiedTypeIdentifier::new(
252                LocalTypeIdentifier(self.to_node(&first)),
253                Vec::new(),
254            )),
255            _ => Err(self.create_error_pair(
256                SpecificError::ExpectedTypeIdentifier(Self::pair_to_rule(&first)),
257                &first,
258            )),
259        }
260    }
261
262     */
263
264    fn convert_into_iterator<'a>(pair: &'a Pair<'a, Rule>) -> impl Iterator<Item = Pair<'a, Rule>> {
265        pair.clone().into_inner()
266    }
267
268    fn create_error_pair(&self, kind: SpecificError, pair: &Pair<Rule>) -> ParseError {
269        ParseError {
270            span: self.to_span(pair.as_span()),
271            specific: kind,
272        }
273    }
274
275    fn to_err(kind: SpecificError, pair: &Pair<Rule>) -> ParseError {
276        ParseError {
277            span: Self::span(pair.as_span()),
278            specific: kind,
279        }
280    }
281
282    fn next_inner_pair<'a>(&self, pair: &Pair<'a, Rule>) -> Result<Pair<'a, Rule>, ParseError> {
283        let _span = pair.as_span();
284        pair.clone()
285            .into_inner()
286            .next()
287            .ok_or_else(move || self.create_error_pair(SpecificError::ExpectingInnerPair, pair))
288    }
289
290    pub fn parse(rule: Rule, raw_script: &str) -> Result<ParseResult<'static>, ParseError> {
291        let pairs = unsafe {
292            std::mem::transmute::<pest::iterators::Pairs<'_, Rule>, pest::iterators::Pairs<'_, Rule>>(
293                ScriptParser::parse(rule, raw_script)?,
294            )
295        };
296        Ok(ParseResult {
297            script: raw_script.to_string(),
298            pairs,
299        })
300    }
301
302    pub fn parse_module(&self, raw_script: &str) -> Result<Module, ParseError> {
303        let result = Self::parse(Rule::program, raw_script)?;
304
305        let mut pairs = result.pairs;
306
307        let program_pair = Self::next_pair(&mut pairs)?;
308
309        let mut expressions = Vec::new();
310        let mut definitions = Vec::new();
311        for pair in Self::convert_into_iterator(&program_pair) {
312            match pair.as_rule() {
313                Rule::definition => {
314                    let def = self.parse_definition(&pair)?;
315                    definitions.push(def);
316                }
317                Rule::expression => {
318                    let expr = self.parse_expression(&pair)?;
319                    expressions.push(expr);
320                }
321                Rule::EOI => {} // End of Input - do nothing
322                _ => {
323                    return Err(self.create_error_pair(
324                        SpecificError::UnexpectedRuleInParseScript(Self::pair_to_rule(&pair)),
325                        &pair,
326                    ));
327                }
328            }
329        }
330
331        let maybe_expression = match expressions.len() {
332            0 => None,
333            1 => Some(expressions.into_iter().next().unwrap()),
334            _ => Some(Expression {
335                kind: ExpressionKind::Block(expressions),
336                node: Node {
337                    span: SpanWithoutFileId::default(),
338                },
339            }),
340        };
341
342        Ok(Module::new(definitions, maybe_expression))
343    }
344
345    fn parse_definition(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
346        let inner_pair = self.next_inner_pair(pair)?;
347        match inner_pair.as_rule() {
348            Rule::impl_def => self.parse_impl_def(&inner_pair),
349            Rule::const_def => self.parse_const_definition(&inner_pair),
350            Rule::struct_def => self.parse_struct_def(&inner_pair),
351            Rule::type_def => self.parse_type_def(&inner_pair),
352            Rule::function_def => self.parse_function_def(&inner_pair),
353            Rule::use_def => self.parse_use(&inner_pair),
354            Rule::mod_def => self.parse_mod(&inner_pair),
355            Rule::enum_def => self.parse_enum_def(&inner_pair),
356            _ => todo!(),
357        }
358    }
359
360    fn parse_const_definition(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
361        Ok(Definition::Constant(self.parse_const_info(pair)?))
362    }
363
364    fn parse_const_info(&self, pair: &Pair<Rule>) -> Result<ConstantInfo, ParseError> {
365        let mut inner = Self::convert_into_iterator(pair);
366        let constant_identifier = self.expect_constant_identifier_next(&mut inner)?;
367        let expr_pair = Self::next_pair(&mut inner)?;
368        let expression = self.parse_expression(&expr_pair)?;
369
370        Ok(ConstantInfo {
371            constant_identifier,
372            expression: Box::new(expression),
373        })
374    }
375
376    fn module_path_and_items(
377        &self,
378        pair: &Pair<Rule>,
379    ) -> Result<(Vec<Node>, ImportItems), ParseError> {
380        let mut inner = Self::convert_into_iterator(pair);
381        let import_path = Self::next_pair(&mut inner)?;
382
383        let mut segments = Vec::new();
384        for pair in import_path.into_inner() {
385            segments.push(self.to_node(&pair));
386        }
387
388        let items = match inner.next() {
389            Some(found_rule) => match found_rule.as_rule() {
390                Rule::all_imports => ImportItems::All,
391                Rule::import_list => {
392                    let mut imported_items = Vec::new();
393                    for list_item in found_rule.into_inner() {
394                        let item = Self::next_pair(&mut list_item.into_inner())?;
395
396                        let import_item = match item.as_rule() {
397                            Rule::identifier => {
398                                ImportItem::Identifier(LocalIdentifier::new(self.to_node(&item)))
399                            }
400                            Rule::type_identifier => {
401                                ImportItem::Type(LocalTypeIdentifier::new(self.to_node(&item)))
402                            }
403                            _ => {
404                                return Err(self
405                                    .create_error_pair(SpecificError::ExpectedIdentifier, &item));
406                            }
407                        };
408
409                        imported_items.push(import_item);
410                    }
411                    if imported_items.is_empty() {
412                        ImportItems::Nothing
413                    } else {
414                        ImportItems::Items(imported_items)
415                    }
416                }
417                _ => panic!("was not all_imports or import_list"),
418            },
419            None => ImportItems::Nothing,
420        };
421
422        Ok((segments, items))
423    }
424
425    fn parse_use(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
426        let (segments, items) = self.module_path_and_items(&pair)?;
427
428        Ok(Definition::Use(Use {
429            module_path: ModulePath(segments),
430            items,
431        }))
432    }
433
434    fn parse_mod(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
435        let (segments, items) = self.module_path_and_items(&pair)?;
436
437        Ok(Definition::Mod(Mod {
438            module_path: ModulePath(segments),
439            items,
440        }))
441    }
442
443    fn pair_to_rule(rule: &Pair<Rule>) -> String {
444        format!("{:?}", rule.as_rule())
445    }
446
447    fn parse_block(&self, block_pair: &Pair<Rule>) -> Result<Expression, ParseError> {
448        if block_pair.as_rule() != Rule::block {
449            return Err(self.create_error_pair(SpecificError::ExpectedBlock, block_pair));
450        }
451
452        let mut expressions = Vec::new();
453
454        for pair in Self::convert_into_iterator(block_pair) {
455            if pair.as_rule() != Rule::expression {
456                return Err(self.create_error_pair(
457                    SpecificError::UnexpectedRuleInParseScript(format!(
458                        "Expected expression_in_block, got: {:?}",
459                        pair.as_rule()
460                    )),
461                    block_pair,
462                ));
463            }
464
465            match pair.as_rule() {
466                Rule::expression => {
467                    let expr = self.parse_expression(&pair)?;
468                    expressions.push(expr);
469                }
470                _ => {
471                    return Err(self.create_error_pair(
472                        SpecificError::UnexpectedRuleInParseScript(format!(
473                            "Unexpected rule in parse_block: {:?}",
474                            pair.as_rule()
475                        )),
476                        &pair,
477                    ));
478                }
479            }
480        }
481
482        let block_expr = self.create_expr(ExpressionKind::Block(expressions), block_pair);
483        Ok(block_expr)
484    }
485
486    fn parse_with_expr(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
487        let mut inner = Self::convert_into_iterator(pair);
488        let binding_list_pair = inner.next().expect("variable list missing");
489        let binding_list = self.parse_variable_binding_list(&binding_list_pair)?;
490
491        let expr_pair = inner.next().expect("block missing");
492        let expr = self.parse_expression(&expr_pair)?;
493
494        let with_expr = self.create_expr(ExpressionKind::With(binding_list, Box::from(expr)), pair);
495        Ok(with_expr)
496    }
497
498    fn parse_when_expr(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
499        let mut inner = Self::convert_into_iterator(pair);
500        let binding_list =
501            self.parse_variable_binding_list(&inner.next().expect("variable list missing"))?;
502        let expr = self.parse_expression(&inner.next().expect("block missing"))?;
503
504        let next = inner.next();
505        let else_expr = if let Some(found_else) = next {
506            Some(Box::new(self.parse_expression(&found_else)?))
507        } else {
508            None
509        };
510
511        Ok(self.create_expr(
512            ExpressionKind::When(binding_list, Box::from(expr), else_expr),
513            pair,
514        ))
515    }
516
517    fn parse_when_variable_binding(
518        &self,
519        pair: &Pair<Rule>,
520    ) -> Result<VariableBinding, ParseError> {
521        let mut inner = Self::convert_into_iterator(pair);
522
523        let variable = self.parse_variable_item(&inner.next().expect("variable missing"))?;
524
525        let expression = match inner.next() {
526            Some(expr_pair) => Some(self.parse_arg_expression(&expr_pair)?),
527            _ => None,
528        };
529
530        Ok(VariableBinding {
531            variable,
532            expression,
533        })
534    }
535
536    fn parse_variable_binding_list(
537        &self,
538        pair: &Pair<Rule>,
539    ) -> Result<Vec<VariableBinding>, ParseError> {
540        let inner = Self::convert_into_iterator(pair);
541        let mut bindings = Vec::new();
542
543        // Each item in inner will be a variable_binding
544        for binding_pair in inner {
545            if binding_pair.as_rule() == Rule::variable_binding {
546                bindings.push(self.parse_when_variable_binding(&binding_pair)?);
547            }
548        }
549
550        Ok(bindings)
551    }
552    fn parse_if_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
553        let mut inner = Self::convert_into_iterator(pair);
554        let condition = self.parse_expression(&Self::next_pair(&mut inner)?)?;
555        let then_branch = self.parse_expression(&Self::next_pair(&mut inner)?)?;
556        let else_branch = inner
557            .next()
558            .map(|p| {
559                match p.as_rule() {
560                    Rule::if_expr => self.parse_if_expression(&p), // Recursively handle `else if`
561                    _ => self.parse_expression(&p),                // Inline or block `else`
562                }
563            })
564            .transpose()?;
565
566        Ok(self.create_expr(
567            ExpressionKind::If(
568                Box::new(condition),
569                Box::new(then_branch),
570                else_branch.map(Box::new),
571            ),
572            pair,
573        ))
574    }
575
576    #[allow(clippy::too_many_lines)]
577    fn parse_postfix_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
578        assert_eq!(pair.as_rule(), Rule::postfix);
579        let mut inner = pair.clone().into_inner();
580
581        let primary_pair = inner.next().ok_or_else(|| {
582            self.create_error_pair(SpecificError::UnexpectedPostfixOperator, pair)
583        })?;
584        let start_expr = self.parse_term(&primary_pair)?;
585        //info!(?start_expr, "start");
586        let mut postfixes = Vec::new();
587        if inner.len() == 0 {
588            return Ok(start_expr);
589        }
590
591        for op_pair in inner.clone() {
592            //info!(rule=?op_pair.as_rule(), "..continuing chain");
593            match op_pair.as_rule() {
594                Rule::postfix_op => {
595                    let mut sub_inner = op_pair.clone().into_inner();
596                    let child = sub_inner.next().ok_or_else(|| {
597                        self.create_error_pair(SpecificError::UnexpectedPostfixOperator, &op_pair)
598                    })?;
599
600                    match child.as_rule() {
601                        Rule::unwrap_postfix => {
602                            postfixes
603                                .push(Postfix::OptionalChainingOperator(self.to_node(&op_pair)));
604                        }
605
606                        Rule::none_coalesce_postfix => {
607                            let mut postfix_inner = Self::convert_into_iterator(&child);
608                            let expr_pair = postfix_inner.next().expect("must have following");
609                            let default_expression = self.parse_expression(&expr_pair)?;
610                            postfixes.push(Postfix::NoneCoalescingOperator(default_expression));
611                        }
612
613                        Rule::function_call_postfix => {
614                            let (maybe_generics, args) =
615                                self.parse_function_call_postfix(&child)?;
616                            let node = self.to_node(&op_pair);
617                            postfixes.push(Postfix::FunctionCall(node, maybe_generics, args));
618                        }
619
620                        Rule::member_call_postfix => {
621                            let (member_identifier, maybe_generics, args) =
622                                self.parse_member_call_postfix(&child)?;
623
624                            postfixes.push(Postfix::MemberCall(
625                                member_identifier.0,
626                                maybe_generics,
627                                args,
628                            ));
629                        }
630
631                        Rule::member_access_postfix => {
632                            let mut inner = child.into_inner();
633                            let dot_id = Self::next_pair(&mut inner)?;
634                            let identifier = self.parse_dot_identifier(&dot_id)?;
635                            postfixes.push(Postfix::FieldAccess(identifier.0));
636                        }
637
638                        Rule::subscript_postfix => {
639                            let mut arr_inner = child.clone().into_inner();
640                            let index_pair = arr_inner.next().ok_or_else(|| {
641                                self.create_error_pair(
642                                    SpecificError::UnexpectedPostfixOperator,
643                                    &child,
644                                )
645                            })?;
646                            let index_expr = self.parse_expression(&index_pair)?;
647                            postfixes.push(Postfix::Subscript(index_expr));
648                        }
649
650                        _ => {
651                            return Err(self.create_error_pair(
652                                SpecificError::UnexpectedPostfixOperator,
653                                &child,
654                            ));
655                        }
656                    }
657                }
658                _ => {
659                    return Err(
660                        self.create_error_pair(SpecificError::UnexpectedPostfixOperator, &op_pair)
661                    );
662                }
663            }
664        }
665
666        Ok(self.create_expr(
667            ExpressionKind::PostfixChain(PostfixChain {
668                base: Box::from(start_expr),
669                postfixes: postfixes,
670            }),
671            pair,
672        ))
673    }
674
675    fn parse_member_call_postfix(
676        &self,
677        pair: &Pair<Rule>,
678    ) -> Result<(FieldName, Option<Vec<Type>>, Vec<Expression>), ParseError> {
679        debug_assert_eq!(pair.as_rule(), Rule::member_call_postfix);
680
681        let mut inner = pair.clone().into_inner();
682
683        let member_access = Self::next_pair(&mut inner)?;
684        debug_assert_eq!(member_access.as_rule(), Rule::member_access_postfix);
685        let mut ma_inner = member_access.into_inner();
686        let dot_id = Self::next_pair(&mut ma_inner)?;
687        let member_identifier = self.parse_dot_identifier(&dot_id)?;
688
689        let mut generic_args: Option<Vec<Type>> = None;
690        // Peek at the next rule without consuming it
691        if let Some(peeked_pair) = inner.peek() {
692            if peeked_pair.as_rule() == Rule::generic_arguments {
693                let generic_args_pair = Self::next_pair(&mut inner)?;
694                generic_args = Some(self.parse_generic_arguments(&generic_args_pair)?);
695            }
696        } else {
697            panic!("shouldn't happen in member_call_postfix")
698        }
699
700        let args_pair = Self::next_pair(&mut inner)?;
701        let args = self.parse_function_call_arguments(&args_pair)?;
702
703        Ok((member_identifier, generic_args, args))
704    }
705
706    fn parse_type_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
707        let mut inner = Self::convert_into_iterator(pair);
708        let alias_name = self.expect_local_type_identifier_next(&mut inner)?;
709        let referenced_type = self.parse_type(inner.next().expect("should work"))?;
710
711        let alias_type = AliasType {
712            identifier: alias_name,
713            referenced_type,
714        };
715
716        Ok(Definition::AliasDef(alias_type))
717    }
718
719    fn parse_struct_type_field(&self, pair: &Pair<Rule>) -> Result<StructTypeField, ParseError> {
720        debug_assert_eq!(pair.as_rule(), Rule::struct_type_field);
721
722        let mut field_inner = Self::convert_into_iterator(&pair);
723        let field_name = self.expect_field_label_next(&mut field_inner)?;
724        let field_type = self.parse_type(Self::next_pair(&mut field_inner)?)?;
725        let struct_type_field = StructTypeField {
726            field_name,
727            field_type,
728        };
729
730        Ok(struct_type_field)
731    }
732
733    fn parse_struct_type_fields(
734        &self,
735        pair: &Pair<Rule>,
736    ) -> Result<Vec<StructTypeField>, ParseError> {
737        debug_assert_eq!(pair.as_rule(), Rule::struct_type_fields);
738        let mut fields = Vec::new();
739        for field_def in Self::convert_into_iterator(pair) {
740            let anonymous_struct_field = self.parse_struct_type_field(&field_def)?;
741
742            fields.push(anonymous_struct_field);
743        }
744        Ok(fields)
745    }
746
747    fn parse_struct_type(&self, pair: &Pair<Rule>) -> Result<AnonymousStructType, ParseError> {
748        debug_assert_eq!(pair.as_rule(), Rule::struct_type);
749        let fields = Self::right_alternative(pair)?;
750        let fields = self.parse_struct_type_fields(&fields)?;
751        let struct_type = AnonymousStructType::new(fields);
752        Ok(struct_type)
753    }
754
755    fn parse_tuple_type_elements(&self, pair: &Pair<Rule>) -> Result<Vec<Type>, ParseError> {
756        debug_assert_eq!(pair.as_rule(), Rule::tuple_type);
757        let mut types = Vec::new();
758        for type_pair in pair.clone().into_inner() {
759            let type_value = self.parse_type(type_pair)?;
760            types.push(type_value);
761        }
762        Ok(types)
763    }
764
765    fn parse_struct_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
766        let mut inner = Self::convert_into_iterator(pair).peekable();
767
768        let name_with_optional_type_params =
769            self.parse_local_type_identifier_with_optional_type_variables(&inner.next().unwrap())?;
770
771        // struct_type is optional
772        // it is valid syntax to just do:
773        // `struct SomeStruct`
774        let struct_type_pair_option = inner.next();
775        let struct_type_result = match struct_type_pair_option {
776            Some(struct_type_pair) => Some(self.parse_struct_type(&struct_type_pair)?),
777            None => None,
778        };
779
780        let struct_type = struct_type_result.map_or_else(
781            || AnonymousStructType::new(vec![]),
782            |found_result| found_result,
783        );
784
785        Ok(Definition::NamedStructDef(NamedStructDef {
786            identifier: name_with_optional_type_params,
787            struct_type,
788        }))
789    }
790
791    fn parse_function_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
792        let function_pair = self.next_inner_pair(pair)?;
793
794        match function_pair.as_rule() {
795            Rule::normal_function => {
796                let mut inner = function_pair.clone().into_inner();
797                let signature_pair = inner.next().ok_or_else(|| {
798                    self.create_error_pair(SpecificError::MissingFunctionSignature, &function_pair)
799                })?;
800
801                let signature = self.parse_function_signature(&signature_pair)?;
802
803                let body = self.parse_block(&inner.next().ok_or_else(|| {
804                    self.create_error_pair(SpecificError::MissingFunctionBody, &function_pair)
805                })?)?;
806
807                Ok(Definition::FunctionDef(Function::Internal(
808                    FunctionWithBody {
809                        declaration: signature,
810                        body,
811                    },
812                )))
813            }
814            Rule::external_function => {
815                let signature_pair =
816                    function_pair.clone().into_inner().next().ok_or_else(|| {
817                        self.create_error_pair(
818                            SpecificError::MissingFunctionSignature,
819                            &function_pair,
820                        )
821                    })?;
822
823                let signature = self.parse_function_signature(&signature_pair)?;
824                Ok(Definition::FunctionDef(Function::External(signature)))
825            }
826            _ => {
827                Err(self
828                    .create_error_pair(SpecificError::ExpectedFunctionDefinition, &function_pair))
829            }
830        }
831    }
832    fn parse_function_signature(
833        &self,
834        pair: &Pair<Rule>,
835    ) -> Result<FunctionDeclaration, ParseError> {
836        if pair.as_rule() != Rule::function_signature {
837            return Err(self.create_error_pair(SpecificError::MissingFunctionSignature, pair));
838        }
839
840        let mut inner = pair.clone().into_inner();
841
842        let function_name = self.expect_function_identifier_next(&mut inner)?;
843
844        let mut generic_types = Vec::new();
845
846        let mut maybe_next_token = inner.next();
847        if let Some(next_rule) = &maybe_next_token {
848            if next_rule.as_rule() == Rule::generic_type_variables {
849                generic_types = self.parse_generic_type_variables(next_rule)?;
850                maybe_next_token = inner.next();
851            }
852        }
853
854        let (parameters, return_type) = match maybe_next_token {
855            Some(token) if token.as_rule() == Rule::parameter_list => {
856                let params = self.parse_parameters(&token)?;
857
858                let ret_type = if let Some(return_type_pair) = inner.next() {
859                    Some(self.parse_return_type(&return_type_pair)?)
860                } else {
861                    None
862                };
863
864                (params, ret_type)
865            }
866
867            Some(token) if token.as_rule() == Rule::return_type => {
868                (Vec::new(), Some(self.parse_return_type(&token)?))
869            }
870            _ => (Vec::new(), None),
871        };
872
873        Ok(FunctionDeclaration {
874            name: function_name.0,
875            params: parameters,
876            self_parameter: None,
877            generic_variables: generic_types,
878            return_type,
879        })
880    }
881
882    fn parse_return_type(&self, pair: &Pair<Rule>) -> Result<Type, ParseError> {
883        let inner_pair = self.next_inner_pair(pair)?;
884        self.parse_type(inner_pair)
885    }
886
887    pub fn parse_parameters(&self, pair: &Pair<Rule>) -> Result<Vec<Parameter>, ParseError> {
888        let mut parameters = Vec::new();
889
890        for param_pair in Self::convert_into_iterator(pair) {
891            match param_pair.as_rule() {
892                Rule::parameter => {
893                    let mut iterator = Self::convert_into_iterator(&param_pair);
894                    let may_mut_pair = iterator.next().unwrap();
895                    let var = self.parse_maybe_mut_identifier(&may_mut_pair)?;
896                    let type_pair = iterator.next().unwrap();
897                    let param_type = self.parse_type(type_pair.clone())?;
898
899                    parameters.push(Parameter {
900                        variable: var,
901                        param_type,
902                    });
903                }
904                Rule::self_parameter => {
905                    panic!("should have been handled before parsing parameters")
906                }
907                _ => {
908                    return Err(
909                        self.create_error_pair(SpecificError::ExpectedParameter, &param_pair)
910                    );
911                }
912            }
913        }
914
915        Ok(parameters)
916    }
917
918    fn parse_impl_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
919        let mut inner = Self::convert_into_iterator(pair);
920        let name_with_optional_type_params =
921            self.parse_local_type_identifier_with_optional_type_variables(&inner.next().unwrap())?;
922
923        let mut functions = Vec::new();
924
925        for item_pair in inner {
926            if item_pair.as_rule() == Rule::impl_item {
927                let inner_item = self.next_inner_pair(&item_pair)?;
928                match inner_item.as_rule() {
929                    Rule::external_member_function => {
930                        let inner_inner_item = self.next_inner_pair(&inner_item)?;
931                        let signature = self.parse_member_signature(&inner_inner_item)?;
932                        functions.push(Function::External(signature));
933                    }
934                    Rule::normal_member_function => {
935                        let function_data = self.parse_member_data(&inner_item)?;
936                        functions.push(Function::Internal(function_data));
937                    }
938                    _ => {
939                        return Err(
940                            self.create_error_pair(SpecificError::ExpectedImplItem, &inner_item)
941                        );
942                    }
943                }
944            }
945        }
946
947        Ok(Definition::ImplDef(
948            name_with_optional_type_params,
949            functions,
950        ))
951    }
952
953    fn parse_member_signature(&self, pair: &Pair<Rule>) -> Result<FunctionDeclaration, ParseError> {
954        debug_assert_eq!(pair.as_rule(), Rule::member_signature);
955
956        let mut inner = pair.clone().into_inner();
957
958        let name = self.expect_function_identifier_next(&mut inner)?;
959
960        let mut generic_type_variables = Vec::new();
961        let maybe_next_token = inner.peek();
962        if let Some(next_rule) = &maybe_next_token {
963            if next_rule.as_rule() == Rule::generic_type_variables {
964                generic_type_variables = self.parse_generic_type_variables(next_rule)?;
965                let _ = inner.next();
966            }
967        }
968
969        let mut parameters = Vec::new();
970        let mut self_parameter = None;
971        let mut return_type = None;
972
973        for next_pair in inner {
974            match next_pair.as_rule() {
975                Rule::self_parameter => {
976                    let mut mut_keyword_node = None;
977                    let mut self_node = None;
978
979                    for pair in next_pair.into_inner() {
980                        match pair.as_rule() {
981                            Rule::mut_keyword => {
982                                mut_keyword_node = Some(self.to_node(&pair));
983                            }
984                            Rule::self_identifier => {
985                                self_node = Some(self.to_node(&pair));
986                            }
987                            _ => unreachable!("Unexpected rule in self_parameter"),
988                        }
989                    }
990
991                    self_parameter = Some(SelfParameter {
992                        is_mutable: mut_keyword_node,
993                        self_node: self_node.expect("self node must exist"),
994                    });
995                }
996                Rule::parameter_list => {
997                    parameters = self.parse_parameters(&next_pair)?;
998                }
999                Rule::return_type => {
1000                    return_type = Some(self.parse_return_type(&next_pair)?);
1001                }
1002                _ => {}
1003            }
1004        }
1005
1006        Ok(FunctionDeclaration {
1007            name: name.0,
1008            params: parameters,
1009            self_parameter,
1010            return_type,
1011            generic_variables: generic_type_variables,
1012        })
1013    }
1014
1015    fn parse_member_data(&self, pair: &Pair<Rule>) -> Result<FunctionWithBody, ParseError> {
1016        if pair.as_rule() != Rule::normal_member_function {
1017            return Err(self.create_error_pair(SpecificError::ExpectedMemberSignature, pair));
1018        }
1019
1020        let mut inner = Self::convert_into_iterator(pair);
1021
1022        let signature_pair = Self::next_pair(&mut inner)?;
1023        let signature = self.parse_member_signature(&signature_pair)?;
1024
1025        let block_pair = Self::next_pair(&mut inner)?;
1026        let body = self.parse_block(&block_pair)?;
1027
1028        Ok(FunctionWithBody {
1029            declaration: signature,
1030            body,
1031        })
1032    }
1033
1034    fn parse_for_loop(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1035        let mut inner = Self::convert_into_iterator(pair);
1036
1037        let pattern_pair = Self::next_pair(&mut inner)?;
1038        if pattern_pair.as_rule() != Rule::for_pattern {
1039            return Err(self.create_error_pair(SpecificError::ExpectedForPattern, &pattern_pair));
1040        }
1041
1042        let inner_pattern = self.next_inner_pair(&pattern_pair)?;
1043        let pattern = match inner_pattern.as_rule() {
1044            Rule::maybe_mut_identifier => {
1045                let mut inner_iter = inner_pattern.clone().into_inner();
1046                let is_mutable = inner_iter
1047                    .peek()
1048                    .map_or(false, |p| p.as_rule() == Rule::mut_keyword);
1049
1050                let is_mut = if is_mutable {
1051                    let mut_node = self.to_node(&inner_iter.next().unwrap());
1052                    Some(mut_node)
1053                } else {
1054                    None
1055                };
1056
1057                let identifier = if is_mutable {
1058                    self.expect_identifier_next(&mut inner_iter)?.0
1059                } else {
1060                    self.to_node(&inner_pattern)
1061                };
1062
1063                ForPattern::Single(ForVar { identifier, is_mut })
1064            }
1065            Rule::for_pair => {
1066                let mut vars = Self::convert_into_iterator(&inner_pattern);
1067
1068                // Parse first variable in the pair
1069                let first_var_pair = Self::next_pair(&mut vars)?;
1070                let mut first_inner_iter = first_var_pair.clone().into_inner();
1071                let first_is_mut = if first_inner_iter
1072                    .peek()
1073                    .map_or(false, |p| p.as_rule() == Rule::mut_keyword)
1074                {
1075                    Some(self.to_node(&first_inner_iter.next().unwrap()))
1076                } else {
1077                    None
1078                };
1079
1080                let first_identifier = if first_is_mut.is_some() {
1081                    self.expect_identifier_next(&mut first_inner_iter)?.0
1082                } else {
1083                    self.to_node(&first_var_pair)
1084                };
1085
1086                // Parse second variable in the pair
1087                let second_var_pair = Self::next_pair(&mut vars)?;
1088                let mut second_inner_iter = second_var_pair.clone().into_inner();
1089                let second_is_mut = if second_inner_iter
1090                    .peek()
1091                    .map_or(false, |p| p.as_rule() == Rule::mut_keyword)
1092                {
1093                    Some(self.to_node(&second_inner_iter.next().unwrap()))
1094                } else {
1095                    None
1096                };
1097
1098                let second_identifier = if second_is_mut.is_some() {
1099                    self.expect_identifier_next(&mut second_inner_iter)?.0
1100                } else {
1101                    self.to_node(&second_var_pair)
1102                };
1103
1104                ForPattern::Pair(
1105                    ForVar {
1106                        identifier: first_identifier,
1107                        is_mut: first_is_mut,
1108                    },
1109                    ForVar {
1110                        identifier: second_identifier,
1111                        is_mut: second_is_mut,
1112                    },
1113                )
1114            }
1115            _ => {
1116                return Err(
1117                    self.create_error_pair(SpecificError::InvalidForPattern, &inner_pattern)
1118                );
1119            }
1120        };
1121
1122        let next_pair = Self::next_pair(&mut inner)?;
1123        let iterable_expression = self.parse_arg_expression(&next_pair)?;
1124
1125        let mut_expression = IterableExpression {
1126            expression: Box::new(iterable_expression),
1127        };
1128
1129        let body = self.parse_expression(&Self::next_pair(&mut inner)?)?;
1130
1131        // Return the ForLoop statement with MutExpression
1132        Ok(self.create_expr(
1133            ExpressionKind::ForLoop(pattern, mut_expression, None, Box::from(body)),
1134            pair,
1135        ))
1136    }
1137
1138    fn parse_while_loop(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1139        let mut inner = Self::convert_into_iterator(pair);
1140
1141        let condition = self.parse_expression(&Self::next_pair(&mut inner)?)?;
1142
1143        let body = self.parse_expression(&Self::next_pair(&mut inner)?)?;
1144
1145        Ok(self.create_expr(
1146            ExpressionKind::WhileLoop(Box::from(condition), Box::from(body)),
1147            pair,
1148        ))
1149    }
1150
1151    fn parse_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1152        let sub = &Self::right_alternative(pair)?;
1153        match sub.as_rule() {
1154            /*
1155            // TODO: verify that this block is not needed
1156            Rule::expression => {
1157                let inner = self.next_inner_pair(sub)?;
1158
1159                self.parse_expression(&inner)
1160            }
1161             */
1162            Rule::qualified_identifier => Ok(self.create_expr(
1163                ExpressionKind::VariableReference(Variable::new(self.to_node(sub), None)),
1164                sub,
1165            )),
1166            Rule::block => self.parse_block(sub),
1167
1168            Rule::assignment => self.parse_assignment_expression(sub),
1169            Rule::destructuring_assignment => self.parse_destructuring_assignment(sub),
1170            Rule::variable_definition => self.parse_variable_definition(sub),
1171
1172            Rule::addition => self.parse_addition(sub),
1173            Rule::range => self.parse_range(sub),
1174            Rule::logical => self.parse_logical(sub),
1175            Rule::comparison => self.parse_comparison(sub),
1176            Rule::multiplication => self.parse_multiplication(sub),
1177
1178            Rule::prefix => self.parse_prefix(sub),
1179
1180            Rule::match_expr => self.parse_match_expr(sub),
1181            Rule::map_literal => self.parse_map_literal(sub),
1182            Rule::array_literal => self.parse_array_literal(sub),
1183            Rule::guard_expr => self.parse_guard_expr_list(sub),
1184            Rule::with_expr => self.parse_with_expr(sub),
1185            Rule::when_expr => self.parse_when_expr(sub),
1186            Rule::if_expr => self.parse_if_expression(sub),
1187            Rule::for_loop => self.parse_for_loop(sub),
1188            Rule::while_loop => self.parse_while_loop(sub),
1189
1190            //            Rule::expression | Rule::literal => self.parse_expr(pair),
1191            Rule::prefix_op | Rule::op_neg | Rule::op_not | Rule::op_borrow_mut_ref => {
1192                // TODO: maybe not called?
1193                let op = self.parse_unary_operator(sub)?;
1194                let expr = self.parse_postfix_expression(&self.next_inner_pair(sub)?)?;
1195                Ok(self.create_expr(ExpressionKind::UnaryOp(op, Box::new(expr)), sub))
1196            }
1197
1198            //Rule::mut_expression => self.parse_mutable_or_immutable_expression(pair),
1199            Rule::postfix => self.parse_postfix_expression(sub), // TODO: maybe not called
1200            _ => Err(self.create_error_pair(
1201                SpecificError::UnexpectedExpressionType(Self::pair_to_rule(sub)),
1202                sub,
1203            )),
1204        }
1205    }
1206
1207    fn parse_at_least_two_variable_list(
1208        &self,
1209        pair: &Pair<Rule>,
1210    ) -> Result<Vec<Variable>, ParseError> {
1211        debug_assert_eq!(pair.as_rule(), Rule::at_least_two_variables_list);
1212        let mut variables = Vec::new();
1213        for item_pair in pair.clone().into_inner() {
1214            variables.push(self.parse_variable_item(&item_pair)?);
1215        }
1216        Ok(variables)
1217    }
1218
1219    fn parse_optional_variable_list(&self, pair: &Pair<Rule>) -> Result<Vec<Variable>, ParseError> {
1220        debug_assert_eq!(pair.as_rule(), Rule::optional_variable_list);
1221        let mut variables = Vec::new();
1222        for item_pair in pair.clone().into_inner() {
1223            variables.push(self.parse_variable_item(&item_pair)?);
1224        }
1225        Ok(variables)
1226    }
1227
1228    fn parse_maybe_mut_identifier(&self, pair: &Pair<Rule>) -> Result<Variable, ParseError> {
1229        debug_assert_eq!(pair.as_rule(), Rule::maybe_mut_identifier);
1230        let mut inner = pair.clone().into_inner();
1231        let mut_node = if let Some(peeked) = inner.peek() {
1232            if peeked.as_rule() == Rule::mut_keyword {
1233                // Convert 'mut' to a Node
1234                let node = self.to_node(&peeked);
1235                inner.next(); // consume the 'mut' token
1236                Some(node)
1237            } else {
1238                None
1239            }
1240        } else {
1241            None
1242        };
1243
1244        let name_pair = inner.next().ok_or_else(|| {
1245            self.create_error_pair(
1246                SpecificError::UnexpectedRuleInParseScript(
1247                    "Expected identifier in variable_item".into(),
1248                ),
1249                pair,
1250            )
1251        })?;
1252
1253        if name_pair.as_rule() != Rule::identifier {
1254            return Err(self.create_error_pair(
1255                SpecificError::UnexpectedRuleInParseScript(format!(
1256                    "Expected identifier, found {:?}",
1257                    name_pair.as_rule()
1258                )),
1259                &name_pair,
1260            ));
1261        }
1262
1263        let variable = Variable {
1264            name: self.to_node(&name_pair),
1265            is_mutable: mut_node,
1266        };
1267
1268        Ok(variable)
1269    }
1270
1271    fn parse_variable_item(&self, pair: &Pair<Rule>) -> Result<Variable, ParseError> {
1272        debug_assert_eq!(pair.as_rule(), Rule::variable_item);
1273        let mut inner = pair.clone().into_inner();
1274        self.parse_maybe_mut_identifier(&inner.next().unwrap())
1275    }
1276
1277    fn parse_assignment_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1278        let mut iterator = pair.clone().into_inner();
1279        let lhs_logical =
1280            self.parse_logical(&iterator.next().expect("parse_assignment_expression"))?;
1281        if let Some(assignment_op_pair) = iterator.peek().clone() {
1282            iterator.next();
1283            let assignment_op = self.parse_assignment_op(&assignment_op_pair)?;
1284            let rhs_expr = self.parse_expression(&iterator.next().unwrap())?;
1285            let kind = match assignment_op {
1286                AssignmentOperatorKind::Assign => {
1287                    ExpressionKind::Assignment(Box::new(lhs_logical), Box::from(rhs_expr))
1288                }
1289                AssignmentOperatorKind::Compound(compound) => {
1290                    let op = CompoundOperator {
1291                        node: Self::node_ex(&assignment_op_pair),
1292                        kind: compound,
1293                    };
1294                    ExpressionKind::CompoundAssignment(
1295                        Box::from(lhs_logical),
1296                        op,
1297                        Box::from(rhs_expr),
1298                    )
1299                }
1300            };
1301
1302            Ok(self.create_expr(kind, &pair))
1303        } else {
1304            Ok(lhs_logical)
1305        }
1306    }
1307
1308    fn parse_assignment_op(&self, pair: &Pair<Rule>) -> Result<AssignmentOperatorKind, ParseError> {
1309        debug_assert_eq!(pair.as_rule(), Rule::assign_op);
1310        let sub = Self::right_alternative(pair)?;
1311        let op = match sub.as_rule() {
1312            Rule::compound_assign_op => {
1313                AssignmentOperatorKind::Compound(Self::parse_compound_assign_op(&sub)?)
1314            }
1315            Rule::normal_assign_op => AssignmentOperatorKind::Assign,
1316            _ => {
1317                return Err(Self::to_err(
1318                    SpecificError::UnknownAssignmentOperator("strange".to_string()),
1319                    &sub,
1320                ));
1321            }
1322        };
1323
1324        Ok(op)
1325    }
1326
1327    #[allow(clippy::too_many_lines)]
1328    fn parse_destructuring_assignment(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1329        debug_assert_eq!(pair.as_rule(), Rule::destructuring_assignment);
1330        let mut inner = pair.clone().into_inner();
1331
1332        let var_list_pair = inner.next().ok_or_else(|| {
1333            self.create_error_pair(
1334                SpecificError::UnexpectedRuleInParseScript("missing variable_list".to_string()),
1335                pair,
1336            )
1337        })?;
1338
1339        let variables = self.parse_at_least_two_variable_list(&var_list_pair)?;
1340
1341        let rhs_pair = inner.next().ok_or_else(|| {
1342            self.create_error_pair(
1343                SpecificError::UnexpectedRuleInParseScript("missing RHS expression".to_string()),
1344                pair,
1345            )
1346        })?;
1347        let rhs_expr = self.parse_expression(&rhs_pair)?;
1348
1349        Ok(self.create_expr(
1350            ExpressionKind::DestructuringAssignment(variables, Box::new(rhs_expr)),
1351            &rhs_pair,
1352        ))
1353    }
1354
1355    fn right_alternative<'a>(pair: &Pair<'a, Rule>) -> Result<Pair<'a, Rule>, ParseError> {
1356        pair.clone()
1357            .into_inner()
1358            .next()
1359            .ok_or_else(|| Self::to_err(SpecificError::CouldNotMoveRight, &pair))
1360    }
1361
1362    pub fn parse_compound_assign_op(
1363        op_pair: &Pair<Rule>,
1364    ) -> Result<CompoundOperatorKind, ParseError> {
1365        debug_assert_eq!(op_pair.as_rule(), Rule::compound_assign_op);
1366
1367        let kind = match Self::right_alternative(&op_pair)?.as_rule() {
1368            Rule::add_assign_op => CompoundOperatorKind::Add,
1369            Rule::sub_assign_op => CompoundOperatorKind::Sub,
1370            Rule::mul_assign_op => CompoundOperatorKind::Mul,
1371            Rule::div_assign_op => CompoundOperatorKind::Div,
1372            Rule::modulo_assign_op => CompoundOperatorKind::Modulo,
1373            _ => {
1374                return Err(Self::to_err(
1375                    SpecificError::UnknownOperator(format!(
1376                        "Found unexpected operator rule: {:?}",
1377                        op_pair.as_rule()
1378                    )),
1379                    &op_pair,
1380                ));
1381            }
1382        };
1383
1384        Ok(kind)
1385    }
1386
1387    #[allow(clippy::too_many_lines)]
1388    fn parse_variable_definition(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1389        debug_assert_eq!(pair.as_rule(), Rule::variable_definition);
1390        let mut inner = pair.clone().into_inner();
1391        let variable_item = Self::next_pair(&mut inner)?;
1392        let found_var = self.parse_variable_item(&variable_item)?;
1393
1394        let maybe_annotation = if let Some(peeked) = inner.peek() {
1395            if peeked.as_rule() == Rule::type_coerce {
1396                let type_coerce_pair = inner.next().unwrap();
1397                let mut type_inner = type_coerce_pair.clone().into_inner();
1398                let type_name_pair = type_inner.next().ok_or_else(|| {
1399                    self.create_error_pair(SpecificError::MissingTypeName, &type_coerce_pair)
1400                })?;
1401                Some(self.parse_type(type_name_pair)?)
1402            } else {
1403                None
1404            }
1405        } else {
1406            None
1407        };
1408
1409        let rhs_expr = self.parse_expression(&Self::next_pair(&mut inner)?)?;
1410
1411        if maybe_annotation.is_some() || found_var.is_mutable.is_some() {
1412            Ok(self.create_expr(
1413                ExpressionKind::VariableDefinition(
1414                    found_var,
1415                    maybe_annotation,
1416                    Box::from(rhs_expr),
1417                ),
1418                pair,
1419            ))
1420        } else {
1421            Ok(self.create_expr(
1422                ExpressionKind::VariableAssignment(found_var, Box::from(rhs_expr)),
1423                pair,
1424            ))
1425        }
1426    }
1427    fn parse_prefix(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1428        debug_assert_eq!(pair.as_rule(), Rule::prefix);
1429        let _span = pair.as_span();
1430        let inner = Self::convert_into_iterator(pair);
1431        let mut expr = None;
1432        let mut prefix_ops = Vec::new();
1433
1434        for part in inner {
1435            match part.as_rule() {
1436                Rule::prefix_op | Rule::op_neg | Rule::op_not => {
1437                    let op = self.parse_unary_operator(&part)?;
1438                    prefix_ops.push(op);
1439                }
1440                _ => {
1441                    expr = Some(self.parse_postfix_expression(&part)?);
1442                    break;
1443                }
1444            }
1445        }
1446
1447        let mut final_expr = expr.ok_or_else(|| {
1448            self.create_error_pair(SpecificError::ExpectedExpressionAfterPrefixOperator, pair)
1449        })?;
1450
1451        for op in prefix_ops.into_iter().rev() {
1452            final_expr = self.create_expr(ExpressionKind::UnaryOp(op, Box::new(final_expr)), pair);
1453        }
1454
1455        Ok(final_expr)
1456    }
1457
1458    fn parse_binary_operator(&self, pair: &Pair<Rule>) -> Result<BinaryOperator, ParseError> {
1459        let op = match pair.as_rule() {
1460            Rule::prefix_op => self.next_inner_pair(pair)?,
1461            _ => pair.clone(),
1462        };
1463
1464        let kind = match op.as_rule() {
1465            Rule::op_add => BinaryOperatorKind::Add,
1466            Rule::op_sub => BinaryOperatorKind::Subtract,
1467            Rule::op_mul => BinaryOperatorKind::Multiply,
1468            Rule::op_div => BinaryOperatorKind::Divide,
1469            Rule::op_mod => BinaryOperatorKind::Modulo,
1470            Rule::op_eq => BinaryOperatorKind::Equal,
1471            Rule::op_neq => BinaryOperatorKind::NotEqual,
1472            Rule::op_lt => BinaryOperatorKind::LessThan,
1473            Rule::op_lte => BinaryOperatorKind::LessEqual,
1474            Rule::op_gt => BinaryOperatorKind::GreaterThan,
1475            Rule::op_gte => BinaryOperatorKind::GreaterEqual,
1476            Rule::op_and => BinaryOperatorKind::LogicalAnd,
1477            Rule::op_or => BinaryOperatorKind::LogicalOr,
1478            _ => {
1479                panic!("unknown operator")
1480            }
1481        };
1482
1483        Ok(BinaryOperator {
1484            kind,
1485            node: self.to_node(pair),
1486        })
1487    }
1488
1489    fn parse_unary_operator(&self, pair: &Pair<Rule>) -> Result<UnaryOperator, ParseError> {
1490        let op = match pair.as_rule() {
1491            Rule::prefix_op => &self.next_inner_pair(pair)?,
1492            _ => pair,
1493        };
1494
1495        let node = self.to_node(op);
1496        match op.as_rule() {
1497            Rule::op_neg => Ok(UnaryOperator::Negate(node)),
1498            Rule::op_not => Ok(UnaryOperator::Not(node)),
1499            Rule::op_borrow_mut_ref => Ok(UnaryOperator::BorrowMutRef(node)),
1500            _ => Err(self.create_error_pair(
1501                SpecificError::UnexpectedUnaryOperator(Self::pair_to_rule(op)),
1502                op,
1503            )),
1504        }
1505    }
1506
1507    fn parse_module_segments(&self, pair: Pair<Rule>) -> Vec<Node> {
1508        pair.into_inner()
1509            .filter_map(|segment| {
1510                if segment.as_rule() == Rule::identifier {
1511                    Some(self.to_node(&segment))
1512                } else {
1513                    None
1514                }
1515            })
1516            .collect()
1517    }
1518
1519    fn parse_qualified_type_identifier(
1520        &self,
1521        pair: &Pair<Rule>,
1522    ) -> Result<QualifiedTypeIdentifier, ParseError> {
1523        let mut inner_pairs = pair.clone().into_inner();
1524        let mut generic_types = Vec::new();
1525
1526        let first = inner_pairs.next().ok_or_else(|| {
1527            self.create_error_pair(
1528                SpecificError::ExpectedTypeIdentifier(Self::pair_to_rule(pair)),
1529                pair,
1530            )
1531        })?;
1532
1533        match first.as_rule() {
1534            Rule::module_segments => {
1535                let module_path = self.parse_module_segments(first.clone());
1536                let type_id = inner_pairs.next().ok_or_else(|| {
1537                    self.create_error_pair(SpecificError::ExpectedTypeIdentifierAfterPath, &first)
1538                })?;
1539
1540                let type_identifier = self.parse_local_type_identifier(&type_id)?;
1541
1542                // TODO: Maybe loop and check for generic params
1543                if let Some(generic_params) = inner_pairs.next() {
1544                    if generic_params.as_rule() == Rule::generic_arguments {
1545                        generic_types = self.parse_generic_arguments(&generic_params)?; // TODO: maybe not used?
1546                    }
1547                }
1548
1549                Ok(QualifiedTypeIdentifier::new_with_generics(
1550                    type_identifier,
1551                    module_path,
1552                    generic_types,
1553                ))
1554            }
1555            Rule::type_identifier => {
1556                let type_identifier = LocalTypeIdentifier(self.to_node(&first));
1557
1558                // TODO: Maybe loop and check for generic params
1559                if let Some(generic_params) = inner_pairs.next() {
1560                    if generic_params.as_rule() == Rule::generic_arguments {
1561                        generic_types = self.parse_generic_arguments(&generic_params)?;
1562                    }
1563                }
1564
1565                Ok(QualifiedTypeIdentifier::new_with_generics(
1566                    type_identifier,
1567                    Vec::new(),
1568                    generic_types,
1569                ))
1570            }
1571            _ => Err(self.create_error_pair(
1572                SpecificError::ExpectedTypeIdentifier(Self::pair_to_rule(&first)),
1573                &first,
1574            )),
1575        }
1576    }
1577
1578    fn parse_qualified_identifier(
1579        &self,
1580        pair: &Pair<Rule>,
1581    ) -> Result<QualifiedIdentifier, ParseError> {
1582        let mut inner_pairs = pair.clone().into_inner();
1583        let mut generic_types = Vec::new();
1584
1585        let first = inner_pairs
1586            .next()
1587            .ok_or_else(|| self.create_error_pair(SpecificError::ExpectedIdentifier, pair))?;
1588
1589        match first.as_rule() {
1590            Rule::module_segments => {
1591                let module_path = self.parse_module_segments(first.clone());
1592                let id = inner_pairs.next().ok_or_else(|| {
1593                    self.create_error_pair(SpecificError::ExpectedIdentifierAfterPath, &first)
1594                })?;
1595
1596                let identifier = self.to_node(&id);
1597
1598                // TODO: Maybe loop and check for generic params
1599                if let Some(generic_params) = inner_pairs.next() {
1600                    if generic_params.as_rule() == Rule::generic_arguments {
1601                        // TODO: maybe not used?
1602                        generic_types = self.parse_generic_arguments(&generic_params)?;
1603                    }
1604                }
1605
1606                Ok(QualifiedIdentifier::new_with_generics(
1607                    identifier,
1608                    module_path,
1609                    generic_types,
1610                ))
1611            }
1612            Rule::identifier => {
1613                let type_identifier = self.to_node(&first);
1614
1615                // TODO: Maybe loop and check for generic params
1616                if let Some(generic_params) = inner_pairs.next() {
1617                    if generic_params.as_rule() == Rule::generic_arguments {
1618                        // TODO: maybe not used
1619                        generic_types = self.parse_generic_arguments(&generic_params)?;
1620                    }
1621                }
1622
1623                Ok(QualifiedIdentifier::new_with_generics(
1624                    type_identifier,
1625                    Vec::new(),
1626                    generic_types,
1627                ))
1628            }
1629            _ => Err(self.create_error_pair(SpecificError::ExpectedIdentifier, &first)),
1630        }
1631    }
1632
1633    fn parse_qualified_identifier_expression(
1634        &self,
1635        pair: &Pair<Rule>,
1636    ) -> Result<Expression, ParseError> {
1637        let qualified_identifier = self.parse_qualified_identifier(pair)?;
1638        Ok(self.create_expr(
1639            ExpressionKind::IdentifierReference(qualified_identifier),
1640            pair,
1641        ))
1642    }
1643
1644    fn parse_generic_arguments(&self, pair: &Pair<Rule>) -> Result<Vec<Type>, ParseError> {
1645        debug_assert_eq!(pair.as_rule(), Rule::generic_arguments);
1646
1647        let inner_pairs = pair.clone().into_inner();
1648        let mut generic_types = Vec::new();
1649
1650        for type_pair in inner_pairs {
1651            if type_pair.as_rule() == Rule::type_name {
1652                generic_types.push(self.parse_type(type_pair)?);
1653            }
1654        }
1655
1656        Ok(generic_types)
1657    }
1658
1659    fn parse_local_type_identifier_node(&self, pair: &Pair<Rule>) -> Result<Node, ParseError> {
1660        if pair.as_rule() != Rule::type_identifier {
1661            return Err(self.create_error_pair(
1662                SpecificError::ExpectedTypeIdentifier(format!("{:?}", pair.as_rule())),
1663                pair,
1664            ));
1665        }
1666        Ok(self.to_node(pair))
1667    }
1668
1669    fn parse_generic_type_variables(
1670        &self,
1671        pair: &Pair<Rule>,
1672    ) -> Result<Vec<TypeVariable>, ParseError> {
1673        debug_assert_eq!(pair.as_rule(), Rule::generic_type_variables);
1674        let mut type_params = Vec::new();
1675
1676        let inner = Self::convert_into_iterator(pair);
1677        for type_variable in inner {
1678            let mut inner_type_var = type_variable.into_inner();
1679            let type_identifier_pair = inner_type_var.next().unwrap();
1680
1681            type_params.push(TypeVariable(
1682                self.parse_local_type_identifier_node(&type_identifier_pair)?,
1683            ));
1684        }
1685        Ok(type_params)
1686    }
1687
1688    fn parse_local_type_identifier_with_optional_type_variables(
1689        &self,
1690        pair: &Pair<Rule>,
1691    ) -> Result<LocalTypeIdentifierWithOptionalTypeVariables, ParseError> {
1692        debug_assert_eq!(
1693            pair.as_rule(),
1694            Rule::type_identifier_optional_type_variables
1695        );
1696
1697        let mut inner = pair.clone().into_inner();
1698        let name = self.expect_local_type_identifier_next(&mut inner)?;
1699
1700        let type_variables = if let Some(generic_params_pair) = inner.peek() {
1701            // Peek to see if generic params exist
1702            if generic_params_pair.as_rule() == Rule::generic_type_variables {
1703                let _ = inner.next().unwrap(); // Consume the generic_type_params pair
1704                self.parse_generic_type_variables(&generic_params_pair)?
1705            } else {
1706                Vec::new()
1707            }
1708        } else {
1709            Vec::new()
1710        };
1711
1712        Ok(LocalTypeIdentifierWithOptionalTypeVariables {
1713            name: name.0,
1714            type_variables,
1715        })
1716    }
1717
1718    fn parse_struct_fields_expressions<'a>(
1719        &self,
1720        field_list_pair: &Pair<Rule>,
1721    ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1722        let mut fields = Vec::new();
1723        let mut has_rest = false;
1724
1725        for field_pair in field_list_pair.clone().into_inner() {
1726            match field_pair.as_rule() {
1727                Rule::struct_field => {
1728                    let mut field_inner = field_pair.into_inner();
1729                    let ident = self.expect_field_label_next(&mut field_inner)?;
1730                    let field_name = FieldName(ident.0);
1731                    let field_value = self.parse_expression(&field_inner.next().unwrap())?;
1732
1733                    fields.push(FieldExpression {
1734                        field_name,
1735                        expression: field_value,
1736                    });
1737                }
1738                Rule::rest_fields => {
1739                    has_rest = true;
1740                }
1741                _ => {
1742                    return Err(
1743                        self.create_error_pair(SpecificError::ExpectedFieldOrRest, &field_pair)
1744                    );
1745                }
1746            }
1747        }
1748
1749        Ok((fields, has_rest))
1750    }
1751
1752    fn parse_anonymous_struct_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1753        let (fields, has_rest) = self.parse_anonymous_struct_literal_fields(&pair)?;
1754        Ok(self.create_expr(
1755            ExpressionKind::AnonymousStructLiteral(fields, has_rest),
1756            pair,
1757        ))
1758    }
1759
1760    fn parse_anonymous_struct_literal_fields(
1761        &self,
1762        pair: &Pair<Rule>,
1763    ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1764        debug_assert_eq!(pair.as_rule(), Rule::anonymous_struct_literal);
1765        let mut inner = Self::convert_into_iterator(pair);
1766        let (field_expressions, detected_rest) =
1767            self.parse_struct_fields_expressions(&inner.next().unwrap())?;
1768
1769        Ok((field_expressions, detected_rest))
1770    }
1771
1772    fn parse_struct_literal_optional_fields(
1773        &self,
1774        pair: &Pair<Rule>,
1775    ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1776        debug_assert_eq!(pair.as_rule(), Rule::struct_literal_optional_field_list);
1777        let mut inner = Self::convert_into_iterator(pair);
1778        let (field_expressions, detected_rest) = if let Some(field_list) = inner.next() {
1779            self.parse_struct_fields_expressions(&field_list)?
1780        } else {
1781            (vec![], false)
1782        };
1783
1784        Ok((field_expressions, detected_rest))
1785    }
1786
1787    fn parse_struct_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1788        let mut inner = Self::convert_into_iterator(pair);
1789
1790        let type_pair = inner.next().unwrap();
1791
1792        let struct_name = self.parse_qualified_type_identifier(&type_pair)?;
1793
1794        let anon_fields = inner.next().unwrap();
1795
1796        let (fields, has_rest) = self.parse_struct_literal_optional_fields(&anon_fields)?;
1797
1798        Ok(self.create_expr(
1799            ExpressionKind::NamedStructLiteral(struct_name, fields, has_rest),
1800            pair,
1801        ))
1802    }
1803
1804    fn parse_static_member_reference(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1805        let mut inner = pair.clone().into_inner();
1806
1807        let type_identifier = self.parse_qualified_type_identifier(&inner.next().unwrap())?;
1808        let member_name = self.expect_identifier_next(&mut inner)?;
1809
1810        Ok(self.create_expr(
1811            ExpressionKind::StaticMemberFunctionReference(type_identifier, member_name.0),
1812            pair,
1813        ))
1814    }
1815
1816    fn parse_constant_reference(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1817        debug_assert_eq!(pair.as_rule(), Rule::constant_reference);
1818        let mut inner_pairs = pair.clone().into_inner();
1819
1820        let mut first = inner_pairs.next().unwrap();
1821
1822        let module_path = if first.as_rule() == Rule::module_segments {
1823            let path = self.parse_module_segments(first.clone());
1824            first = inner_pairs.next().unwrap();
1825            Some(ModulePath(path))
1826        } else {
1827            None
1828        };
1829
1830        let identifier = QualifiedConstantIdentifier::new(self.to_node(&first), module_path);
1831
1832        Ok(self.create_expr(ExpressionKind::ConstantReference(identifier), pair))
1833    }
1834
1835    fn parse_term(&self, pair2: &Pair<Rule>) -> Result<Expression, ParseError> {
1836        debug_assert_eq!(pair2.as_rule(), Rule::term);
1837        let sub = &Self::right_alternative(pair2)?;
1838        match sub.as_rule() {
1839            Rule::qualified_identifier => self.parse_qualified_identifier_expression(sub),
1840            Rule::static_member_reference => self.parse_static_member_reference(sub),
1841
1842            Rule::enum_literal => {
1843                Ok(self.create_expr(ExpressionKind::Literal(self.parse_enum_literal(sub)?), sub))
1844            }
1845            Rule::constant_reference => self.parse_constant_reference(sub),
1846            Rule::parenthesized => {
1847                let inner = self.next_inner_pair(sub)?;
1848                self.parse_expression(&inner)
1849            }
1850            Rule::basic_literal => {
1851                let (literal, node) = self.parse_basic_literal(sub)?;
1852                Ok(self.create_expr_span(ExpressionKind::Literal(literal), node))
1853            }
1854            Rule::struct_literal => self.parse_struct_literal(sub),
1855            Rule::anonymous_struct_literal => self.parse_anonymous_struct_literal(sub),
1856
1857            Rule::interpolated_string => self.parse_interpolated_string(sub),
1858
1859            Rule::lambda => self.parse_lambda(sub),
1860
1861            _ => {
1862                Err(self
1863                    .create_error_pair(SpecificError::UnknownTerm(Self::pair_to_rule(sub)), sub))
1864            }
1865        }
1866    }
1867
1868    fn parse_interpolated_string(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1869        let mut parts = Vec::new();
1870
1871        for part_pair in Self::convert_into_iterator(pair) {
1872            match part_pair.as_rule() {
1873                Rule::text => {
1874                    parts.push(StringPart::Literal(
1875                        self.to_node(&part_pair),
1876                        self.unescape_string(&part_pair, false)?,
1877                    ));
1878                }
1879                Rule::interpolation => {
1880                    let inner = self.next_inner_pair(&part_pair.clone())?;
1881                    let expr = match inner.as_rule() {
1882                        Rule::expression => self.parse_expression(&inner)?,
1883                        _ => {
1884                            return Err(self.create_error_pair(
1885                                SpecificError::ExpectedExpressionInInterpolation,
1886                                &inner,
1887                            ));
1888                        }
1889                    };
1890
1891                    let format = match Self::convert_into_iterator(&part_pair).nth(1) {
1892                        Some(fmt) => {
1893                            if fmt.as_rule() == Rule::format_specifier {
1894                                Some(self.parse_format_specifier(&fmt)?)
1895                            } else {
1896                                None
1897                            }
1898                        }
1899                        _ => None,
1900                    };
1901
1902                    parts.push(StringPart::Interpolation(Box::new(expr), format));
1903                }
1904                _ => {
1905                    return Err(self.create_error_pair(
1906                        SpecificError::UnexpectedRuleInInterpolation,
1907                        &part_pair,
1908                    ));
1909                }
1910            }
1911        }
1912
1913        Ok(self.create_expr(ExpressionKind::InterpolatedString(parts), pair))
1914    }
1915
1916    fn parse_format_specifier(&self, pair: &Pair<Rule>) -> Result<FormatSpecifier, ParseError> {
1917        let node = self.to_node(pair);
1918        match pair.as_str() {
1919            "x" => Ok(FormatSpecifier::LowerHex(node)),
1920            "X" => Ok(FormatSpecifier::UpperHex(node)),
1921            "b" => Ok(FormatSpecifier::Binary(node)),
1922            "f" => Ok(FormatSpecifier::Float(node)),
1923            s if s.starts_with("..") => {
1924                let precision: u32 = s[2..s.len() - 1].parse().map_err(|_| {
1925                    self.create_error_pair(SpecificError::InvalidPrecisionValue, pair)
1926                })?;
1927                let typ = match s.chars().last().unwrap() {
1928                    'f' => PrecisionType::Float(node),
1929                    's' => PrecisionType::String(node),
1930                    _ => {
1931                        return Err(
1932                            self.create_error_pair(SpecificError::InvalidPrecisionType, pair)
1933                        )?;
1934                    }
1935                };
1936                Ok(FormatSpecifier::Precision(
1937                    precision,
1938                    self.to_node(&pair),
1939                    typ,
1940                ))
1941            }
1942            _ => Err(self.create_error_pair(SpecificError::InvalidFormatSpecifier, pair)),
1943        }
1944    }
1945
1946    fn parse_enum_literal(&self, pair: &Pair<Rule>) -> Result<LiteralKind, ParseError> {
1947        let mut inner = Self::convert_into_iterator(pair);
1948
1949        // Parse enum type name
1950        let enum_type = self.parse_qualified_type_identifier(&inner.next().unwrap())?;
1951
1952        // Parse variant name
1953        let variant_pair = Self::expect_next(&mut inner, Rule::type_identifier)?;
1954        let variant_type_identifier = LocalTypeIdentifier::new(self.to_node(&variant_pair));
1955
1956        // Parse fields if they exist
1957        let enum_variant_literal = match inner.next() {
1958            Some(fields_pair) => match fields_pair.as_rule() {
1959                Rule::struct_literal_optional_field_list => {
1960                    let (field_expressions, detected_rest) =
1961                        self.parse_struct_literal_optional_fields(&fields_pair)?;
1962                    EnumVariantLiteral::Struct(
1963                        enum_type,
1964                        variant_type_identifier,
1965                        field_expressions,
1966                        detected_rest,
1967                    )
1968                }
1969                Rule::tuple_fields => {
1970                    let mut expressions = vec![];
1971                    for field in Self::convert_into_iterator(&fields_pair) {
1972                        let field_value = self.parse_expression(&field)?;
1973                        expressions.push(field_value);
1974                    }
1975                    EnumVariantLiteral::Tuple(enum_type, variant_type_identifier, expressions)
1976                }
1977                _ => {
1978                    error!("{:?}, {}", fields_pair.as_rule(), "strange");
1979                    return Err(
1980                        self.create_error_pair(SpecificError::UnexpectedVariantField, &fields_pair)
1981                    );
1982                }
1983            },
1984            _ => EnumVariantLiteral::Simple(enum_type, variant_type_identifier),
1985        };
1986
1987        Ok(LiteralKind::EnumVariant(enum_variant_literal))
1988    }
1989
1990    fn unescape_unicode(
1991        &self,
1992        chars: &mut Peekable<Chars>,
1993        octets: &mut Vec<u8>,
1994        pair: &Pair<Rule>,
1995    ) -> Result<(), ParseError> {
1996        match chars.next() {
1997            Some('(') => {
1998                let mut hex_digits = String::new();
1999
2000                while let Some(&c) = chars.peek() {
2001                    if c == ')' {
2002                        break;
2003                    }
2004                    if c.is_ascii_hexdigit() && hex_digits.len() < 6 {
2005                        hex_digits.push(c);
2006                        chars.next();
2007                    } else {
2008                        return Err(
2009                            self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
2010                        );
2011                    }
2012                }
2013
2014                match chars.next() {
2015                    Some(')') => {
2016                        if hex_digits.is_empty() {
2017                            return Err(
2018                                self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
2019                            );
2020                        }
2021
2022                        let code = u32::from_str_radix(&hex_digits, 16).map_err(|_| {
2023                            self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
2024                        })?;
2025
2026                        if code > 0x0010_FFFF {
2027                            return Err(
2028                                self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
2029                            );
2030                        }
2031
2032                        if let Some(c) = std::char::from_u32(code) {
2033                            let mut buf = [0; 4];
2034                            let encoded = c.encode_utf8(&mut buf);
2035                            octets.extend_from_slice(encoded.as_bytes());
2036                        } else {
2037                            return Err(
2038                                self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
2039                            );
2040                        }
2041                    }
2042                    _ => {
2043                        return Err(
2044                            self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
2045                        );
2046                    }
2047                }
2048            }
2049            _ => {
2050                return Err(self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair));
2051            }
2052        }
2053        Ok(())
2054    }
2055
2056    fn unescape_hex(
2057        &self,
2058        chars: &mut Peekable<Chars>,
2059        pair: &Pair<Rule>,
2060    ) -> Result<u8, ParseError> {
2061        let mut hex_digits = String::new();
2062        for _ in 0..2 {
2063            match chars.next() {
2064                Some(h) if h.is_ascii_hexdigit() => {
2065                    hex_digits.push(h);
2066                }
2067                _ => {
2068                    return Err(self.create_error_pair(SpecificError::InvalidHexEscape, pair));
2069                }
2070            }
2071        }
2072        u8::from_str_radix(&hex_digits, 16)
2073            .map_err(|_| self.create_error_pair(SpecificError::InvalidHexEscape, pair))
2074    }
2075
2076    fn unescape_string(&self, pair: &Pair<Rule>, is_literal: bool) -> Result<String, ParseError> {
2077        let mut octets = Vec::new();
2078
2079        let raw = if is_literal {
2080            &pair.as_str()[1..pair.as_str().len() - 1]
2081        } else {
2082            pair.as_str()
2083        };
2084
2085        let mut chars = raw.chars().peekable();
2086
2087        while let Some(ch) = chars.next() {
2088            if ch == '\\' {
2089                let Some(next_ch) = chars.next() else {
2090                    return Err(
2091                        self.create_error_pair(SpecificError::UnfinishedEscapeSequence, pair)
2092                    );
2093                };
2094                match next_ch {
2095                    'n' => {
2096                        octets.push(b'\n');
2097                    }
2098                    't' => {
2099                        octets.push(b'\t');
2100                    }
2101                    '\\' => {
2102                        octets.push(b'\\');
2103                    }
2104                    '"' => {
2105                        octets.push(b'"');
2106                    }
2107                    '\'' => {
2108                        octets.push(b'\'');
2109                    }
2110                    // Two hexadecimal digits that result in an `u8`
2111                    'x' => {
2112                        let code = self.unescape_hex(&mut chars, pair)?;
2113                        octets.push(code);
2114                    }
2115                    // Unicode character
2116                    'u' => {
2117                        self.unescape_unicode(&mut chars, &mut octets, pair)?;
2118                    }
2119
2120                    other => {
2121                        return Err(self.create_error_pair(
2122                            SpecificError::UnknownEscapeCharacter(other),
2123                            pair,
2124                        ));
2125                    }
2126                }
2127            } else {
2128                let mut buf = [0; 4];
2129                let utf8_bytes = ch.encode_utf8(&mut buf);
2130                octets.extend_from_slice(utf8_bytes.as_bytes());
2131            }
2132        }
2133
2134        let output = String::from_utf8(octets)
2135            .map_err(|_| self.create_error_pair(SpecificError::InvalidUtf8Sequence, pair))?;
2136
2137        Ok(output)
2138    }
2139
2140    fn parse_basic_literal(&self, pair: &Pair<Rule>) -> Result<(LiteralKind, Node), ParseError> {
2141        debug_assert_eq!(pair.as_rule(), Rule::basic_literal);
2142        let inner = self.next_inner_pair(pair)?;
2143        let literal_kind = match inner.as_rule() {
2144            Rule::int_lit => LiteralKind::Int,
2145            Rule::float_lit => LiteralKind::Float,
2146            Rule::string_lit => {
2147                let processed_string = self.unescape_string(&inner, true)?;
2148                LiteralKind::String(processed_string)
2149            }
2150            Rule::bool_lit => LiteralKind::Bool,
2151            Rule::none_lit => LiteralKind::None,
2152            Rule::tuple_lit => {
2153                let mut expressions = Vec::new();
2154                for expr_pair in Self::convert_into_iterator(&inner) {
2155                    expressions.push(self.parse_expression(&expr_pair)?);
2156                }
2157                LiteralKind::Tuple(expressions)
2158            }
2159            _ => return Err(self.create_error_pair(SpecificError::UnknownLiteral, &inner)),
2160        };
2161        Ok((literal_kind, self.to_node(&inner)))
2162    }
2163
2164    fn parse_array_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2165        let mut elements = Vec::new();
2166        for element in Self::convert_into_iterator(pair) {
2167            elements.push(self.parse_expression(&element)?);
2168        }
2169        Ok(self.create_expr(ExpressionKind::Literal(LiteralKind::Slice(elements)), pair))
2170    }
2171
2172    fn parse_map_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2173        let mut entries = Vec::new();
2174
2175        for entry_pair in Self::convert_into_iterator(pair) {
2176            if entry_pair.as_rule() == Rule::map_entry {
2177                let mut entry_inner = Self::convert_into_iterator(&entry_pair);
2178                let key = self.parse_expression(&Self::next_pair(&mut entry_inner)?)?;
2179                let value = self.parse_expression(&Self::next_pair(&mut entry_inner)?)?;
2180                entries.push((key, value));
2181            }
2182        }
2183
2184        Ok(self.create_expr(
2185            ExpressionKind::Literal(LiteralKind::SlicePair(entries)),
2186            pair,
2187        ))
2188    }
2189
2190    fn assert_end(pairs: &mut Pairs<Rule>) {
2191        assert!(pairs.next().is_none());
2192    }
2193
2194    fn parse_function_call_postfix(
2195        &self,
2196        pair: &Pair<Rule>,
2197    ) -> Result<(Option<Vec<Type>>, Vec<Expression>), ParseError> {
2198        debug_assert_eq!(pair.as_rule(), Rule::function_call_postfix);
2199        let mut inner = pair.clone().into_inner();
2200
2201        let mut generic_args: Option<Vec<Type>> = None;
2202        let args_pair: Pair<Rule>; // To hold the function_call_args pair
2203
2204        if let Some(first_inner) = inner.peek() {
2205            if first_inner.as_rule() == Rule::generic_arguments {
2206                let generic_args_pair = Self::next_pair(&mut inner)?;
2207                generic_args = Some(self.parse_generic_arguments(&generic_args_pair)?);
2208
2209                args_pair = Self::next_pair(&mut inner)?;
2210            } else {
2211                args_pair = Self::next_pair(&mut inner)?;
2212            }
2213        } else {
2214            panic!("problem in function_call_postfix");
2215        }
2216
2217        debug_assert_eq!(args_pair.as_rule(), Rule::function_call_args);
2218
2219        let regular_args = self.parse_function_call_arguments(&args_pair)?;
2220
2221        Self::assert_end(&mut inner);
2222
2223        Ok((generic_args, regular_args))
2224    }
2225
2226    fn parse_arg_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2227        debug_assert_eq!(pair.as_rule(), Rule::arg_expression);
2228        let mut inner = pair.clone().into_inner();
2229        self.parse_logical(&inner.next().unwrap())
2230    }
2231
2232    fn parse_function_call_arguments(
2233        &self,
2234        pair: &Pair<Rule>,
2235    ) -> Result<Vec<Expression>, ParseError> {
2236        debug_assert_eq!(pair.as_rule(), Rule::function_call_args);
2237        let inner = pair.clone().into_inner();
2238        let mut args = Vec::new();
2239
2240        // Parse arguments
2241        for arg_pair in inner {
2242            let expr = self.parse_arg_expression(&arg_pair)?;
2243            args.push(expr);
2244        }
2245
2246        Ok(args)
2247    }
2248
2249    #[allow(clippy::too_many_lines)]
2250    fn parse_type(&self, pair: Pair<Rule>) -> Result<Type, ParseError> {
2251        match pair.as_rule() {
2252            Rule::type_name => {
2253                let mut inner = pair.clone().into_inner();
2254                let base_type = if let Some(inner_pair) = inner.next() {
2255                    self.parse_type(inner_pair)?
2256                } else {
2257                    panic!("shouldn't get to here")
2258                };
2259
2260                let optional_marker = inner
2261                    .find(|p| p.as_rule() == Rule::optional_marker)
2262                    .map(|marker_pair| self.to_node(&marker_pair));
2263                if let Some(found_optional_marker) = optional_marker {
2264                    Ok(Type::Optional(Box::new(base_type), found_optional_marker))
2265                } else {
2266                    Ok(base_type)
2267                }
2268            }
2269
2270            Rule::base_type => {
2271                let mut inner = pair.into_inner();
2272                let first = inner.next().unwrap();
2273                let base_type = self.parse_type(first)?;
2274
2275                Ok(base_type)
2276            }
2277            Rule::function_type => {
2278                let mut function_inner = pair.into_inner();
2279
2280                // Parse parameter types
2281                let param_types = if let Some(params) = function_inner
2282                    .next()
2283                    .filter(|p| p.as_rule() == Rule::function_params)
2284                {
2285                    params
2286                        .into_inner()
2287                        .map(|param| {
2288                            Ok(TypeForParameter {
2289                                ast_type: self.parse_type(param).unwrap(),
2290                                is_mutable: false,
2291                            })
2292                        })
2293                        .collect::<Result<Vec<_>, ParseError>>()?
2294                } else {
2295                    Vec::new()
2296                };
2297
2298                // Parse return type
2299                let return_type = self.parse_type(function_inner.next().unwrap())?;
2300
2301                Ok(Type::Function(param_types, Box::new(return_type)))
2302            }
2303
2304            Rule::qualified_type_identifier => {
2305                let qualified_id = self.parse_qualified_type_identifier(&pair)?;
2306                Ok(Type::Named(qualified_id))
2307            }
2308            Rule::tuple_type => {
2309                let elements = self.parse_tuple_type_elements(&pair)?;
2310                Ok(Type::Tuple(elements))
2311            }
2312            Rule::slice_pair_type => {
2313                let mut inner = pair.into_inner();
2314                let key_type = self.parse_type(Self::next_pair(&mut inner)?)?;
2315                let value_type = self.parse_type(Self::next_pair(&mut inner)?)?;
2316                Ok(Type::SlicePair(Box::new(key_type), Box::new(value_type)))
2317            }
2318
2319            Rule::slice_type => {
2320                let inner = self.next_inner_pair(&pair)?;
2321                let element_type = self.parse_type(inner)?;
2322                Ok(Type::Slice(Box::new(element_type)))
2323            }
2324
2325            Rule::struct_type => {
2326                let element_type = self.parse_struct_type(&pair)?;
2327                Ok(Type::AnonymousStruct(element_type))
2328            }
2329
2330            Rule::unit_type => Ok(Type::Unit),
2331
2332            _ => Err(self.create_error_pair(
2333                SpecificError::UnexpectedTypeRule(format!("{:?}", pair.as_rule())),
2334                &pair,
2335            )),
2336        }
2337    }
2338
2339    #[allow(unused)] // TODO: Use this again
2340    fn parse_local_type_identifier(
2341        &self,
2342        pair: &Pair<Rule>,
2343    ) -> Result<LocalTypeIdentifier, ParseError> {
2344        if pair.as_rule() != Rule::type_identifier {
2345            return Err(self.create_error_pair(
2346                SpecificError::ExpectedTypeIdentifier(format!("{:?}", pair.as_rule())),
2347                pair,
2348            ));
2349        }
2350        Ok(LocalTypeIdentifier::new(self.to_node(pair)))
2351    }
2352
2353    fn parse_enum_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
2354        let mut inner = Self::convert_into_iterator(pair);
2355
2356        let name_with_optional_type_params =
2357            self.parse_local_type_identifier_with_optional_type_variables(&inner.next().unwrap())?;
2358
2359        let mut variants = Vec::new();
2360
2361        if let Some(variants_pair) = inner.next() {
2362            if variants_pair.as_rule() == Rule::enum_variants {
2363                for variant_pair in Self::convert_into_iterator(&variants_pair) {
2364                    if variant_pair.as_rule() == Rule::enum_variant {
2365                        let variant =
2366                            self.parse_enum_variant(&self.next_inner_pair(&variant_pair)?)?;
2367
2368                        variants.push(variant);
2369                    }
2370                }
2371            }
2372        }
2373
2374        Ok(Definition::EnumDef(
2375            name_with_optional_type_params,
2376            variants,
2377        ))
2378    }
2379
2380    fn parse_enum_variant(&self, pair: &Pair<Rule>) -> Result<EnumVariantType, ParseError> {
2381        let enum_variant = match pair.as_rule() {
2382            Rule::simple_variant => EnumVariantType::Simple(self.to_node(pair)),
2383            Rule::tuple_variant => {
2384                let mut inner = Self::convert_into_iterator(pair);
2385                let name = self.expect_local_type_identifier_next(&mut inner)?;
2386
2387                let tuple_elements = self.parse_tuple_type_elements(&inner.next().unwrap())?;
2388
2389                EnumVariantType::Tuple(name.0, tuple_elements)
2390            }
2391            Rule::struct_variant => {
2392                let mut inner = Self::convert_into_iterator(pair);
2393                let name = self.expect_local_type_identifier_next(&mut inner)?;
2394
2395                let struct_type = self.parse_struct_type(&inner.next().unwrap())?;
2396                EnumVariantType::Struct(name.0, struct_type)
2397            }
2398            _ => {
2399                return Err(self.create_error_pair(
2400                    SpecificError::UnknownEnumVariant(Self::pair_to_rule(pair)),
2401                    pair,
2402                ));
2403            }
2404        };
2405
2406        Ok(enum_variant)
2407    }
2408
2409    fn parse_match_expr(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2410        let mut inner = Self::convert_into_iterator(pair);
2411        let value = self.parse_arg_expression(&Self::next_pair(&mut inner)?)?;
2412        let arms_pair = Self::next_pair(&mut inner)?;
2413        let mut arms = Vec::new();
2414
2415        for arm_pair in Self::convert_into_iterator(&arms_pair) {
2416            if arm_pair.as_rule() == Rule::match_arm {
2417                let mut arm_inner = Self::convert_into_iterator(&arm_pair);
2418                let pattern = self.parse_match_pattern(&Self::next_pair(&mut arm_inner)?)?;
2419
2420                // Handle both block and direct expression cases
2421                let expr = match Self::next_pair(&mut arm_inner)? {
2422                    block if block.as_rule() == Rule::block => self.parse_block(&block)?,
2423                    expr => self.parse_expression(&expr)?,
2424                };
2425
2426                arms.push(MatchArm {
2427                    pattern,
2428                    expression: expr,
2429                });
2430            }
2431        }
2432
2433        if arms.is_empty() {
2434            return Err(self.create_error_pair(SpecificError::MustHaveAtLeastOneArm, pair));
2435        }
2436
2437        Ok(self.create_expr(ExpressionKind::Match(Box::new(value), arms), pair))
2438    }
2439
2440    fn parse_match_pattern(&self, pair: &Pair<Rule>) -> Result<Pattern, ParseError> {
2441        let mut inner = Self::convert_into_iterator(pair);
2442        let pattern_inside = inner.next().expect("should have inner");
2443        match pattern_inside.as_rule() {
2444            Rule::normal_pattern => {
2445                let (match_pattern, pattern_node) =
2446                    self.parse_normal_match_pattern(&pattern_inside)?;
2447                let inner_pairs: Vec<_> = pattern_inside.clone().into_inner().collect();
2448                let has_guard = inner_pairs
2449                    .get(1)
2450                    .map(|p| p.as_rule() == Rule::guard_clause)
2451                    .unwrap_or(false);
2452
2453                let guard_clause = if has_guard {
2454                    Some(self.parse_guard_clause(&inner_pairs[1])?)
2455                } else {
2456                    None
2457                };
2458                Ok(Pattern::NormalPattern(
2459                    pattern_node,
2460                    match_pattern,
2461                    guard_clause,
2462                ))
2463            }
2464            Rule::wildcard_pattern => Ok(Pattern::Wildcard(self.to_node(pair))),
2465            _ => Err(self.create_error_pair(SpecificError::MustHaveAtLeastOneArm, pair)),
2466        }
2467    }
2468
2469    fn parse_guard_clause(&self, pair: &Pair<Rule>) -> Result<GuardClause, ParseError> {
2470        let inner = Self::right_alternative(&pair)?;
2471        let clause = match inner.as_rule() {
2472            Rule::wildcard_pattern => GuardClause::Wildcard(Self::node_ex(&pair)),
2473            Rule::expression => {
2474                let mut iterator = inner.into_inner();
2475                let result = self.parse_expression(&Self::next_pair(&mut iterator)?)?;
2476                GuardClause::Expression(result)
2477            }
2478            _ => {
2479                return Err(Self::to_err(
2480                    SpecificError::UnknownExpr("guard_clause".to_string()),
2481                    &pair,
2482                ))?;
2483            }
2484        };
2485
2486        Ok(clause)
2487    }
2488
2489    fn parse_guard_expr_list(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2490        let mut guard_exprs = Vec::new();
2491
2492        for expr_pair in Self::convert_into_iterator(pair) {
2493            match expr_pair.as_rule() {
2494                Rule::guard_item => {
2495                    let mut guard_inner = Self::convert_into_iterator(&expr_pair);
2496                    let guard_clause = Self::next_pair(&mut guard_inner)?;
2497                    let condition = self.parse_guard_clause(&guard_clause)?;
2498                    let result = self.parse_expression(&Self::next_pair(&mut guard_inner)?)?;
2499                    guard_exprs.push(GuardExpr {
2500                        clause: condition,
2501                        result,
2502                    });
2503                }
2504
2505                _ => {
2506                    panic!("Unexpected rule: {:?}", expr_pair.as_rule());
2507                }
2508            }
2509        }
2510
2511        Ok(self.create_expr(ExpressionKind::Guard(guard_exprs), pair))
2512    }
2513
2514    fn parse_normal_match_pattern(
2515        &self,
2516        pair: &Pair<Rule>,
2517    ) -> Result<(NormalPattern, Node), ParseError> {
2518        let mut inner = Self::convert_into_iterator(pair);
2519        let pattern = inner.next().expect("should have inner");
2520
2521        match pattern.as_rule() {
2522            Rule::pattern => {
2523                let mut pattern_inner = Self::convert_into_iterator(&pattern);
2524                let pattern_type = pattern_inner.next().expect("should have inner");
2525
2526                match pattern_type.as_rule() {
2527                    Rule::enum_pattern => {
2528                        let mut inner = Self::convert_into_iterator(&pattern_type);
2529                        let variant = self.expect_local_type_identifier_next(&mut inner)?;
2530                        let elements = inner
2531                            .next()
2532                            .map(|p| self.parse_pattern_list(&p))
2533                            .transpose()?;
2534                        Ok((
2535                            NormalPattern::EnumPattern(variant.0, elements),
2536                            self.to_node(&pattern),
2537                        ))
2538                    }
2539                    Rule::pattern_list => {
2540                        let elements = self.parse_pattern_list(&pattern_type)?;
2541                        Ok((NormalPattern::PatternList(elements), self.to_node(&pattern)))
2542                    }
2543                    Rule::basic_literal => {
2544                        let (literal, node) = self.parse_basic_literal(&pattern_type)?;
2545                        Ok((NormalPattern::Literal(literal), node))
2546                    }
2547                    _ => {
2548                        Err(self.create_error_pair(SpecificError::UnknownMatchType, &pattern_type))
2549                    }
2550                }
2551            }
2552            _ => Err(self.create_error_pair(SpecificError::UnknownMatchType, &pattern)),
2553        }
2554    }
2555
2556    fn parse_pattern_list(&self, pair: &Pair<Rule>) -> Result<Vec<PatternElement>, ParseError> {
2557        let mut elements = Vec::new();
2558        for item in Self::convert_into_iterator(pair) {
2559            match item.as_rule() {
2560                Rule::pattern_field => {
2561                    let inner_pair = item.clone().into_inner().next().unwrap();
2562                    let maybe_mut_identifier = self.parse_maybe_mut_identifier(&inner_pair)?;
2563                    if inner_pair.as_str() == "_" {
2564                        elements.push(PatternElement::Wildcard(self.to_node(&item)));
2565                    } else {
2566                        elements.push(PatternElement::Variable(maybe_mut_identifier));
2567                    }
2568                }
2569                Rule::expression => {
2570                    elements.push(PatternElement::Expression(self.parse_expression(&item)?));
2571                }
2572                _ => {
2573                    return Err(self.create_error_pair(
2574                        SpecificError::UnexpectedPatternListElement(Self::pair_to_rule(&item)),
2575                        &item,
2576                    ));
2577                }
2578            }
2579        }
2580        Ok(elements)
2581    }
2582
2583    fn to_node(&self, pair: &Pair<Rule>) -> Node {
2584        let pair_span = pair.as_span();
2585        let span = SpanWithoutFileId {
2586            offset: pair_span.start() as u32,
2587            length: (pair_span.end() - pair_span.start()) as u16,
2588        };
2589
2590        Node { span }
2591    }
2592
2593    fn node_ex(pair: &Pair<Rule>) -> Node {
2594        let pair_span = pair.as_span();
2595        let span = SpanWithoutFileId {
2596            offset: pair_span.start() as u32,
2597            length: (pair_span.end() - pair_span.start()) as u16,
2598        };
2599
2600        Node { span }
2601    }
2602
2603    fn to_span(&self, pest_span: pest::Span) -> SpanWithoutFileId {
2604        SpanWithoutFileId {
2605            offset: pest_span.start() as u32,
2606            length: (pest_span.end() - pest_span.start()) as u16,
2607        }
2608    }
2609
2610    fn span(pest_span: pest::Span) -> SpanWithoutFileId {
2611        SpanWithoutFileId {
2612            offset: pest_span.start() as u32,
2613            length: (pest_span.end() - pest_span.start()) as u16,
2614        }
2615    }
2616
2617    fn create_expr(&self, kind: ExpressionKind, pair: &Pair<Rule>) -> Expression {
2618        self.create_expr_span(kind, self.to_node(pair))
2619    }
2620
2621    fn create_expr_span(&self, kind: ExpressionKind, node: Node) -> Expression {
2622        //info!(?kind, ?node, "create_expr()");
2623        Expression { kind, node }
2624    }
2625
2626    fn parse_multiplication(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2627        let mut inner = pair.clone().into_inner();
2628        let mut expr = self.parse_prefix(&inner.next().unwrap())?;
2629        while let Some(op) = inner.next() {
2630            // Expect the next token to be a multiplication operator, then the next operand.
2631            let operator = self.parse_binary_operator(&op)?; // op_mul, op_div, or op_mod
2632            let right = self.parse_prefix(&inner.next().unwrap())?;
2633            expr = self.create_expr(
2634                ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2635                pair,
2636            );
2637        }
2638        Ok(expr)
2639    }
2640
2641    fn parse_addition(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2642        let mut inner = pair.clone().into_inner();
2643        let mut expr = self.parse_multiplication(&inner.next().unwrap())?;
2644        while let Some(op) = inner.next() {
2645            let operator = self.parse_binary_operator(&op)?; // op_add or op_sub
2646            let right = self.parse_multiplication(&inner.next().unwrap())?;
2647            expr = self.create_expr(
2648                ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2649                pair,
2650            );
2651        }
2652        Ok(expr)
2653    }
2654
2655    fn parse_comparison(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2656        let mut inner = pair.clone().into_inner();
2657        let mut expr = self.parse_addition(&inner.next().unwrap())?;
2658        while let Some(op) = inner.next() {
2659            let operator = self.parse_binary_operator(&op)?; // e.g. op_lt, op_eq, etc.
2660            let right = self.parse_addition(&inner.next().unwrap())?;
2661            expr = self.create_expr(
2662                ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2663                pair,
2664            );
2665        }
2666        Ok(expr)
2667    }
2668
2669    fn parse_range(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2670        let mut inner = pair.clone().into_inner();
2671        let left = self.parse_comparison(&inner.next().unwrap())?;
2672        if let Some(op) = inner.next() {
2673            let right = self.parse_comparison(&inner.next().unwrap())?;
2674            match op.as_rule() {
2675                Rule::exclusive_range_op => {
2676                    return Ok(self.create_expr(
2677                        ExpressionKind::Range(
2678                            Box::new(left),
2679                            Box::new(right),
2680                            RangeMode::Exclusive,
2681                        ),
2682                        pair,
2683                    ));
2684                }
2685                Rule::inclusive_range_op => {
2686                    return Ok(self.create_expr(
2687                        ExpressionKind::Range(
2688                            Box::new(left),
2689                            Box::new(right),
2690                            RangeMode::Inclusive,
2691                        ),
2692                        pair,
2693                    ));
2694                }
2695                _ => {}
2696            }
2697            let operator = self.parse_binary_operator(&op)?; // inclusive_range_op or exclusive_range_op
2698            Ok(self.create_expr(
2699                ExpressionKind::BinaryOp(Box::new(left), operator, Box::new(right)),
2700                pair,
2701            ))
2702        } else {
2703            Ok(left)
2704        }
2705    }
2706
2707    fn parse_logical(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2708        debug_assert_eq!(pair.as_rule(), Rule::logical);
2709        let mut inner = pair.clone().into_inner();
2710        let mut expr = self.parse_range(&inner.next().unwrap())?;
2711        while let Some(op) = inner.next() {
2712            let operator = self.parse_binary_operator(&op)?; // op_and or op_or
2713            let right = self.parse_range(&inner.next().unwrap())?;
2714            expr = self.create_expr(
2715                ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2716                pair,
2717            );
2718        }
2719        Ok(expr)
2720    }
2721
2722    fn parse_lambda(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2723        debug_assert_eq!(pair.as_rule(), Rule::lambda);
2724        let mut inner = pair.clone().into_inner();
2725        let variable_list_pair = inner.next().unwrap();
2726        let variable_list = self.parse_optional_variable_list(&variable_list_pair)?;
2727        let expression_pair = inner.next().unwrap();
2728        let expression = self.parse_expression(&expression_pair)?;
2729
2730        Ok(self.create_expr(
2731            ExpressionKind::Lambda(variable_list, Box::new(expression)),
2732            pair,
2733        ))
2734    }
2735}