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