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