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