swamp_script_parser/
lib.rs

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