swamp_parser/
lib.rs

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