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