swamp_script_parser/
lib.rs

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