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