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,
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 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 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 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 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 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 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 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::expression => {
1141 let inner = self.next_inner_pair(sub)?;
1142
1143 self.parse_expression(&inner)
1144 }
1145
1146 Rule::qualified_identifier => Ok(self.create_expr(
1147 ExpressionKind::VariableReference(Variable::new(self.to_node(sub), None)),
1148 sub,
1149 )),
1150 Rule::block => self.parse_block(sub),
1151
1152 Rule::assignment => self.parse_assignment_expression(sub),
1153 Rule::destructuring_assignment => self.parse_destructuring_assignment(sub),
1154 Rule::variable_definition => self.parse_variable_definition(sub),
1155
1156 Rule::addition => self.parse_addition(sub),
1157 Rule::range => self.parse_range(sub),
1158 Rule::logical => self.parse_logical(sub),
1159 Rule::comparison => self.parse_comparison(sub),
1160 Rule::multiplication => self.parse_multiplication(sub),
1161
1162 Rule::prefix => self.parse_prefix(sub),
1163
1164 Rule::match_expr => self.parse_match_expr(sub),
1165 Rule::map_literal => self.parse_map_literal(sub),
1166 Rule::array_literal => self.parse_array_literal(sub),
1167 Rule::guard_expr => self.parse_guard_expr_list(sub),
1168 Rule::with_expr => self.parse_with_expr(sub),
1169 Rule::when_expr => self.parse_when_expr(sub),
1170 Rule::if_expr => self.parse_if_expression(sub),
1171 Rule::for_loop => self.parse_for_loop(sub),
1172 Rule::while_loop => self.parse_while_loop(sub),
1173
1174 Rule::prefix_op | Rule::op_neg | Rule::op_not => {
1176 let op = self.parse_unary_operator(sub)?;
1177 let expr = self.parse_postfix_expression(&self.next_inner_pair(sub)?)?;
1178 Ok(self.create_expr(ExpressionKind::UnaryOp(op, Box::new(expr)), sub))
1179 }
1180
1181 Rule::postfix => self.parse_postfix_expression(sub),
1183 _ => Err(self.create_error_pair(
1184 SpecificError::UnexpectedExpressionType(Self::pair_to_rule(sub)),
1185 sub,
1186 )),
1187 }
1188 }
1189
1190 fn parse_variable_list(&self, pair: &Pair<Rule>) -> Result<Vec<Variable>, ParseError> {
1191 let mut variables = Vec::new();
1192 for item_pair in pair.clone().into_inner() {
1193 if item_pair.as_rule() == Rule::variable_item {
1194 variables.push(self.parse_variable_item(&item_pair)?);
1195 }
1196 }
1197 Ok(variables)
1198 }
1199
1200 fn parse_maybe_mut_identifier(&self, pair: &Pair<Rule>) -> Result<Variable, ParseError> {
1201 assert_eq!(pair.as_rule(), Rule::maybe_mut_identifier);
1202 let mut inner = pair.clone().into_inner();
1203 let mut_node = if let Some(peeked) = inner.peek() {
1204 if peeked.as_rule() == Rule::mut_keyword {
1205 let node = self.to_node(&peeked);
1207 inner.next(); Some(node)
1209 } else {
1210 None
1211 }
1212 } else {
1213 None
1214 };
1215
1216 let name_pair = inner.next().ok_or_else(|| {
1217 self.create_error_pair(
1218 SpecificError::UnexpectedRuleInParseScript(
1219 "Expected identifier in variable_item".into(),
1220 ),
1221 pair,
1222 )
1223 })?;
1224
1225 if name_pair.as_rule() != Rule::identifier {
1226 return Err(self.create_error_pair(
1227 SpecificError::UnexpectedRuleInParseScript(format!(
1228 "Expected identifier, found {:?}",
1229 name_pair.as_rule()
1230 )),
1231 &name_pair,
1232 ));
1233 }
1234
1235 let variable = Variable {
1236 name: self.to_node(&name_pair),
1237 is_mutable: mut_node,
1238 };
1239
1240 Ok(variable)
1241 }
1242
1243 fn parse_variable_item(&self, pair: &Pair<Rule>) -> Result<Variable, ParseError> {
1244 assert_eq!(pair.as_rule(), Rule::variable_item);
1245 let mut inner = pair.clone().into_inner();
1246 self.parse_maybe_mut_identifier(&inner.next().unwrap())
1247 }
1248
1249 fn parse_assignment_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1250 let mut iterator = pair.clone().into_inner();
1251 let lhs_logical =
1252 self.parse_logical(&iterator.next().expect("parse_assignment_expression"))?;
1253 if let Some(assignment_op_pair) = iterator.peek().clone() {
1254 iterator.next();
1255 let assignment_op = self.parse_assignment_op(&assignment_op_pair)?;
1256 let rhs_expr = self.parse_expression(&iterator.next().unwrap())?;
1257 let kind = match assignment_op {
1258 AssignmentOperatorKind::Assign => {
1259 ExpressionKind::Assignment(Box::new(lhs_logical), Box::from(rhs_expr))
1260 }
1261 AssignmentOperatorKind::Compound(compound) => {
1262 let op = CompoundOperator {
1263 node: Self::node_ex(&assignment_op_pair),
1264 kind: compound,
1265 };
1266 ExpressionKind::CompoundAssignment(
1267 Box::from(lhs_logical),
1268 op,
1269 Box::from(rhs_expr),
1270 )
1271 }
1272 };
1273
1274 Ok(self.create_expr(kind, &pair))
1275 } else {
1276 Ok(lhs_logical)
1277 }
1278 }
1279
1280 fn parse_assignment_op(&self, pair: &Pair<Rule>) -> Result<AssignmentOperatorKind, ParseError> {
1281 assert_eq!(pair.as_rule(), Rule::assign_op);
1282 let sub = Self::right_alternative(pair)?;
1283 let op = match sub.as_rule() {
1284 Rule::compound_assign_op => {
1285 AssignmentOperatorKind::Compound(Self::parse_compound_assign_op(&sub)?)
1286 }
1287 Rule::normal_assign_op => AssignmentOperatorKind::Assign,
1288 _ => {
1289 return Err(Self::to_err(
1290 SpecificError::UnknownAssignmentOperator("strange".to_string()),
1291 &sub,
1292 ));
1293 }
1294 };
1295
1296 Ok(op)
1297 }
1298
1299 #[allow(clippy::too_many_lines)]
1300 fn parse_destructuring_assignment(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1301 assert_eq!(pair.as_rule(), Rule::destructuring_assignment);
1302 let mut inner = pair.clone().into_inner();
1303
1304 let var_list_pair = inner.next().ok_or_else(|| {
1305 self.create_error_pair(
1306 SpecificError::UnexpectedRuleInParseScript("missing variable_list".to_string()),
1307 pair,
1308 )
1309 })?;
1310
1311 let variables = self.parse_variable_list(&var_list_pair)?;
1312
1313 let rhs_pair = inner.next().ok_or_else(|| {
1314 self.create_error_pair(
1315 SpecificError::UnexpectedRuleInParseScript("missing RHS expression".to_string()),
1316 pair,
1317 )
1318 })?;
1319 let rhs_expr = self.parse_expression(&rhs_pair)?;
1320
1321 Ok(self.create_expr(
1322 ExpressionKind::DestructuringAssignment(variables, Box::new(rhs_expr)),
1323 &rhs_pair,
1324 ))
1325 }
1326
1327 fn right_alternative<'a>(pair: &Pair<'a, Rule>) -> Result<Pair<'a, Rule>, ParseError> {
1328 pair.clone()
1329 .into_inner()
1330 .next()
1331 .ok_or_else(|| Self::to_err(SpecificError::CouldNotMoveRight, &pair))
1332 }
1333
1334 pub fn parse_compound_assign_op(
1335 op_pair: &Pair<Rule>,
1336 ) -> Result<CompoundOperatorKind, ParseError> {
1337 assert_eq!(op_pair.as_rule(), Rule::compound_assign_op);
1338
1339 let kind = match Self::right_alternative(&op_pair)?.as_rule() {
1340 Rule::add_assign_op => CompoundOperatorKind::Add,
1341 Rule::sub_assign_op => CompoundOperatorKind::Sub,
1342 Rule::mul_assign_op => CompoundOperatorKind::Mul,
1343 Rule::div_assign_op => CompoundOperatorKind::Div,
1344 Rule::modulo_assign_op => CompoundOperatorKind::Modulo,
1345 _ => {
1346 return Err(Self::to_err(
1347 SpecificError::UnknownOperator(format!(
1348 "Found unexpected operator rule: {:?}",
1349 op_pair.as_rule()
1350 )),
1351 &op_pair,
1352 ));
1353 }
1354 };
1355
1356 Ok(kind)
1357 }
1358
1359 #[allow(clippy::too_many_lines)]
1360 fn parse_variable_definition(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1361 let mut inner = pair.clone().into_inner();
1362 let variable_item = Self::next_pair(&mut inner)?;
1363 let found_var = self.parse_variable_item(&variable_item)?;
1364
1365 let maybe_annotation = if let Some(peeked) = inner.peek() {
1366 if peeked.as_rule() == Rule::type_coerce {
1367 let type_coerce_pair = inner.next().unwrap();
1368 let mut type_inner = type_coerce_pair.clone().into_inner();
1369 let type_name_pair = type_inner.next().ok_or_else(|| {
1370 self.create_error_pair(SpecificError::MissingTypeName, &type_coerce_pair)
1371 })?;
1372 Some(self.parse_type(type_name_pair)?)
1373 } else {
1374 None
1375 }
1376 } else {
1377 None
1378 };
1379
1380 let rhs_expr = self.parse_mutable_or_immutable_expression(&Self::next_pair(&mut inner)?)?;
1381
1382 if maybe_annotation.is_some() || found_var.is_mutable.is_some() {
1383 Ok(self.create_expr(
1384 ExpressionKind::VariableDefinition(
1385 found_var,
1386 maybe_annotation,
1387 Box::from(rhs_expr),
1388 ),
1389 pair,
1390 ))
1391 } else {
1392 Ok(self.create_expr(
1393 ExpressionKind::VariableAssignment(found_var, Box::from(rhs_expr)),
1394 pair,
1395 ))
1396 }
1397 }
1398 fn parse_prefix(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1399 assert_eq!(pair.as_rule(), Rule::prefix);
1400 let _span = pair.as_span();
1401 let inner = Self::convert_into_iterator(pair);
1402 let mut expr = None;
1403 let mut prefix_ops = Vec::new();
1404
1405 for part in inner {
1406 match part.as_rule() {
1407 Rule::prefix_op | Rule::op_neg | Rule::op_not => {
1408 let op = self.parse_unary_operator(&part)?;
1409 prefix_ops.push(op);
1410 }
1411 _ => {
1412 expr = Some(self.parse_postfix_expression(&part)?);
1413 break;
1414 }
1415 }
1416 }
1417
1418 let mut final_expr = expr.ok_or_else(|| {
1419 self.create_error_pair(SpecificError::ExpectedExpressionAfterPrefixOperator, pair)
1420 })?;
1421
1422 for op in prefix_ops.into_iter().rev() {
1423 final_expr = self.create_expr(ExpressionKind::UnaryOp(op, Box::new(final_expr)), pair);
1424 }
1425
1426 Ok(final_expr)
1427 }
1428
1429 fn parse_binary_operator(&self, pair: &Pair<Rule>) -> Result<BinaryOperator, ParseError> {
1430 let op = match pair.as_rule() {
1431 Rule::prefix_op => self.next_inner_pair(pair)?,
1432 _ => pair.clone(),
1433 };
1434
1435 let kind = match op.as_rule() {
1436 Rule::op_add => BinaryOperatorKind::Add,
1437 Rule::op_sub => BinaryOperatorKind::Subtract,
1438 Rule::op_mul => BinaryOperatorKind::Multiply,
1439 Rule::op_div => BinaryOperatorKind::Divide,
1440 Rule::op_mod => BinaryOperatorKind::Modulo,
1441 Rule::op_eq => BinaryOperatorKind::Equal,
1442 Rule::op_neq => BinaryOperatorKind::NotEqual,
1443 Rule::op_lt => BinaryOperatorKind::LessThan,
1444 Rule::op_lte => BinaryOperatorKind::LessEqual,
1445 Rule::op_gt => BinaryOperatorKind::GreaterThan,
1446 Rule::op_gte => BinaryOperatorKind::GreaterEqual,
1447 Rule::op_and => BinaryOperatorKind::LogicalAnd,
1448 Rule::op_or => BinaryOperatorKind::LogicalOr,
1449 _ => {
1450 panic!("unknown operator")
1451 }
1452 };
1453
1454 Ok(BinaryOperator {
1455 kind,
1456 node: self.to_node(pair),
1457 })
1458 }
1459
1460 fn parse_unary_operator(&self, pair: &Pair<Rule>) -> Result<UnaryOperator, ParseError> {
1461 let op = match pair.as_rule() {
1462 Rule::prefix_op => &self.next_inner_pair(pair)?,
1463 _ => pair,
1464 };
1465
1466 let node = self.to_node(op);
1467 match op.as_rule() {
1468 Rule::op_neg => Ok(UnaryOperator::Negate(node)),
1469 Rule::op_not => Ok(UnaryOperator::Not(node)),
1470 _ => Err(self.create_error_pair(
1471 SpecificError::UnexpectedUnaryOperator(Self::pair_to_rule(op)),
1472 op,
1473 )),
1474 }
1475 }
1476
1477 fn parse_module_segments(&self, pair: Pair<Rule>) -> Vec<Node> {
1478 pair.into_inner()
1479 .filter_map(|segment| {
1480 if segment.as_rule() == Rule::identifier {
1481 Some(self.to_node(&segment))
1482 } else {
1483 None
1484 }
1485 })
1486 .collect()
1487 }
1488
1489 fn parse_qualified_type_identifier(
1490 &self,
1491 pair: &Pair<Rule>,
1492 ) -> Result<QualifiedTypeIdentifier, ParseError> {
1493 let mut inner_pairs = pair.clone().into_inner();
1494 let mut generic_types = Vec::new();
1495
1496 let first = inner_pairs.next().ok_or_else(|| {
1497 self.create_error_pair(
1498 SpecificError::ExpectedTypeIdentifier(Self::pair_to_rule(pair)),
1499 pair,
1500 )
1501 })?;
1502
1503 match first.as_rule() {
1504 Rule::module_segments => {
1505 let module_path = self.parse_module_segments(first.clone());
1506 let type_id = inner_pairs.next().ok_or_else(|| {
1507 self.create_error_pair(SpecificError::ExpectedTypeIdentifierAfterPath, &first)
1508 })?;
1509
1510 let type_identifier = self.parse_local_type_identifier(&type_id)?;
1511
1512 if let Some(generic_params) = inner_pairs.next() {
1514 if generic_params.as_rule() == Rule::generic_params {
1515 generic_types = self.parse_generic_params(&generic_params)?;
1516 }
1517 }
1518
1519 Ok(QualifiedTypeIdentifier::new_with_generics(
1520 type_identifier,
1521 module_path,
1522 generic_types,
1523 ))
1524 }
1525 Rule::type_identifier => {
1526 let type_identifier = LocalTypeIdentifier(self.to_node(&first));
1527
1528 if let Some(generic_params) = inner_pairs.next() {
1530 if generic_params.as_rule() == Rule::generic_params {
1531 generic_types = self.parse_generic_params(&generic_params)?;
1532 }
1533 }
1534
1535 Ok(QualifiedTypeIdentifier::new_with_generics(
1536 type_identifier,
1537 Vec::new(),
1538 generic_types,
1539 ))
1540 }
1541 _ => Err(self.create_error_pair(
1542 SpecificError::ExpectedTypeIdentifier(Self::pair_to_rule(&first)),
1543 &first,
1544 )),
1545 }
1546 }
1547
1548 fn parse_qualified_identifier(
1549 &self,
1550 pair: &Pair<Rule>,
1551 ) -> Result<QualifiedIdentifier, ParseError> {
1552 let mut inner_pairs = pair.clone().into_inner();
1553 let mut generic_types = Vec::new();
1554
1555 let first = inner_pairs
1556 .next()
1557 .ok_or_else(|| self.create_error_pair(SpecificError::ExpectedIdentifier, pair))?;
1558
1559 match first.as_rule() {
1560 Rule::module_segments => {
1561 let module_path = self.parse_module_segments(first.clone());
1562 let id = inner_pairs.next().ok_or_else(|| {
1563 self.create_error_pair(SpecificError::ExpectedIdentifierAfterPath, &first)
1564 })?;
1565
1566 let identifier = self.to_node(&id);
1567
1568 if let Some(generic_params) = inner_pairs.next() {
1570 if generic_params.as_rule() == Rule::generic_params {
1571 generic_types = self.parse_generic_params(&generic_params)?;
1572 }
1573 }
1574
1575 Ok(QualifiedIdentifier::new_with_generics(
1576 identifier,
1577 module_path,
1578 generic_types,
1579 ))
1580 }
1581 Rule::identifier => {
1582 let type_identifier = self.to_node(&first);
1583
1584 if let Some(generic_params) = inner_pairs.next() {
1586 if generic_params.as_rule() == Rule::generic_params {
1587 generic_types = self.parse_generic_params(&generic_params)?;
1588 }
1589 }
1590
1591 Ok(QualifiedIdentifier::new_with_generics(
1592 type_identifier,
1593 Vec::new(),
1594 generic_types,
1595 ))
1596 }
1597 _ => Err(self.create_error_pair(SpecificError::ExpectedIdentifier, &first)),
1598 }
1599 }
1600
1601 fn parse_qualified_identifier_expression(
1602 &self,
1603 pair: &Pair<Rule>,
1604 ) -> Result<Expression, ParseError> {
1605 let qualified_identifier = self.parse_qualified_identifier(pair)?;
1606 Ok(self.create_expr(
1607 ExpressionKind::IdentifierReference(qualified_identifier),
1608 pair,
1609 ))
1610 }
1611
1612 fn parse_generic_params(&self, pair: &Pair<Rule>) -> Result<Vec<Type>, ParseError> {
1613 let inner_pairs = pair.clone().into_inner();
1614 let mut generic_types = Vec::new();
1615
1616 for type_pair in inner_pairs {
1617 if type_pair.as_rule() == Rule::type_name {
1618 generic_types.push(self.parse_type(type_pair)?);
1619 }
1620 }
1621
1622 Ok(generic_types)
1623 }
1624
1625 fn parse_local_type_identifier_node(&self, pair: &Pair<Rule>) -> Result<Node, ParseError> {
1626 if pair.as_rule() != Rule::type_identifier {
1627 return Err(self.create_error_pair(
1628 SpecificError::ExpectedTypeIdentifier(format!("{:?}", pair.as_rule())),
1629 pair,
1630 ));
1631 }
1632 Ok(self.to_node(pair))
1633 }
1634
1635 fn parse_generic_type_variables(
1636 &self,
1637 pair: &Pair<Rule>,
1638 ) -> Result<Vec<TypeVariable>, ParseError> {
1639 assert_eq!(pair.as_rule(), Rule::generic_type_params);
1640 let mut type_params = Vec::new();
1641 for type_identifier_pair in Self::convert_into_iterator(pair) {
1642 if type_identifier_pair.as_rule() == Rule::type_identifier {
1643 type_params.push(TypeVariable(
1644 self.parse_local_type_identifier_node(&type_identifier_pair)?,
1645 ));
1646 } else {
1647 panic!("internal error generic type params")
1648 }
1649 }
1650 Ok(type_params)
1651 }
1652
1653 fn parse_local_type_identifier_with_optional_type_variables(
1654 &self,
1655 pair: &Pair<Rule>,
1656 ) -> Result<LocalTypeIdentifierWithOptionalTypeVariables, ParseError> {
1657 assert_eq!(pair.as_rule(), Rule::type_identifier_optional_type_params);
1658
1659 let mut inner = pair.clone().into_inner();
1660 let name = self.expect_local_type_identifier_next(&mut inner)?;
1661
1662 let type_variables = if let Some(generic_params_pair) = inner.peek() {
1663 if generic_params_pair.as_rule() == Rule::generic_type_params {
1665 let generic_params_pair = inner.next().unwrap(); self.parse_generic_type_variables(&generic_params_pair)?
1667 } else {
1668 Vec::new()
1669 }
1670 } else {
1671 Vec::new()
1672 };
1673
1674 Ok(LocalTypeIdentifierWithOptionalTypeVariables {
1675 name: name.0,
1676 type_variables,
1677 })
1678 }
1679
1680 fn parse_struct_fields_expressions<'a>(
1681 &self,
1682 field_list_pair: &Pair<Rule>,
1683 ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1684 let mut fields = Vec::new();
1685 let mut has_rest = false;
1686
1687 for field_pair in field_list_pair.clone().into_inner() {
1688 match field_pair.as_rule() {
1689 Rule::struct_field => {
1690 let mut field_inner = field_pair.into_inner();
1691 let ident = self.expect_field_label_next(&mut field_inner)?;
1692 let field_name = FieldName(ident.0);
1693 let field_value = self.parse_expression(&field_inner.next().unwrap())?;
1694
1695 fields.push(FieldExpression {
1696 field_name,
1697 expression: field_value,
1698 });
1699 }
1700 Rule::rest_fields => {
1701 has_rest = true;
1702 }
1703 _ => {
1704 return Err(
1705 self.create_error_pair(SpecificError::ExpectedFieldOrRest, &field_pair)
1706 );
1707 }
1708 }
1709 }
1710
1711 Ok((fields, has_rest))
1712 }
1713
1714 fn parse_anonymous_struct_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1715 let (fields, has_rest) = self.parse_anonymous_struct_literal_fields(&pair)?;
1716 Ok(self.create_expr(
1717 ExpressionKind::AnonymousStructLiteral(fields, has_rest),
1718 pair,
1719 ))
1720 }
1721
1722 fn parse_anonymous_struct_literal_fields(
1723 &self,
1724 pair: &Pair<Rule>,
1725 ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1726 assert_eq!(pair.as_rule(), Rule::anonymous_struct_literal);
1727 let mut inner = Self::convert_into_iterator(pair);
1728 let (field_expressions, detected_rest) =
1729 self.parse_struct_fields_expressions(&inner.next().unwrap())?;
1730
1731 Ok((field_expressions, detected_rest))
1732 }
1733
1734 fn parse_struct_literal_optional_fields(
1735 &self,
1736 pair: &Pair<Rule>,
1737 ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1738 assert_eq!(pair.as_rule(), Rule::struct_literal_optional_field_list);
1739 let mut inner = Self::convert_into_iterator(pair);
1740 let (field_expressions, detected_rest) = if let Some(field_list) = inner.next() {
1741 self.parse_struct_fields_expressions(&field_list)?
1742 } else {
1743 (vec![], false)
1744 };
1745
1746 Ok((field_expressions, detected_rest))
1747 }
1748
1749 fn parse_struct_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1750 let mut inner = Self::convert_into_iterator(pair);
1751
1752 let type_pair = inner.next().unwrap();
1753
1754 let struct_name = self.parse_qualified_type_identifier(&type_pair)?;
1755
1756 let anon_fields = inner.next().unwrap();
1757
1758 let (fields, has_rest) = self.parse_struct_literal_optional_fields(&anon_fields)?;
1759
1760 Ok(self.create_expr(
1761 ExpressionKind::NamedStructLiteral(struct_name, fields, has_rest),
1762 pair,
1763 ))
1764 }
1765
1766 fn parse_static_member_reference(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1767 let mut inner = pair.clone().into_inner();
1768
1769 let type_identifier = self.parse_qualified_type_identifier(&inner.next().unwrap())?;
1770 let member_name = self.expect_identifier_next(&mut inner)?;
1771
1772 Ok(self.create_expr(
1773 ExpressionKind::StaticMemberFunctionReference(type_identifier, member_name.0),
1774 pair,
1775 ))
1776 }
1777
1778 fn parse_constant_reference(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1779 assert_eq!(pair.as_rule(), Rule::constant_reference);
1780 let mut inner_pairs = pair.clone().into_inner();
1781
1782 let mut first = inner_pairs.next().unwrap();
1783
1784 let module_path = if first.as_rule() == Rule::module_segments {
1785 let path = self.parse_module_segments(first.clone());
1786 first = inner_pairs.next().unwrap();
1787 Some(ModulePath(path))
1788 } else {
1789 None
1790 };
1791
1792 let identifier = QualifiedConstantIdentifier::new(self.to_node(&first), module_path);
1793
1794 Ok(self.create_expr(ExpressionKind::ConstantReference(identifier), pair))
1795 }
1796
1797 fn parse_term(&self, pair2: &Pair<Rule>) -> Result<Expression, ParseError> {
1798 assert_eq!(pair2.as_rule(), Rule::term);
1799 let sub = &Self::right_alternative(pair2)?;
1800 match sub.as_rule() {
1801 Rule::qualified_identifier => self.parse_qualified_identifier_expression(sub),
1802 Rule::static_member_reference => self.parse_static_member_reference(sub),
1803
1804 Rule::enum_literal => {
1805 Ok(self.create_expr(ExpressionKind::Literal(self.parse_enum_literal(sub)?), sub))
1806 }
1807 Rule::constant_reference => self.parse_constant_reference(sub),
1808 Rule::parenthesized => {
1809 let inner = self.next_inner_pair(sub)?;
1810 self.parse_expression(&inner)
1811 }
1812 Rule::basic_literal => {
1813 let (literal, node) = self.parse_basic_literal(sub)?;
1814 Ok(self.create_expr_span(ExpressionKind::Literal(literal), node))
1815 }
1816 Rule::struct_literal => self.parse_struct_literal(sub),
1817 Rule::anonymous_struct_literal => self.parse_anonymous_struct_literal(sub),
1818
1819 Rule::interpolated_string => self.parse_interpolated_string(sub),
1820
1821 _ => {
1822 Err(self
1823 .create_error_pair(SpecificError::UnknownTerm(Self::pair_to_rule(sub)), sub))
1824 }
1825 }
1826 }
1827
1828 fn parse_interpolated_string(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1829 let mut parts = Vec::new();
1830
1831 for part_pair in Self::convert_into_iterator(pair) {
1832 match part_pair.as_rule() {
1833 Rule::text => {
1834 parts.push(StringPart::Literal(
1835 self.to_node(&part_pair),
1836 self.unescape_string(&part_pair, false)?,
1837 ));
1838 }
1839 Rule::interpolation => {
1840 let inner = self.next_inner_pair(&part_pair.clone())?;
1841 let expr = match inner.as_rule() {
1842 Rule::expression => self.parse_expression(&inner)?,
1843 _ => {
1844 return Err(self.create_error_pair(
1845 SpecificError::ExpectedExpressionInInterpolation,
1846 &inner,
1847 ));
1848 }
1849 };
1850
1851 let format = match Self::convert_into_iterator(&part_pair).nth(1) {
1852 Some(fmt) => {
1853 if fmt.as_rule() == Rule::format_specifier {
1854 Some(self.parse_format_specifier(&fmt)?)
1855 } else {
1856 None
1857 }
1858 }
1859 _ => None,
1860 };
1861
1862 parts.push(StringPart::Interpolation(Box::new(expr), format));
1863 }
1864 _ => {
1865 return Err(self.create_error_pair(
1866 SpecificError::UnexpectedRuleInInterpolation,
1867 &part_pair,
1868 ));
1869 }
1870 }
1871 }
1872
1873 Ok(self.create_expr(ExpressionKind::InterpolatedString(parts), pair))
1874 }
1875
1876 fn parse_format_specifier(&self, pair: &Pair<Rule>) -> Result<FormatSpecifier, ParseError> {
1877 let node = self.to_node(pair);
1878 match pair.as_str() {
1879 "x" => Ok(FormatSpecifier::LowerHex(node)),
1880 "X" => Ok(FormatSpecifier::UpperHex(node)),
1881 "b" => Ok(FormatSpecifier::Binary(node)),
1882 "f" => Ok(FormatSpecifier::Float(node)),
1883 s if s.starts_with("..") => {
1884 let precision: u32 = s[2..s.len() - 1].parse().map_err(|_| {
1885 self.create_error_pair(SpecificError::InvalidPrecisionValue, pair)
1886 })?;
1887 let typ = match s.chars().last().unwrap() {
1888 'f' => PrecisionType::Float(node),
1889 's' => PrecisionType::String(node),
1890 _ => {
1891 return Err(
1892 self.create_error_pair(SpecificError::InvalidPrecisionType, pair)
1893 )?;
1894 }
1895 };
1896 Ok(FormatSpecifier::Precision(
1897 precision,
1898 self.to_node(&pair),
1899 typ,
1900 ))
1901 }
1902 _ => Err(self.create_error_pair(SpecificError::InvalidFormatSpecifier, pair)),
1903 }
1904 }
1905
1906 fn parse_enum_literal(&self, pair: &Pair<Rule>) -> Result<LiteralKind, ParseError> {
1907 let mut inner = Self::convert_into_iterator(pair);
1908
1909 let enum_type = self.parse_qualified_type_identifier(&inner.next().unwrap())?;
1911
1912 let variant_pair = Self::expect_next(&mut inner, Rule::type_identifier)?;
1914 let variant_type_identifier = LocalTypeIdentifier::new(self.to_node(&variant_pair));
1915
1916 let enum_variant_literal = match inner.next() {
1918 Some(fields_pair) => match fields_pair.as_rule() {
1919 Rule::struct_literal_optional_field_list => {
1920 let (field_expressions, detected_rest) =
1921 self.parse_struct_literal_optional_fields(&fields_pair)?;
1922 EnumVariantLiteral::Struct(
1923 enum_type,
1924 variant_type_identifier,
1925 field_expressions,
1926 detected_rest,
1927 )
1928 }
1929 Rule::tuple_fields => {
1930 let mut expressions = vec![];
1931 for field in Self::convert_into_iterator(&fields_pair) {
1932 let field_value = self.parse_expression(&field)?;
1933 expressions.push(field_value);
1934 }
1935 EnumVariantLiteral::Tuple(enum_type, variant_type_identifier, expressions)
1936 }
1937 _ => {
1938 error!("{:?}, {}", fields_pair.as_rule(), "strange");
1939 return Err(
1940 self.create_error_pair(SpecificError::UnexpectedVariantField, &fields_pair)
1941 );
1942 }
1943 },
1944 _ => EnumVariantLiteral::Simple(enum_type, variant_type_identifier),
1945 };
1946
1947 Ok(LiteralKind::EnumVariant(enum_variant_literal))
1948 }
1949
1950 fn unescape_unicode(
1951 &self,
1952 chars: &mut Peekable<Chars>,
1953 octets: &mut Vec<u8>,
1954 pair: &Pair<Rule>,
1955 ) -> Result<(), ParseError> {
1956 match chars.next() {
1957 Some('(') => {
1958 let mut hex_digits = String::new();
1959
1960 while let Some(&c) = chars.peek() {
1961 if c == ')' {
1962 break;
1963 }
1964 if c.is_ascii_hexdigit() && hex_digits.len() < 6 {
1965 hex_digits.push(c);
1966 chars.next();
1967 } else {
1968 return Err(
1969 self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
1970 );
1971 }
1972 }
1973
1974 match chars.next() {
1975 Some(')') => {
1976 if hex_digits.is_empty() {
1977 return Err(
1978 self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
1979 );
1980 }
1981
1982 let code = u32::from_str_radix(&hex_digits, 16).map_err(|_| {
1983 self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
1984 })?;
1985
1986 if code > 0x0010_FFFF {
1987 return Err(
1988 self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
1989 );
1990 }
1991
1992 if let Some(c) = std::char::from_u32(code) {
1993 let mut buf = [0; 4];
1994 let encoded = c.encode_utf8(&mut buf);
1995 octets.extend_from_slice(encoded.as_bytes());
1996 } else {
1997 return Err(
1998 self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
1999 );
2000 }
2001 }
2002 _ => {
2003 return Err(
2004 self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair)
2005 );
2006 }
2007 }
2008 }
2009 _ => {
2010 return Err(self.create_error_pair(SpecificError::InvalidUnicodeEscape, pair));
2011 }
2012 }
2013 Ok(())
2014 }
2015
2016 fn unescape_hex(
2017 &self,
2018 chars: &mut Peekable<Chars>,
2019 pair: &Pair<Rule>,
2020 ) -> Result<u8, ParseError> {
2021 let mut hex_digits = String::new();
2022 for _ in 0..2 {
2023 match chars.next() {
2024 Some(h) if h.is_ascii_hexdigit() => {
2025 hex_digits.push(h);
2026 }
2027 _ => {
2028 return Err(self.create_error_pair(SpecificError::InvalidHexEscape, pair));
2029 }
2030 }
2031 }
2032 u8::from_str_radix(&hex_digits, 16)
2033 .map_err(|_| self.create_error_pair(SpecificError::InvalidHexEscape, pair))
2034 }
2035
2036 fn unescape_string(&self, pair: &Pair<Rule>, is_literal: bool) -> Result<String, ParseError> {
2037 let mut octets = Vec::new();
2038
2039 let raw = if is_literal {
2040 &pair.as_str()[1..pair.as_str().len() - 1]
2041 } else {
2042 pair.as_str()
2043 };
2044
2045 let mut chars = raw.chars().peekable();
2046
2047 while let Some(ch) = chars.next() {
2048 if ch == '\\' {
2049 let Some(next_ch) = chars.next() else {
2050 return Err(
2051 self.create_error_pair(SpecificError::UnfinishedEscapeSequence, pair)
2052 );
2053 };
2054 match next_ch {
2055 'n' => {
2056 octets.push(b'\n');
2057 }
2058 't' => {
2059 octets.push(b'\t');
2060 }
2061 '\\' => {
2062 octets.push(b'\\');
2063 }
2064 '"' => {
2065 octets.push(b'"');
2066 }
2067 '\'' => {
2068 octets.push(b'\'');
2069 }
2070 'x' => {
2072 let code = self.unescape_hex(&mut chars, pair)?;
2073 octets.push(code);
2074 }
2075 'u' => {
2077 self.unescape_unicode(&mut chars, &mut octets, pair)?;
2078 }
2079
2080 other => {
2081 return Err(self.create_error_pair(
2082 SpecificError::UnknownEscapeCharacter(other),
2083 pair,
2084 ));
2085 }
2086 }
2087 } else {
2088 let mut buf = [0; 4];
2089 let utf8_bytes = ch.encode_utf8(&mut buf);
2090 octets.extend_from_slice(utf8_bytes.as_bytes());
2091 }
2092 }
2093
2094 let output = String::from_utf8(octets)
2095 .map_err(|_| self.create_error_pair(SpecificError::InvalidUtf8Sequence, pair))?;
2096
2097 Ok(output)
2098 }
2099
2100 fn parse_basic_literal(&self, pair: &Pair<Rule>) -> Result<(LiteralKind, Node), ParseError> {
2101 assert_eq!(pair.as_rule(), Rule::basic_literal);
2102 let inner = self.next_inner_pair(pair)?;
2103 let literal_kind = match inner.as_rule() {
2104 Rule::int_lit => LiteralKind::Int,
2105 Rule::float_lit => LiteralKind::Float,
2106 Rule::string_lit => {
2107 let processed_string = self.unescape_string(&inner, true)?;
2108 LiteralKind::String(processed_string)
2109 }
2110 Rule::bool_lit => LiteralKind::Bool,
2111 Rule::none_lit => LiteralKind::None,
2112 Rule::tuple_lit => {
2113 let mut expressions = Vec::new();
2114 for expr_pair in Self::convert_into_iterator(&inner) {
2115 expressions.push(self.parse_expression(&expr_pair)?);
2116 }
2117 LiteralKind::Tuple(expressions)
2118 }
2119 _ => return Err(self.create_error_pair(SpecificError::UnknownLiteral, &inner)),
2120 };
2121 Ok((literal_kind, self.to_node(&inner)))
2122 }
2123
2124 fn parse_array_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2125 let mut elements = Vec::new();
2126 for element in Self::convert_into_iterator(pair) {
2127 elements.push(self.parse_expression(&element)?);
2128 }
2129 Ok(self.create_expr(ExpressionKind::Literal(LiteralKind::Slice(elements)), pair))
2130 }
2131
2132 fn parse_map_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2133 let mut entries = Vec::new();
2134
2135 for entry_pair in Self::convert_into_iterator(pair) {
2136 if entry_pair.as_rule() == Rule::map_entry {
2137 let mut entry_inner = Self::convert_into_iterator(&entry_pair);
2138 let key = self.parse_expression(&Self::next_pair(&mut entry_inner)?)?;
2139 let value = self.parse_expression(&Self::next_pair(&mut entry_inner)?)?;
2140 entries.push((key, value));
2141 }
2142 }
2143
2144 Ok(self.create_expr(
2145 ExpressionKind::Literal(LiteralKind::SlicePair(entries)),
2146 pair,
2147 ))
2148 }
2149
2150 fn parse_mutable_or_immutable_expression(
2151 &self,
2152 pair: &Pair<Rule>,
2153 ) -> Result<MutableOrImmutableExpression, ParseError> {
2154 let mut inner = pair.clone().into_inner();
2157 let first = Self::next_pair(&mut inner)?;
2158 match first.as_rule() {
2159 Rule::lvalue => {
2160 let mut lvalue_inner = first.into_inner();
2161 let mut_kw = Self::next_pair(&mut lvalue_inner)?;
2162 let postfix = Self::next_pair(&mut lvalue_inner)?;
2163 let expr = self.parse_postfix_expression(&postfix)?;
2164 Ok(MutableOrImmutableExpression {
2165 is_mutable: Some(self.to_node(&mut_kw)),
2166 expression: expr,
2167 })
2168 }
2169 Rule::expression => {
2170 let expr = self.parse_expression(&first)?;
2172 Ok(MutableOrImmutableExpression {
2173 is_mutable: None,
2174 expression: expr,
2175 })
2176 }
2177 _ => {
2178 Err(self
2179 .create_error_pair(SpecificError::UnexpectedTokenInMutableExpression, &first))
2180 }
2181 }
2182 }
2183
2184 fn parse_function_call_postfix(
2185 &self,
2186 pair: &Pair<Rule>,
2187 ) -> Result<Vec<MutableOrImmutableExpression>, ParseError> {
2188 assert_eq!(pair.as_rule(), Rule::function_call_postfix);
2189 let mut inner = pair.clone().into_inner();
2190 self.parse_function_call_arguments(&Self::next_pair(&mut inner)?)
2191 }
2192
2193 fn parse_function_call_arguments(
2194 &self,
2195 pair: &Pair<Rule>,
2196 ) -> Result<Vec<MutableOrImmutableExpression>, ParseError> {
2197 assert_eq!(pair.as_rule(), Rule::function_call_args);
2198 let inner = pair.clone().into_inner();
2199 let mut args = Vec::new();
2200
2201 for arg_pair in inner {
2203 if arg_pair.as_rule() == Rule::mut_expression {
2204 let expr = self.parse_mutable_or_immutable_expression(&arg_pair)?;
2207 args.push(expr);
2208 } else {
2209 return Err(
2210 self.create_error_pair(SpecificError::UnexpectedTokenInFunctionCall, &arg_pair)
2211 );
2212 }
2213 }
2214
2215 Ok(args)
2216 }
2217
2218 #[allow(clippy::too_many_lines)]
2219 fn parse_type(&self, pair: Pair<Rule>) -> Result<Type, ParseError> {
2220 match pair.as_rule() {
2221 Rule::type_name => {
2222 let mut inner = pair.clone().into_inner();
2223 let base_type = if let Some(inner_pair) = inner.next() {
2224 self.parse_type(inner_pair)?
2225 } else {
2226 panic!("shouldn't get to here")
2227 };
2228
2229 let optional_marker = inner
2230 .find(|p| p.as_rule() == Rule::optional_marker)
2231 .map(|marker_pair| self.to_node(&marker_pair));
2232 if let Some(found_optional_marker) = optional_marker {
2233 Ok(Type::Optional(Box::new(base_type), found_optional_marker))
2234 } else {
2235 Ok(base_type)
2236 }
2237 }
2238
2239 Rule::base_type => {
2240 let mut inner = pair.into_inner();
2241 let first = inner.next().unwrap();
2242 let base_type = self.parse_type(first)?;
2243
2244 Ok(base_type)
2245 }
2246 Rule::function_type => {
2247 let mut function_inner = pair.into_inner();
2248
2249 let param_types = if let Some(params) = function_inner
2251 .next()
2252 .filter(|p| p.as_rule() == Rule::function_params)
2253 {
2254 params
2255 .into_inner()
2256 .map(|param| {
2257 Ok(TypeForParameter {
2258 ast_type: self.parse_type(param).unwrap(),
2259 is_mutable: false,
2260 })
2261 })
2262 .collect::<Result<Vec<_>, ParseError>>()?
2263 } else {
2264 Vec::new()
2265 };
2266
2267 let return_type = self.parse_type(function_inner.next().unwrap())?;
2269
2270 Ok(Type::Function(param_types, Box::new(return_type)))
2271 }
2272
2273 Rule::qualified_type_identifier => {
2274 let qualified_id = self.parse_qualified_type_identifier(&pair)?;
2275 Ok(Type::Named(qualified_id))
2276 }
2277 Rule::tuple_type => {
2278 let elements = self.parse_tuple_type_elements(&pair)?;
2279 Ok(Type::Tuple(elements))
2280 }
2281 Rule::slice_pair_type => {
2282 let mut inner = pair.into_inner();
2283 let key_type = self.parse_type(Self::next_pair(&mut inner)?)?;
2284 let value_type = self.parse_type(Self::next_pair(&mut inner)?)?;
2285 Ok(Type::SlicePair(Box::new(key_type), Box::new(value_type)))
2286 }
2287
2288 Rule::slice_type => {
2289 let inner = self.next_inner_pair(&pair)?;
2290 let element_type = self.parse_type(inner)?;
2291 Ok(Type::Slice(Box::new(element_type)))
2292 }
2293
2294 Rule::struct_type => {
2295 let element_type = self.parse_struct_type(&pair)?;
2296 Ok(Type::AnonymousStruct(element_type))
2297 }
2298
2299 _ => Err(self.create_error_pair(SpecificError::UnexpectedTypeRule, &pair)),
2300 }
2301 }
2302
2303 #[allow(unused)] fn parse_local_type_identifier(
2305 &self,
2306 pair: &Pair<Rule>,
2307 ) -> Result<LocalTypeIdentifier, ParseError> {
2308 if pair.as_rule() != Rule::type_identifier {
2309 return Err(self.create_error_pair(
2310 SpecificError::ExpectedTypeIdentifier(format!("{:?}", pair.as_rule())),
2311 pair,
2312 ));
2313 }
2314 Ok(LocalTypeIdentifier::new(self.to_node(pair)))
2315 }
2316
2317 fn parse_local_type_identifier_next<'a>(
2318 &self,
2319 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
2320 ) -> Result<LocalTypeIdentifier, ParseError> {
2321 let pair = Self::next_pair(pairs)?;
2322 if pair.as_rule() != Rule::type_identifier {
2323 return Err(self.create_error_pair(
2324 SpecificError::ExpectedLocalTypeIdentifier(Self::pair_to_rule(&pair)),
2325 &pair,
2326 ));
2327 }
2328 Ok(LocalTypeIdentifier::new(self.to_node(&pair)))
2329 }
2330
2331 fn parse_enum_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
2332 let mut inner = Self::convert_into_iterator(pair);
2333
2334 let name_with_optional_type_params =
2335 self.parse_local_type_identifier_with_optional_type_variables(&inner.next().unwrap())?;
2336
2337 let mut variants = Vec::new();
2338
2339 if let Some(variants_pair) = inner.next() {
2340 if variants_pair.as_rule() == Rule::enum_variants {
2341 for variant_pair in Self::convert_into_iterator(&variants_pair) {
2342 if variant_pair.as_rule() == Rule::enum_variant {
2343 let variant =
2344 self.parse_enum_variant(&self.next_inner_pair(&variant_pair)?)?;
2345
2346 variants.push(variant);
2347 }
2348 }
2349 }
2350 }
2351
2352 Ok(Definition::EnumDef(
2353 name_with_optional_type_params,
2354 variants,
2355 ))
2356 }
2357
2358 fn parse_enum_variant(&self, pair: &Pair<Rule>) -> Result<EnumVariantType, ParseError> {
2359 let enum_variant = match pair.as_rule() {
2360 Rule::simple_variant => EnumVariantType::Simple(self.to_node(pair)),
2361 Rule::tuple_variant => {
2362 let mut inner = Self::convert_into_iterator(pair);
2363 let name = self.expect_local_type_identifier_next(&mut inner)?;
2364
2365 let tuple_elements = self.parse_tuple_type_elements(&inner.next().unwrap())?;
2366
2367 EnumVariantType::Tuple(name.0, tuple_elements)
2368 }
2369 Rule::struct_variant => {
2370 let mut inner = Self::convert_into_iterator(pair);
2371 let name = self.expect_local_type_identifier_next(&mut inner)?;
2372
2373 let struct_type = self.parse_struct_type(&inner.next().unwrap())?;
2374 EnumVariantType::Struct(name.0, struct_type)
2375 }
2376 _ => {
2377 return Err(self.create_error_pair(
2378 SpecificError::UnknownEnumVariant(Self::pair_to_rule(pair)),
2379 pair,
2380 ));
2381 }
2382 };
2383
2384 Ok(enum_variant)
2385 }
2386
2387 fn parse_match_expr(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2388 let mut inner = Self::convert_into_iterator(pair);
2389 let value = self.parse_mutable_or_immutable_expression(&Self::next_pair(&mut inner)?)?;
2390 let arms_pair = Self::next_pair(&mut inner)?;
2391 let mut arms = Vec::new();
2392
2393 for arm_pair in Self::convert_into_iterator(&arms_pair) {
2394 if arm_pair.as_rule() == Rule::match_arm {
2395 let mut arm_inner = Self::convert_into_iterator(&arm_pair);
2396 let pattern = self.parse_match_pattern(&Self::next_pair(&mut arm_inner)?)?;
2397
2398 let expr = match Self::next_pair(&mut arm_inner)? {
2400 block if block.as_rule() == Rule::block => self.parse_block(&block)?,
2401 expr => self.parse_expression(&expr)?,
2402 };
2403
2404 arms.push(MatchArm {
2405 pattern,
2406 expression: expr,
2407 });
2408 }
2409 }
2410
2411 if arms.is_empty() {
2412 return Err(self.create_error_pair(SpecificError::MustHaveAtLeastOneArm, pair));
2413 }
2414
2415 Ok(self.create_expr(ExpressionKind::Match(Box::new(value), arms), pair))
2416 }
2417
2418 fn parse_match_pattern(&self, pair: &Pair<Rule>) -> Result<Pattern, ParseError> {
2419 let mut inner = Self::convert_into_iterator(pair);
2420 let pattern_inside = inner.next().expect("should have inner");
2421 match pattern_inside.as_rule() {
2422 Rule::normal_pattern => {
2423 let (match_pattern, pattern_node) =
2424 self.parse_normal_match_pattern(&pattern_inside)?;
2425 let inner_pairs: Vec<_> = pattern_inside.clone().into_inner().collect();
2426 let has_guard = inner_pairs
2427 .get(1)
2428 .map(|p| p.as_rule() == Rule::guard_clause)
2429 .unwrap_or(false);
2430
2431 let guard_clause = if has_guard {
2432 Some(self.parse_guard_clause(&inner_pairs[1])?)
2433 } else {
2434 None
2435 };
2436 Ok(Pattern::NormalPattern(
2437 pattern_node,
2438 match_pattern,
2439 guard_clause,
2440 ))
2441 }
2442 Rule::wildcard_pattern => Ok(Pattern::Wildcard(self.to_node(pair))),
2443 _ => Err(self.create_error_pair(SpecificError::MustHaveAtLeastOneArm, pair)),
2444 }
2445 }
2446
2447 fn parse_guard_clause(&self, pair: &Pair<Rule>) -> Result<GuardClause, ParseError> {
2448 let inner = Self::right_alternative(&pair)?;
2449 let clause = match inner.as_rule() {
2450 Rule::wildcard_pattern => GuardClause::Wildcard(Self::node_ex(&pair)),
2451 Rule::expression => {
2452 let mut iterator = inner.into_inner();
2453 let result = self.parse_expression(&Self::next_pair(&mut iterator)?)?;
2454 GuardClause::Expression(result)
2455 }
2456 _ => {
2457 return Err(Self::to_err(
2458 SpecificError::UnknownExpr("guard_clause".to_string()),
2459 &pair,
2460 ))?;
2461 }
2462 };
2463
2464 Ok(clause)
2465 }
2466
2467 fn parse_guard_expr_list(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2468 let mut guard_exprs = Vec::new();
2469
2470 for expr_pair in Self::convert_into_iterator(pair) {
2471 match expr_pair.as_rule() {
2472 Rule::guard_item => {
2473 let mut guard_inner = Self::convert_into_iterator(&expr_pair);
2474 let guard_clause = Self::next_pair(&mut guard_inner)?;
2475 let condition = self.parse_guard_clause(&guard_clause)?;
2476 let result = self.parse_expression(&Self::next_pair(&mut guard_inner)?)?;
2477 guard_exprs.push(GuardExpr {
2478 clause: condition,
2479 result,
2480 });
2481 }
2482
2483 _ => {
2484 panic!("Unexpected rule: {:?}", expr_pair.as_rule());
2485 }
2486 }
2487 }
2488
2489 Ok(self.create_expr(ExpressionKind::Guard(guard_exprs), pair))
2490 }
2491
2492 fn parse_normal_match_pattern(
2493 &self,
2494 pair: &Pair<Rule>,
2495 ) -> Result<(NormalPattern, Node), ParseError> {
2496 let mut inner = Self::convert_into_iterator(pair);
2497 let pattern = inner.next().expect("should have inner");
2498
2499 match pattern.as_rule() {
2500 Rule::pattern => {
2501 let mut pattern_inner = Self::convert_into_iterator(&pattern);
2502 let pattern_type = pattern_inner.next().expect("should have inner");
2503
2504 match pattern_type.as_rule() {
2505 Rule::enum_pattern => {
2506 let mut inner = Self::convert_into_iterator(&pattern_type);
2507 let variant = self.expect_local_type_identifier_next(&mut inner)?;
2508 let elements = inner
2509 .next()
2510 .map(|p| self.parse_pattern_list(&p))
2511 .transpose()?;
2512 Ok((
2513 NormalPattern::EnumPattern(variant.0, elements),
2514 self.to_node(&pattern),
2515 ))
2516 }
2517 Rule::pattern_list => {
2518 let elements = self.parse_pattern_list(&pattern_type)?;
2519 Ok((NormalPattern::PatternList(elements), self.to_node(&pattern)))
2520 }
2521 Rule::basic_literal => {
2522 let (literal, node) = self.parse_basic_literal(&pattern_type)?;
2523 Ok((NormalPattern::Literal(literal), node))
2524 }
2525 _ => {
2526 Err(self.create_error_pair(SpecificError::UnknownMatchType, &pattern_type))
2527 }
2528 }
2529 }
2530 _ => Err(self.create_error_pair(SpecificError::UnknownMatchType, &pattern)),
2531 }
2532 }
2533
2534 fn parse_pattern_list(&self, pair: &Pair<Rule>) -> Result<Vec<PatternElement>, ParseError> {
2535 let mut elements = Vec::new();
2536 for item in Self::convert_into_iterator(pair) {
2537 match item.as_rule() {
2538 Rule::pattern_field => {
2539 let inner_pair = item.clone().into_inner().next().unwrap();
2540 let maybe_mut_identifier = self.parse_maybe_mut_identifier(&inner_pair)?;
2541 if inner_pair.as_str() == "_" {
2542 elements.push(PatternElement::Wildcard(self.to_node(&item)));
2543 } else {
2544 elements.push(PatternElement::Variable(maybe_mut_identifier));
2545 }
2546 }
2547 Rule::expression => {
2548 elements.push(PatternElement::Expression(self.parse_expression(&item)?));
2549 }
2550 _ => {
2551 return Err(self.create_error_pair(
2552 SpecificError::UnexpectedPatternListElement(Self::pair_to_rule(&item)),
2553 &item,
2554 ));
2555 }
2556 }
2557 }
2558 Ok(elements)
2559 }
2560
2561 fn to_node(&self, pair: &Pair<Rule>) -> Node {
2562 let pair_span = pair.as_span();
2563 let span = SpanWithoutFileId {
2564 offset: pair_span.start() as u32,
2565 length: (pair_span.end() - pair_span.start()) as u16,
2566 };
2567
2568 Node { span }
2569 }
2570
2571 fn node_ex(pair: &Pair<Rule>) -> Node {
2572 let pair_span = pair.as_span();
2573 let span = SpanWithoutFileId {
2574 offset: pair_span.start() as u32,
2575 length: (pair_span.end() - pair_span.start()) as u16,
2576 };
2577
2578 Node { span }
2579 }
2580
2581 fn to_span(&self, pest_span: pest::Span) -> SpanWithoutFileId {
2582 SpanWithoutFileId {
2583 offset: pest_span.start() as u32,
2584 length: (pest_span.end() - pest_span.start()) as u16,
2585 }
2586 }
2587
2588 fn span(pest_span: pest::Span) -> SpanWithoutFileId {
2589 SpanWithoutFileId {
2590 offset: pest_span.start() as u32,
2591 length: (pest_span.end() - pest_span.start()) as u16,
2592 }
2593 }
2594
2595 fn create_expr(&self, kind: ExpressionKind, pair: &Pair<Rule>) -> Expression {
2596 self.create_expr_span(kind, self.to_node(pair))
2597 }
2598
2599 fn create_expr_span(&self, kind: ExpressionKind, node: Node) -> Expression {
2600 Expression { kind, node }
2602 }
2603
2604 fn parse_multiplication(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2605 let mut inner = pair.clone().into_inner();
2606 let mut expr = self.parse_prefix(&inner.next().unwrap())?;
2607 while let Some(op) = inner.next() {
2608 let operator = self.parse_binary_operator(&op)?; let right = self.parse_prefix(&inner.next().unwrap())?;
2611 expr = self.create_expr(
2612 ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2613 pair,
2614 );
2615 }
2616 Ok(expr)
2617 }
2618
2619 fn parse_addition(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2620 let mut inner = pair.clone().into_inner();
2621 let mut expr = self.parse_multiplication(&inner.next().unwrap())?;
2622 while let Some(op) = inner.next() {
2623 let operator = self.parse_binary_operator(&op)?; let right = self.parse_multiplication(&inner.next().unwrap())?;
2625 expr = self.create_expr(
2626 ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2627 pair,
2628 );
2629 }
2630 Ok(expr)
2631 }
2632
2633 fn parse_comparison(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2634 let mut inner = pair.clone().into_inner();
2635 let mut expr = self.parse_addition(&inner.next().unwrap())?;
2636 while let Some(op) = inner.next() {
2637 let operator = self.parse_binary_operator(&op)?; let right = self.parse_addition(&inner.next().unwrap())?;
2639 expr = self.create_expr(
2640 ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2641 pair,
2642 );
2643 }
2644 Ok(expr)
2645 }
2646
2647 fn parse_range(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2648 let mut inner = pair.clone().into_inner();
2649 let left = self.parse_comparison(&inner.next().unwrap())?;
2650 if let Some(op) = inner.next() {
2651 let right = self.parse_comparison(&inner.next().unwrap())?;
2652 match op.as_rule() {
2653 Rule::exclusive_range_op => {
2654 return Ok(self.create_expr(
2655 ExpressionKind::Range(
2656 Box::new(left),
2657 Box::new(right),
2658 RangeMode::Exclusive,
2659 ),
2660 pair,
2661 ));
2662 }
2663 Rule::inclusive_range_op => {
2664 return Ok(self.create_expr(
2665 ExpressionKind::Range(
2666 Box::new(left),
2667 Box::new(right),
2668 RangeMode::Inclusive,
2669 ),
2670 pair,
2671 ));
2672 }
2673 _ => {}
2674 }
2675 let operator = self.parse_binary_operator(&op)?; Ok(self.create_expr(
2677 ExpressionKind::BinaryOp(Box::new(left), operator, Box::new(right)),
2678 pair,
2679 ))
2680 } else {
2681 Ok(left)
2682 }
2683 }
2684
2685 fn parse_logical(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
2686 let mut inner = pair.clone().into_inner();
2687 let mut expr = self.parse_range(&inner.next().unwrap())?;
2688 while let Some(op) = inner.next() {
2689 let operator = self.parse_binary_operator(&op)?; let right = self.parse_range(&inner.next().unwrap())?;
2691 expr = self.create_expr(
2692 ExpressionKind::BinaryOp(Box::new(expr), operator, Box::new(right)),
2693 pair,
2694 );
2695 }
2696 Ok(expr)
2697 }
2698}