swamp_script_parser/
lib.rs

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