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