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, LocalTypeIdentifierWithOptionalTypeVariables, Mod,
17 NamedStructDef, PatternElement, QualifiedIdentifier, RangeMode, SpanWithoutFileId,
18 StructTypeField, TypeForParameter, TypeVariable, VariableBinding, prelude::*,
19};
20use swamp_script_ast::{Function, WhenBinding};
21use swamp_script_ast::{LiteralKind, MutableOrImmutableExpression};
22use swamp_script_ast::{Postfix, PostfixChain};
23
24pub struct ParseResult<'a> {
25 #[allow(dead_code)]
26 script: String, pairs: pest::iterators::Pairs<'a, Rule>,
28}
29
30pub struct GeneralError {
31 pub description: String,
32}
33
34#[derive(Debug)]
35pub enum SpecificError {
36 CouldNotMoveDown,
37 CouldNotMoveRight,
38 General(String),
39 ExpectingTypeIdentifier,
40 ExpectingInnerPair,
41 UnexpectedTypeRule,
42 ExpectedTypeIdentifier(String),
43 ExpectedLocalTypeIdentifier(String),
44 UnexpectedRuleInParseScript(String),
45 ExpectedControlStatement(String),
46 ExpectedStatement(String),
47 ExpectedIfOrElse(String),
48 MissingFunctionSignature,
49 MissingFunctionBody,
50 ExpectedStatementBlock,
51 ExpectedFunctionDefinition,
52 ExpectedParameter,
53 ExpectedImplItem,
54 ExpectedMemberSignature,
55 ExpectedBlockInWhileLoop,
56 UnexpectedExpressionType(String),
57 UnexpectedAccessType(String),
58 UnknownAssignmentOperator(String),
59 CompoundOperatorCanNotContainMut,
60 InvalidAssignmentTarget,
61 CompoundOperatorCanNotHaveMultipleVariables,
62 ExpectedExpressionAfterPrefixOperator,
63 UnknownOperator(String),
64 UnexpectedPostfixOperator,
65 UnexpectedUnaryOperator(String),
66 InvalidMemberCall,
67 UnknownMatchType,
68 UnexpectedElementInPatternList,
69 InvalidPrecisionValue,
70 InvalidPrecisionType,
71 ExpectedTypeIdentifierAfterPath,
72 UnexpectedPatternListElement(String),
73 MustHaveAtLeastOneArm,
74 UnexpectedMatchArmRule(String),
75 UnknownEnumVariant(String),
76 UnknownLiteral,
77 UnknownPrimary(String),
78 InvalidFormatSpecifier,
79 UnexpectedVariantField,
80 MutOnlyForVariables,
81 UnexpectedTokenInFunctionCall,
82 ExpectedExpressionInInterpolation,
83 UnexpectedRuleInInterpolation,
84 ExpectedForPattern,
85 ExpectedBlock,
86 InvalidForPattern,
87 UnexpectedRuleInElse(String),
88 ExpectedLocationExpression,
89 ExpectedImportPath,
90 ExpectedIdentifier,
91 ExpectedIdentifierAfterPath,
92 ExpectedFieldOrRest,
93 UnknownEscapeCharacter(char),
94 UnfinishedEscapeSequence,
95 InvalidUnicodeEscape,
96 InvalidHexEscape,
97 InvalidUtf8Sequence,
98 MissingTypeName,
99 UnknownTerm(String),
100 UnknownExpr(String),
101 UnexpectedTokenInMutableExpression,
102}
103
104#[derive(Debug)]
105pub struct ParseError {
106 pub span: SpanWithoutFileId,
107 pub specific: SpecificError,
108}
109
110#[derive(Parser)]
111#[grammar = "grammar.pest"]
112pub struct ScriptParser;
113
114pub const UNKNOWN_FILE_ID: u16 = 0xffff;
115
116pub struct AstParser;
117
118impl From<Error<Rule>> for ParseError {
119 fn from(value: Error<Rule>) -> Self {
120 let span = match value.location {
121 InputLocation::Pos(pos) => SpanWithoutFileId {
122 offset: pos as u32,
123 length: 1,
124 },
125 InputLocation::Span((start, end)) => SpanWithoutFileId {
126 offset: start as u32,
127 length: (end - start) as u16,
128 },
129 };
130 Self {
131 span,
132 specific: SpecificError::General(value.variant.to_string()),
133 }
134 }
135}
136
137impl AstParser {
138 fn next_pair<'a>(
139 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
140 ) -> Result<Pair<'a, Rule>, ParseError> {
141 Ok(pairs.next().ok_or_else(|| {
142 Error::new_from_pos(
143 ErrorVariant::CustomError {
144 message: "Expected more tokens".into(),
145 },
146 Position::from_start(""),
147 )
148 })?)
149 }
150
151 fn expect_next<'a>(
152 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
153 expected_rule: Rule,
154 ) -> Result<Pair<'a, Rule>, ParseError> {
155 let pair = Self::next_pair(pairs)?;
156 if pair.as_rule() != expected_rule {
157 return Err(Error::new_from_span(
158 ErrorVariant::CustomError {
159 message: format!("Expected {:?}, found {:?}", expected_rule, pair.as_rule()),
160 },
161 pair.as_span(),
162 ))?;
163 }
164 Ok(pair)
165 }
166
167 fn expect_identifier_next<'a>(
168 &self,
169 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
170 ) -> Result<LocalIdentifier, ParseError> {
171 let pair = Self::expect_next(pairs, Rule::identifier)?;
172 Ok(LocalIdentifier::new(self.to_node(&pair)))
173 }
174
175 fn expect_function_identifier_next<'a>(
176 &self,
177 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
178 ) -> Result<LocalIdentifier, ParseError> {
179 let pair = Self::expect_next(pairs, Rule::function_identifier)?;
180 Ok(LocalIdentifier::new(self.to_node(&pair)))
181 }
182
183 fn expect_constant_identifier_next<'a>(
184 &self,
185 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
186 ) -> Result<ConstantIdentifier, ParseError> {
187 let pair = Self::expect_next(pairs, Rule::constant_identifier)?;
188 Ok(ConstantIdentifier::new(self.to_node(&pair)))
189 }
190
191 fn _expect_variable_next<'a>(
192 &self,
193 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
194 ) -> Result<Variable, ParseError> {
195 let identifier = self.expect_identifier_next(pairs)?;
196 Ok(Variable {
197 name: identifier.0,
198 is_mutable: None,
199 })
200 }
201
202 fn expect_field_label_next<'a>(
203 &self,
204 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
205 ) -> Result<FieldName, ParseError> {
206 let field_label_pair = Self::expect_next(pairs, Rule::field_label)?;
207 let mut inner = field_label_pair.clone().into_inner();
208 let ident_pair = inner.next().ok_or_else(|| {
209 self.create_error_pair(SpecificError::ExpectedIdentifier, &field_label_pair)
210 })?;
211
212 Ok(FieldName(self.to_node(&ident_pair)))
213 }
214
215 fn parse_dot_identifier<'a>(&self, pair: &Pair<Rule>) -> Result<FieldName, ParseError> {
216 assert_eq!(pair.as_rule(), Rule::dot_identifier);
217 let mut inner = pair.clone().into_inner();
218 let ident_pair = inner
219 .next()
220 .ok_or_else(|| self.create_error_pair(SpecificError::ExpectedIdentifier, &pair))?;
221
222 Ok(FieldName(self.to_node(&ident_pair)))
223 }
224
225 fn expect_local_type_identifier_next<'a>(
226 &self,
227 pairs: &mut impl Iterator<Item = Pair<'a, Rule>>,
228 ) -> Result<LocalTypeIdentifier, ParseError> {
229 let pair = Self::expect_next(pairs, Rule::type_identifier)?;
230 Ok(LocalTypeIdentifier::new(self.to_node(&pair)))
231 }
232
233 fn convert_into_iterator<'a>(pair: &'a Pair<'a, Rule>) -> impl Iterator<Item = Pair<'a, Rule>> {
263 pair.clone().into_inner()
264 }
265
266 fn create_error_pair(&self, kind: SpecificError, pair: &Pair<Rule>) -> ParseError {
267 ParseError {
268 span: self.to_span(pair.as_span()),
269 specific: kind,
270 }
271 }
272
273 fn to_err(kind: SpecificError, pair: &Pair<Rule>) -> ParseError {
274 ParseError {
275 span: Self::span(pair.as_span()),
276 specific: kind,
277 }
278 }
279
280 fn next_inner_pair<'a>(&self, pair: &Pair<'a, Rule>) -> Result<Pair<'a, Rule>, ParseError> {
281 let _span = pair.as_span();
282 pair.clone()
283 .into_inner()
284 .next()
285 .ok_or_else(move || self.create_error_pair(SpecificError::ExpectingInnerPair, pair))
286 }
287
288 pub fn parse(rule: Rule, raw_script: &str) -> Result<ParseResult<'static>, ParseError> {
289 let pairs = unsafe {
290 std::mem::transmute::<pest::iterators::Pairs<'_, Rule>, pest::iterators::Pairs<'_, Rule>>(
291 ScriptParser::parse(rule, raw_script)?,
292 )
293 };
294 Ok(ParseResult {
295 script: raw_script.to_string(),
296 pairs,
297 })
298 }
299
300 pub fn parse_module(&self, raw_script: &str) -> Result<Module, ParseError> {
301 let result = Self::parse(Rule::program, raw_script)?;
302
303 let mut pairs = result.pairs;
304
305 let program_pair = Self::next_pair(&mut pairs)?;
306
307 let mut expressions = Vec::new();
308 let mut definitions = Vec::new();
309 for pair in Self::convert_into_iterator(&program_pair) {
310 match pair.as_rule() {
311 Rule::definition => {
312 let def = self.parse_definition(&pair)?;
313 definitions.push(def);
314 }
315 Rule::expression => {
316 let expr = self.parse_expression(&pair)?;
317 expressions.push(expr);
318 }
319 Rule::EOI => {} _ => {
321 return Err(self.create_error_pair(
322 SpecificError::UnexpectedRuleInParseScript(Self::pair_to_rule(&pair)),
323 &pair,
324 ));
325 }
326 }
327 }
328
329 let maybe_expression = match expressions.len() {
330 0 => None,
331 1 => Some(expressions.into_iter().next().unwrap()),
332 _ => Some(Expression {
333 kind: ExpressionKind::Block(expressions),
334 node: Node {
335 span: SpanWithoutFileId::default(),
336 },
337 }),
338 };
339
340 Ok(Module::new(definitions, maybe_expression))
341 }
342
343 fn parse_definition(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
344 let inner_pair = self.next_inner_pair(pair)?;
345 match inner_pair.as_rule() {
346 Rule::impl_def => self.parse_impl_def(&inner_pair),
347 Rule::const_def => self.parse_const_definition(&inner_pair),
348 Rule::struct_def => self.parse_struct_def(&inner_pair),
349 Rule::type_def => self.parse_type_def(&inner_pair),
350 Rule::function_def => self.parse_function_def(&inner_pair),
351 Rule::use_def => self.parse_use(&inner_pair),
352 Rule::mod_def => self.parse_mod(&inner_pair),
353 Rule::enum_def => self.parse_enum_def(&inner_pair),
354 _ => todo!(),
355 }
356 }
357
358 fn parse_const_definition(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
359 Ok(Definition::Constant(self.parse_const_info(pair)?))
360 }
361
362 fn parse_const_info(&self, pair: &Pair<Rule>) -> Result<ConstantInfo, ParseError> {
363 let mut inner = Self::convert_into_iterator(pair);
364 let constant_identifier = self.expect_constant_identifier_next(&mut inner)?;
365 let expr_pair = Self::next_pair(&mut inner)?;
366 let expression = self.parse_expression(&expr_pair)?;
367
368 Ok(ConstantInfo {
369 constant_identifier,
370 expression: Box::new(expression),
371 })
372 }
373
374 fn module_path_and_items(
375 &self,
376 pair: &Pair<Rule>,
377 ) -> Result<(Vec<Node>, ImportItems), ParseError> {
378 let mut inner = Self::convert_into_iterator(pair);
379 let import_path = Self::next_pair(&mut inner)?;
380
381 let mut segments = Vec::new();
382 for pair in import_path.into_inner() {
383 segments.push(self.to_node(&pair));
384 }
385
386 let items = match inner.next() {
387 Some(found_rule) => match found_rule.as_rule() {
388 Rule::all_imports => ImportItems::All,
389 Rule::import_list => {
390 let mut imported_items = Vec::new();
391 for list_item in found_rule.into_inner() {
392 let item = Self::next_pair(&mut list_item.into_inner())?;
393
394 let import_item = match item.as_rule() {
395 Rule::identifier => {
396 ImportItem::Identifier(LocalIdentifier::new(self.to_node(&item)))
397 }
398 Rule::type_identifier => {
399 ImportItem::Type(LocalTypeIdentifier::new(self.to_node(&item)))
400 }
401 _ => {
402 return Err(self
403 .create_error_pair(SpecificError::ExpectedIdentifier, &item));
404 }
405 };
406
407 imported_items.push(import_item);
408 }
409 if imported_items.is_empty() {
410 ImportItems::Nothing
411 } else {
412 ImportItems::Items(imported_items)
413 }
414 }
415 _ => panic!("was not all_imports or import_list"),
416 },
417 None => ImportItems::Nothing,
418 };
419
420 Ok((segments, items))
421 }
422
423 fn parse_use(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
424 let (segments, items) = self.module_path_and_items(&pair)?;
425
426 Ok(Definition::Use(Use {
427 module_path: ModulePath(segments),
428 items,
429 }))
430 }
431
432 fn parse_mod(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
433 let (segments, items) = self.module_path_and_items(&pair)?;
434
435 Ok(Definition::Mod(Mod {
436 module_path: ModulePath(segments),
437 items,
438 }))
439 }
440
441 fn pair_to_rule(rule: &Pair<Rule>) -> String {
442 format!("{:?}", rule.as_rule())
443 }
444
445 fn parse_block(&self, block_pair: &Pair<Rule>) -> Result<Expression, ParseError> {
446 if block_pair.as_rule() != Rule::block {
447 return Err(self.create_error_pair(SpecificError::ExpectedBlock, block_pair));
448 }
449
450 let mut expressions = Vec::new();
451
452 for pair in Self::convert_into_iterator(block_pair) {
453 if pair.as_rule() != Rule::expression {
454 return Err(self.create_error_pair(
455 SpecificError::UnexpectedRuleInParseScript(format!(
456 "Expected expression_in_block, got: {:?}",
457 pair.as_rule()
458 )),
459 block_pair,
460 ));
461 }
462
463 match pair.as_rule() {
464 Rule::expression => {
465 let expr = self.parse_expression(&pair)?;
466 expressions.push(expr);
467 }
468 _ => {
469 return Err(self.create_error_pair(
470 SpecificError::UnexpectedRuleInParseScript(format!(
471 "Unexpected rule in parse_block: {:?}",
472 pair.as_rule()
473 )),
474 &pair,
475 ));
476 }
477 }
478 }
479
480 let block_expr = self.create_expr(ExpressionKind::Block(expressions), block_pair);
481 Ok(block_expr)
482 }
483
484 fn parse_with_expr(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
485 let mut inner = Self::convert_into_iterator(pair);
486 let binding_list_pair = inner.next().expect("variable list missing");
487 let binding_list = self.parse_variable_binding_list(&binding_list_pair)?;
488
489 let expr_pair = inner.next().expect("block missing");
490 let expr = self.parse_expression(&expr_pair)?;
491
492 let with_expr = self.create_expr(ExpressionKind::With(binding_list, Box::from(expr)), pair);
493 Ok(with_expr)
494 }
495
496 fn parse_when_expr(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
497 let mut inner = Self::convert_into_iterator(pair);
498 let binding_list =
499 self.parse_when_variable_binding_list(&inner.next().expect("variable list missing"))?;
500 let expr = self.parse_expression(&inner.next().expect("block missing"))?;
501
502 let next = inner.next();
503 let else_expr = if let Some(found_else) = next {
504 Some(Box::new(self.parse_expression(&found_else)?))
505 } else {
506 None
507 };
508
509 Ok(self.create_expr(
510 ExpressionKind::When(binding_list, Box::from(expr), else_expr),
511 pair,
512 ))
513 }
514
515 fn parse_variable_binding_list(
516 &self,
517 pair: &Pair<Rule>,
518 ) -> Result<Vec<VariableBinding>, ParseError> {
519 let inner = Self::convert_into_iterator(pair);
520 let mut bindings = Vec::new();
521
522 for binding_pair in inner {
524 if binding_pair.as_rule() == Rule::variable_binding {
525 bindings.push(self.parse_variable_binding(&binding_pair)?);
526 }
527 }
528
529 Ok(bindings)
530 }
531
532 fn parse_variable_binding(&self, pair: &Pair<Rule>) -> Result<VariableBinding, ParseError> {
533 let mut inner = Self::convert_into_iterator(pair);
534
535 let variable = self.parse_variable_item(&inner.next().expect("variable missing"))?;
536
537 let expression = match inner.next() {
538 Some(expr_pair) => self.parse_mutable_or_immutable_expression(&expr_pair)?,
539 _ => MutableOrImmutableExpression {
540 expression: self
541 .create_expr(ExpressionKind::VariableReference(variable.clone()), pair),
542 is_mutable: None,
543 },
544 };
545
546 Ok(VariableBinding {
547 variable,
548 expression,
549 })
550 }
551
552 fn parse_when_variable_binding(&self, pair: &Pair<Rule>) -> Result<WhenBinding, ParseError> {
553 let mut inner = Self::convert_into_iterator(pair);
554
555 let variable = self.parse_variable_item(&inner.next().expect("variable missing"))?;
556
557 let expression = match inner.next() {
558 Some(expr_pair) => Some(self.parse_mutable_or_immutable_expression(&expr_pair)?),
559 _ => None,
560 };
561
562 Ok(WhenBinding {
563 variable,
564 expression,
565 })
566 }
567
568 fn parse_when_variable_binding_list(
569 &self,
570 pair: &Pair<Rule>,
571 ) -> Result<Vec<WhenBinding>, ParseError> {
572 let inner = Self::convert_into_iterator(pair);
573 let mut bindings = Vec::new();
574
575 for binding_pair in inner {
577 if binding_pair.as_rule() == Rule::variable_when_binding {
578 bindings.push(self.parse_when_variable_binding(&binding_pair)?);
579 }
580 }
581
582 Ok(bindings)
583 }
584
585 fn parse_if_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
586 let mut inner = Self::convert_into_iterator(pair);
587 let condition = self.parse_expression(&Self::next_pair(&mut inner)?)?;
588 let then_branch = self.parse_expression(&Self::next_pair(&mut inner)?)?;
589 let else_branch = inner
590 .next()
591 .map(|p| {
592 match p.as_rule() {
593 Rule::if_expr => self.parse_if_expression(&p), _ => self.parse_expression(&p), }
596 })
597 .transpose()?;
598
599 Ok(self.create_expr(
600 ExpressionKind::If(
601 Box::new(condition),
602 Box::new(then_branch),
603 else_branch.map(Box::new),
604 ),
605 pair,
606 ))
607 }
608
609 #[allow(clippy::too_many_lines)]
610 fn parse_postfix_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
611 assert_eq!(pair.as_rule(), Rule::postfix);
612 let mut inner = pair.clone().into_inner();
613
614 let primary_pair = inner.next().ok_or_else(|| {
615 self.create_error_pair(SpecificError::UnexpectedPostfixOperator, pair)
616 })?;
617 let start_expr = self.parse_term(&primary_pair)?;
618 let mut postfixes = Vec::new();
620 if inner.len() == 0 {
621 return Ok(start_expr);
622 }
623
624 for op_pair in inner.clone() {
625 match op_pair.as_rule() {
627 Rule::postfix_op => {
628 let mut sub_inner = op_pair.clone().into_inner();
629 let child = sub_inner.next().ok_or_else(|| {
630 self.create_error_pair(SpecificError::UnexpectedPostfixOperator, &op_pair)
631 })?;
632
633 match child.as_rule() {
634 Rule::unwrap_postfix => {
635 postfixes.push(Postfix::OptionUnwrap(self.to_node(&op_pair)));
636 }
637
638 Rule::none_coalesce_postfix => {
639 let mut postfix_inner = Self::convert_into_iterator(&child);
640 let expr_pair = postfix_inner.next().expect("must have following");
641 let default_expression = self.parse_expression(&expr_pair)?;
642 postfixes.push(Postfix::NoneCoalesce(default_expression));
643 }
644
645 Rule::function_call_postfix => {
646 let args = self.parse_function_call_postfix(&child)?;
647 let node = self.to_node(&op_pair);
648 postfixes.push(Postfix::FunctionCall(node, args));
649 }
650
651 Rule::member_call_postfix => {
652 let mut inner = child.into_inner();
653
654 let member_access = Self::next_pair(&mut inner)?;
655 assert_eq!(member_access.as_rule(), Rule::member_access_postfix);
656 let mut ma_inner = member_access.into_inner();
657 let dot_id = Self::next_pair(&mut ma_inner)?;
658 let member_identifier = self.parse_dot_identifier(&dot_id)?;
659
660 let args_pair = Self::next_pair(&mut inner)?;
661 let args = self.parse_function_call_arguments(&args_pair)?;
662
663 postfixes.push(Postfix::MemberCall(member_identifier.0, args));
664 }
665
666 Rule::member_access_postfix => {
667 let mut inner = child.into_inner();
668 let dot_id = Self::next_pair(&mut inner)?;
669 let identifier = self.parse_dot_identifier(&dot_id)?;
670 postfixes.push(Postfix::FieldAccess(identifier.0));
671 }
672
673 Rule::subscript_postfix => {
674 let mut arr_inner = child.clone().into_inner();
675 let index_pair = arr_inner.next().ok_or_else(|| {
676 self.create_error_pair(
677 SpecificError::UnexpectedPostfixOperator,
678 &child,
679 )
680 })?;
681 let index_expr = self.parse_expression(&index_pair)?;
682 postfixes.push(Postfix::Subscript(index_expr));
683 }
684
685 _ => {
686 return Err(self.create_error_pair(
687 SpecificError::UnexpectedPostfixOperator,
688 &child,
689 ));
690 }
691 }
692 }
693 _ => {
694 return Err(
695 self.create_error_pair(SpecificError::UnexpectedPostfixOperator, &op_pair)
696 );
697 }
698 }
699 }
700
701 Ok(self.create_expr(
702 ExpressionKind::PostfixChain(PostfixChain {
703 base: Box::from(start_expr),
704 postfixes: postfixes,
705 }),
706 pair,
707 ))
708 }
709
710 fn parse_type_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
711 let mut inner = Self::convert_into_iterator(pair);
712 let alias_name = self.expect_local_type_identifier_next(&mut inner)?;
713 let referenced_type = self.parse_type(inner.next().expect("should work"))?;
714
715 let alias_type = AliasType {
716 identifier: alias_name,
717 referenced_type,
718 };
719
720 Ok(Definition::AliasDef(alias_type))
721 }
722
723 fn parse_struct_type_field(&self, pair: &Pair<Rule>) -> Result<StructTypeField, ParseError> {
724 assert_eq!(pair.as_rule(), Rule::struct_type_field);
725
726 let mut field_inner = Self::convert_into_iterator(&pair);
727 let field_name = self.expect_field_label_next(&mut field_inner)?;
728 let field_type = self.parse_type(Self::next_pair(&mut field_inner)?)?;
729 let struct_type_field = StructTypeField {
730 field_name,
731 field_type,
732 };
733
734 Ok(struct_type_field)
735 }
736
737 fn parse_struct_type_fields(
738 &self,
739 pair: &Pair<Rule>,
740 ) -> Result<Vec<StructTypeField>, ParseError> {
741 assert_eq!(pair.as_rule(), Rule::struct_type_fields);
742 let mut fields = Vec::new();
743 for field_def in Self::convert_into_iterator(pair) {
744 let anonymous_struct_field = self.parse_struct_type_field(&field_def)?;
745
746 fields.push(anonymous_struct_field);
747 }
748 Ok(fields)
749 }
750
751 fn parse_struct_type(&self, pair: &Pair<Rule>) -> Result<AnonymousStructType, ParseError> {
752 assert_eq!(pair.as_rule(), Rule::struct_type);
753 let fields = Self::right_alternative(pair)?;
754 let fields = self.parse_struct_type_fields(&fields)?;
755 let struct_type = AnonymousStructType::new(fields);
756 Ok(struct_type)
757 }
758
759 fn parse_tuple_type_elements(&self, pair: &Pair<Rule>) -> Result<Vec<Type>, ParseError> {
760 assert_eq!(pair.as_rule(), Rule::tuple_type);
761 let mut types = Vec::new();
762 for type_pair in pair.clone().into_inner() {
763 let type_value = self.parse_type(type_pair)?;
764 types.push(type_value);
765 }
766 Ok(types)
767 }
768
769 fn parse_struct_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
770 let mut inner = Self::convert_into_iterator(pair).peekable();
771
772 let name_with_optional_type_params =
773 self.parse_local_type_identifier_with_optional_type_variables(&inner.next().unwrap())?;
774
775 let struct_type_pair_option = inner.next();
779 let struct_type_result = match struct_type_pair_option {
780 Some(struct_type_pair) => Some(self.parse_struct_type(&struct_type_pair)?),
781 None => None,
782 };
783
784 let struct_type = struct_type_result.map_or_else(
785 || AnonymousStructType::new(vec![]),
786 |found_result| found_result,
787 );
788
789 Ok(Definition::NamedStructDef(NamedStructDef {
790 identifier: name_with_optional_type_params,
791 struct_type,
792 }))
793 }
794
795 fn parse_function_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
796 let function_pair = self.next_inner_pair(pair)?;
797
798 match function_pair.as_rule() {
799 Rule::normal_function => {
800 let mut inner = function_pair.clone().into_inner();
801 let signature_pair = inner.next().ok_or_else(|| {
802 self.create_error_pair(SpecificError::MissingFunctionSignature, &function_pair)
803 })?;
804
805 let signature = self.parse_function_signature(&signature_pair)?;
806
807 let body = self.parse_block(&inner.next().ok_or_else(|| {
808 self.create_error_pair(SpecificError::MissingFunctionBody, &function_pair)
809 })?)?;
810
811 Ok(Definition::FunctionDef(Function::Internal(
812 FunctionWithBody {
813 declaration: signature,
814 body,
815 },
816 )))
817 }
818 Rule::external_function => {
819 let signature_pair =
820 function_pair.clone().into_inner().next().ok_or_else(|| {
821 self.create_error_pair(
822 SpecificError::MissingFunctionSignature,
823 &function_pair,
824 )
825 })?;
826
827 let signature = self.parse_function_signature(&signature_pair)?;
828 Ok(Definition::FunctionDef(Function::External(signature)))
829 }
830 _ => {
831 Err(self
832 .create_error_pair(SpecificError::ExpectedFunctionDefinition, &function_pair))
833 }
834 }
835 }
836 fn parse_function_signature(
837 &self,
838 pair: &Pair<Rule>,
839 ) -> Result<FunctionDeclaration, ParseError> {
840 if pair.as_rule() != Rule::function_signature {
841 return Err(self.create_error_pair(SpecificError::MissingFunctionSignature, pair));
842 }
843
844 let mut inner = pair.clone().into_inner();
845
846 let function_name = self.expect_function_identifier_next(&mut inner)?;
847
848 let next_token = inner.next();
849 let (parameters, return_type) = match next_token {
850 Some(token) if token.as_rule() == Rule::parameter_list => {
851 let params = self.parse_parameters(&token)?;
852
853 let ret_type = if let Some(return_type_pair) = inner.next() {
854 Some(self.parse_return_type(&return_type_pair)?)
855 } else {
856 None
857 };
858
859 (params, ret_type)
860 }
861
862 Some(token) if token.as_rule() == Rule::return_type => {
863 (Vec::new(), Some(self.parse_return_type(&token)?))
864 }
865 _ => (Vec::new(), None),
866 };
867
868 Ok(FunctionDeclaration {
869 name: function_name.0,
870 params: parameters,
871 self_parameter: None,
872 return_type,
873 })
874 }
875
876 fn parse_return_type(&self, pair: &Pair<Rule>) -> Result<Type, ParseError> {
877 let inner_pair = self.next_inner_pair(pair)?;
878 self.parse_type(inner_pair)
879 }
880
881 pub fn parse_parameters(&self, pair: &Pair<Rule>) -> Result<Vec<Parameter>, ParseError> {
882 let mut parameters = Vec::new();
883
884 for param_pair in Self::convert_into_iterator(pair) {
885 match param_pair.as_rule() {
886 Rule::parameter => {
887 let mut iterator = Self::convert_into_iterator(¶m_pair);
888 let may_mut_pair = iterator.next().unwrap();
889 let var = self.parse_maybe_mut_identifier(&may_mut_pair)?;
890 let type_pair = iterator.next().unwrap();
891 let param_type = self.parse_type(type_pair.clone())?;
892
893 parameters.push(Parameter {
894 variable: var,
895 param_type,
896 });
897 }
898 Rule::self_parameter => {
899 panic!("should have been handled before parsing parameters")
900 }
901 _ => {
902 return Err(
903 self.create_error_pair(SpecificError::ExpectedParameter, ¶m_pair)
904 );
905 }
906 }
907 }
908
909 Ok(parameters)
910 }
911
912 fn parse_impl_def(&self, pair: &Pair<Rule>) -> Result<Definition, ParseError> {
913 let mut inner = Self::convert_into_iterator(pair);
914 let name_with_optional_type_params =
915 self.parse_local_type_identifier_with_optional_type_variables(&inner.next().unwrap())?;
916
917 let mut functions = Vec::new();
918
919 for item_pair in inner {
920 if item_pair.as_rule() == Rule::impl_item {
921 let inner_item = self.next_inner_pair(&item_pair)?;
922 match inner_item.as_rule() {
923 Rule::external_member_function => {
924 let inner_inner_item = self.next_inner_pair(&inner_item)?;
925 let signature = self.parse_member_signature(&inner_inner_item)?;
926 functions.push(Function::External(signature));
927 }
928 Rule::normal_member_function => {
929 let function_data = self.parse_member_data(&inner_item)?;
930 functions.push(Function::Internal(function_data));
931 }
932 _ => {
933 return Err(
934 self.create_error_pair(SpecificError::ExpectedImplItem, &inner_item)
935 );
936 }
937 }
938 }
939 }
940
941 Ok(Definition::ImplDef(
942 name_with_optional_type_params,
943 functions,
944 ))
945 }
946
947 fn parse_member_signature(&self, pair: &Pair<Rule>) -> Result<FunctionDeclaration, ParseError> {
948 assert_eq!(pair.as_rule(), Rule::member_signature);
949
950 let mut inner = pair.clone().into_inner();
951
952 let name = self.expect_function_identifier_next(&mut inner)?;
953
954 let mut parameters = Vec::new();
955 let mut self_parameter = None;
956 let mut return_type = None;
957
958 for next_pair in inner {
959 match next_pair.as_rule() {
960 Rule::self_parameter => {
961 let mut mut_keyword_node = None;
962 let mut self_node = None;
963
964 for pair in next_pair.into_inner() {
965 match pair.as_rule() {
966 Rule::mut_keyword => {
967 mut_keyword_node = Some(self.to_node(&pair));
968 }
969 Rule::self_identifier => {
970 self_node = Some(self.to_node(&pair));
971 }
972 _ => unreachable!("Unexpected rule in self_parameter"),
973 }
974 }
975
976 self_parameter = Some(SelfParameter {
977 is_mutable: mut_keyword_node,
978 self_node: self_node.expect("self node must exist"),
979 });
980 }
981 Rule::parameter_list => {
982 parameters = self.parse_parameters(&next_pair)?;
983 }
984 Rule::return_type => {
985 return_type = Some(self.parse_return_type(&next_pair)?);
986 }
987 _ => {}
988 }
989 }
990
991 Ok(FunctionDeclaration {
992 name: name.0,
993 params: parameters,
994 self_parameter,
995 return_type,
996 })
997 }
998
999 fn parse_member_data(&self, pair: &Pair<Rule>) -> Result<FunctionWithBody, ParseError> {
1000 if pair.as_rule() != Rule::normal_member_function {
1001 return Err(self.create_error_pair(SpecificError::ExpectedMemberSignature, pair));
1002 }
1003
1004 let mut inner = Self::convert_into_iterator(pair);
1005
1006 let signature_pair = Self::next_pair(&mut inner)?;
1007 let signature = self.parse_member_signature(&signature_pair)?;
1008
1009 let block_pair = Self::next_pair(&mut inner)?;
1010 let body = self.parse_block(&block_pair)?;
1011
1012 Ok(FunctionWithBody {
1013 declaration: signature,
1014 body,
1015 })
1016 }
1017
1018 fn parse_for_loop(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1019 let mut inner = Self::convert_into_iterator(pair);
1020
1021 let pattern_pair = Self::next_pair(&mut inner)?;
1022 if pattern_pair.as_rule() != Rule::for_pattern {
1023 return Err(self.create_error_pair(SpecificError::ExpectedForPattern, &pattern_pair));
1024 }
1025
1026 let inner_pattern = self.next_inner_pair(&pattern_pair)?;
1027 let pattern = match inner_pattern.as_rule() {
1028 Rule::maybe_mut_identifier => {
1029 let mut inner_iter = inner_pattern.clone().into_inner();
1030 let is_mutable = inner_iter
1031 .peek()
1032 .map_or(false, |p| p.as_rule() == Rule::mut_keyword);
1033
1034 let is_mut = if is_mutable {
1035 let mut_node = self.to_node(&inner_iter.next().unwrap());
1036 Some(mut_node)
1037 } else {
1038 None
1039 };
1040
1041 let identifier = if is_mutable {
1042 self.expect_identifier_next(&mut inner_iter)?.0
1043 } else {
1044 self.to_node(&inner_pattern)
1045 };
1046
1047 ForPattern::Single(ForVar { identifier, is_mut })
1048 }
1049 Rule::for_pair => {
1050 let mut vars = Self::convert_into_iterator(&inner_pattern);
1051
1052 let first_var_pair = Self::next_pair(&mut vars)?;
1054 let mut first_inner_iter = first_var_pair.clone().into_inner();
1055 let first_is_mut = if first_inner_iter
1056 .peek()
1057 .map_or(false, |p| p.as_rule() == Rule::mut_keyword)
1058 {
1059 Some(self.to_node(&first_inner_iter.next().unwrap()))
1060 } else {
1061 None
1062 };
1063
1064 let first_identifier = if first_is_mut.is_some() {
1065 self.expect_identifier_next(&mut first_inner_iter)?.0
1066 } else {
1067 self.to_node(&first_var_pair)
1068 };
1069
1070 let second_var_pair = Self::next_pair(&mut vars)?;
1072 let mut second_inner_iter = second_var_pair.clone().into_inner();
1073 let second_is_mut = if second_inner_iter
1074 .peek()
1075 .map_or(false, |p| p.as_rule() == Rule::mut_keyword)
1076 {
1077 Some(self.to_node(&second_inner_iter.next().unwrap()))
1078 } else {
1079 None
1080 };
1081
1082 let second_identifier = if second_is_mut.is_some() {
1083 self.expect_identifier_next(&mut second_inner_iter)?.0
1084 } else {
1085 self.to_node(&second_var_pair)
1086 };
1087
1088 ForPattern::Pair(
1089 ForVar {
1090 identifier: first_identifier,
1091 is_mut: first_is_mut,
1092 },
1093 ForVar {
1094 identifier: second_identifier,
1095 is_mut: second_is_mut,
1096 },
1097 )
1098 }
1099 _ => {
1100 return Err(
1101 self.create_error_pair(SpecificError::InvalidForPattern, &inner_pattern)
1102 );
1103 }
1104 };
1105
1106 let next_pair = Self::next_pair(&mut inner)?;
1107 let iterable_expression = self.parse_mutable_or_immutable_expression(&next_pair)?;
1108
1109 let mut_expression = IterableExpression {
1110 expression: Box::new(iterable_expression),
1111 };
1112
1113 let body = self.parse_expression(&Self::next_pair(&mut inner)?)?;
1114
1115 Ok(self.create_expr(
1117 ExpressionKind::ForLoop(pattern, mut_expression, Box::from(body)),
1118 pair,
1119 ))
1120 }
1121
1122 fn parse_while_loop(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1123 let mut inner = Self::convert_into_iterator(pair);
1124
1125 let condition = self.parse_expression(&Self::next_pair(&mut inner)?)?;
1126
1127 let body = self.parse_expression(&Self::next_pair(&mut inner)?)?;
1128
1129 Ok(self.create_expr(
1130 ExpressionKind::WhileLoop(Box::from(condition), Box::from(body)),
1131 pair,
1132 ))
1133 }
1134
1135 fn parse_return(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1136 let mut inner = Self::convert_into_iterator(pair);
1137
1138 let expr = match inner.next() {
1139 Some(expr_pair) => Some(Box::new(self.parse_expression(&expr_pair)?)),
1140 None => None,
1141 };
1142
1143 Ok(self.create_expr(ExpressionKind::Return(expr), pair))
1144 }
1145
1146 fn parse_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1147 let sub = &Self::right_alternative(pair)?;
1148 match sub.as_rule() {
1149 Rule::expression => {
1150 let inner = self.next_inner_pair(sub)?;
1151
1152 self.parse_expression(&inner)
1153 }
1154
1155 Rule::qualified_identifier => Ok(self.create_expr(
1156 ExpressionKind::VariableReference(Variable::new(self.to_node(sub), None)),
1157 sub,
1158 )),
1159 Rule::block => self.parse_block(sub),
1160
1161 Rule::assignment => self.parse_assignment_expression(sub),
1162 Rule::destructuring_assignment => self.parse_destructuring_assignment(sub),
1163 Rule::variable_definition => self.parse_variable_definition(sub),
1164
1165 Rule::addition => self.parse_addition(sub),
1166 Rule::range => self.parse_range(sub),
1167 Rule::logical => self.parse_logical(sub),
1168 Rule::comparison => self.parse_comparison(sub),
1169 Rule::multiplication => self.parse_multiplication(sub),
1170
1171 Rule::prefix => self.parse_prefix(sub),
1172
1173 Rule::match_expr => self.parse_match_expr(sub),
1174 Rule::map_literal => self.parse_map_literal(sub),
1175 Rule::array_literal => self.parse_array_literal(sub),
1176 Rule::guard_expr => self.parse_guard_expr_list(sub),
1177 Rule::return_expr => self.parse_return(sub),
1178 Rule::break_expr => Ok(self.create_expr(ExpressionKind::Break, sub)),
1179 Rule::continue_expr => Ok(self.create_expr(ExpressionKind::Continue, sub)),
1180 Rule::with_expr => self.parse_with_expr(sub),
1181 Rule::when_expr => self.parse_when_expr(sub),
1182 Rule::if_expr => self.parse_if_expression(sub),
1183 Rule::for_loop => self.parse_for_loop(sub),
1184 Rule::while_loop => self.parse_while_loop(sub),
1185
1186 Rule::prefix_op | Rule::op_neg | Rule::op_not => {
1188 let op = self.parse_unary_operator(sub)?;
1189 let expr = self.parse_postfix_expression(&self.next_inner_pair(sub)?)?;
1190 Ok(self.create_expr(ExpressionKind::UnaryOp(op, Box::new(expr)), sub))
1191 }
1192
1193 Rule::postfix => self.parse_postfix_expression(sub),
1195 _ => Err(self.create_error_pair(
1196 SpecificError::UnexpectedExpressionType(Self::pair_to_rule(sub)),
1197 sub,
1198 )),
1199 }
1200 }
1201
1202 fn parse_variable_list(&self, pair: &Pair<Rule>) -> Result<Vec<Variable>, ParseError> {
1203 let mut variables = Vec::new();
1204 for item_pair in pair.clone().into_inner() {
1205 if item_pair.as_rule() == Rule::variable_item {
1206 variables.push(self.parse_variable_item(&item_pair)?);
1207 }
1208 }
1209 Ok(variables)
1210 }
1211
1212 fn parse_maybe_mut_identifier(&self, pair: &Pair<Rule>) -> Result<Variable, ParseError> {
1213 assert_eq!(pair.as_rule(), Rule::maybe_mut_identifier);
1214 let mut inner = pair.clone().into_inner();
1215 let mut_node = if let Some(peeked) = inner.peek() {
1216 if peeked.as_rule() == Rule::mut_keyword {
1217 let node = self.to_node(&peeked);
1219 inner.next(); Some(node)
1221 } else {
1222 None
1223 }
1224 } else {
1225 None
1226 };
1227
1228 let name_pair = inner.next().ok_or_else(|| {
1229 self.create_error_pair(
1230 SpecificError::UnexpectedRuleInParseScript(
1231 "Expected identifier in variable_item".into(),
1232 ),
1233 pair,
1234 )
1235 })?;
1236
1237 if name_pair.as_rule() != Rule::identifier {
1238 return Err(self.create_error_pair(
1239 SpecificError::UnexpectedRuleInParseScript(format!(
1240 "Expected identifier, found {:?}",
1241 name_pair.as_rule()
1242 )),
1243 &name_pair,
1244 ));
1245 }
1246
1247 let variable = Variable {
1248 name: self.to_node(&name_pair),
1249 is_mutable: mut_node,
1250 };
1251
1252 Ok(variable)
1253 }
1254
1255 fn parse_variable_item(&self, pair: &Pair<Rule>) -> Result<Variable, ParseError> {
1256 assert_eq!(pair.as_rule(), Rule::variable_item);
1257 let mut inner = pair.clone().into_inner();
1258 self.parse_maybe_mut_identifier(&inner.next().unwrap())
1259 }
1260
1261 fn parse_assignment_expression(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1262 let mut iterator = pair.clone().into_inner();
1263 let lhs_logical =
1264 self.parse_logical(&iterator.next().expect("parse_assignment_expression"))?;
1265 if let Some(assignment_op_pair) = iterator.peek().clone() {
1266 iterator.next();
1267 let assignment_op = self.parse_assignment_op(&assignment_op_pair)?;
1268 let rhs_expr = self.parse_expression(&iterator.next().unwrap())?;
1269 let kind = match assignment_op {
1270 AssignmentOperatorKind::Assign => {
1271 ExpressionKind::Assignment(Box::new(lhs_logical), Box::from(rhs_expr))
1272 }
1273 AssignmentOperatorKind::Compound(compound) => {
1274 let op = CompoundOperator {
1275 node: Self::node_ex(&assignment_op_pair),
1276 kind: compound,
1277 };
1278 ExpressionKind::CompoundAssignment(
1279 Box::from(lhs_logical),
1280 op,
1281 Box::from(rhs_expr),
1282 )
1283 }
1284 };
1285
1286 Ok(self.create_expr(kind, &pair))
1287 } else {
1288 Ok(lhs_logical)
1289 }
1290 }
1291
1292 fn parse_assignment_op(&self, pair: &Pair<Rule>) -> Result<AssignmentOperatorKind, ParseError> {
1293 assert_eq!(pair.as_rule(), Rule::assign_op);
1294 let sub = Self::right_alternative(pair)?;
1295 let op = match sub.as_rule() {
1296 Rule::compound_assign_op => {
1297 AssignmentOperatorKind::Compound(Self::parse_compound_assign_op(&sub)?)
1298 }
1299 Rule::normal_assign_op => AssignmentOperatorKind::Assign,
1300 _ => {
1301 return Err(Self::to_err(
1302 SpecificError::UnknownAssignmentOperator("strange".to_string()),
1303 &sub,
1304 ));
1305 }
1306 };
1307
1308 Ok(op)
1309 }
1310
1311 #[allow(clippy::too_many_lines)]
1312 fn parse_destructuring_assignment(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1313 assert_eq!(pair.as_rule(), Rule::destructuring_assignment);
1314 let mut inner = pair.clone().into_inner();
1315
1316 let var_list_pair = inner.next().ok_or_else(|| {
1317 self.create_error_pair(
1318 SpecificError::UnexpectedRuleInParseScript("missing variable_list".to_string()),
1319 pair,
1320 )
1321 })?;
1322
1323 let variables = self.parse_variable_list(&var_list_pair)?;
1324
1325 let rhs_pair = inner.next().ok_or_else(|| {
1326 self.create_error_pair(
1327 SpecificError::UnexpectedRuleInParseScript("missing RHS expression".to_string()),
1328 pair,
1329 )
1330 })?;
1331 let rhs_expr = self.parse_expression(&rhs_pair)?;
1332
1333 Ok(self.create_expr(
1334 ExpressionKind::DestructuringAssignment(variables, Box::new(rhs_expr)),
1335 &rhs_pair,
1336 ))
1337 }
1338
1339 fn right_alternative<'a>(pair: &Pair<'a, Rule>) -> Result<Pair<'a, Rule>, ParseError> {
1340 pair.clone()
1341 .into_inner()
1342 .next()
1343 .ok_or_else(|| Self::to_err(SpecificError::CouldNotMoveRight, &pair))
1344 }
1345
1346 pub fn parse_compound_assign_op(
1347 op_pair: &Pair<Rule>,
1348 ) -> Result<CompoundOperatorKind, ParseError> {
1349 assert_eq!(op_pair.as_rule(), Rule::compound_assign_op);
1350
1351 let kind = match Self::right_alternative(&op_pair)?.as_rule() {
1352 Rule::add_assign_op => CompoundOperatorKind::Add,
1353 Rule::sub_assign_op => CompoundOperatorKind::Sub,
1354 Rule::mul_assign_op => CompoundOperatorKind::Mul,
1355 Rule::div_assign_op => CompoundOperatorKind::Div,
1356 Rule::modulo_assign_op => CompoundOperatorKind::Modulo,
1357 _ => {
1358 return Err(Self::to_err(
1359 SpecificError::UnknownOperator(format!(
1360 "Found unexpected operator rule: {:?}",
1361 op_pair.as_rule()
1362 )),
1363 &op_pair,
1364 ));
1365 }
1366 };
1367
1368 Ok(kind)
1369 }
1370
1371 #[allow(clippy::too_many_lines)]
1372 fn parse_variable_definition(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1373 let mut inner = pair.clone().into_inner();
1374 let variable_item = Self::next_pair(&mut inner)?;
1375 let found_var = self.parse_variable_item(&variable_item)?;
1376
1377 let maybe_annotation = if let Some(peeked) = inner.peek() {
1378 if peeked.as_rule() == Rule::type_coerce {
1379 let type_coerce_pair = inner.next().unwrap();
1380 let mut type_inner = type_coerce_pair.clone().into_inner();
1381 let type_name_pair = type_inner.next().ok_or_else(|| {
1382 self.create_error_pair(SpecificError::MissingTypeName, &type_coerce_pair)
1383 })?;
1384 Some(self.parse_type(type_name_pair)?)
1385 } else {
1386 None
1387 }
1388 } else {
1389 None
1390 };
1391
1392 let rhs_expr = self.parse_mutable_or_immutable_expression(&Self::next_pair(&mut inner)?)?;
1393
1394 if maybe_annotation.is_some() || found_var.is_mutable.is_some() {
1395 Ok(self.create_expr(
1396 ExpressionKind::VariableDefinition(
1397 found_var,
1398 maybe_annotation,
1399 Box::from(rhs_expr),
1400 ),
1401 pair,
1402 ))
1403 } else {
1404 Ok(self.create_expr(
1405 ExpressionKind::VariableAssignment(found_var, Box::from(rhs_expr)),
1406 pair,
1407 ))
1408 }
1409 }
1410 fn parse_prefix(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1411 assert_eq!(pair.as_rule(), Rule::prefix);
1412 let _span = pair.as_span();
1413 let inner = Self::convert_into_iterator(pair);
1414 let mut expr = None;
1415 let mut prefix_ops = Vec::new();
1416
1417 for part in inner {
1418 match part.as_rule() {
1419 Rule::prefix_op | Rule::op_neg | Rule::op_not => {
1420 let op = self.parse_unary_operator(&part)?;
1421 prefix_ops.push(op);
1422 }
1423 _ => {
1424 expr = Some(self.parse_postfix_expression(&part)?);
1425 break;
1426 }
1427 }
1428 }
1429
1430 let mut final_expr = expr.ok_or_else(|| {
1431 self.create_error_pair(SpecificError::ExpectedExpressionAfterPrefixOperator, pair)
1432 })?;
1433
1434 for op in prefix_ops.into_iter().rev() {
1435 final_expr = self.create_expr(ExpressionKind::UnaryOp(op, Box::new(final_expr)), pair);
1436 }
1437
1438 Ok(final_expr)
1439 }
1440
1441 fn parse_binary_operator(&self, pair: &Pair<Rule>) -> Result<BinaryOperator, ParseError> {
1442 let op = match pair.as_rule() {
1443 Rule::prefix_op => self.next_inner_pair(pair)?,
1444 _ => pair.clone(),
1445 };
1446
1447 let kind = match op.as_rule() {
1448 Rule::op_add => BinaryOperatorKind::Add,
1449 Rule::op_sub => BinaryOperatorKind::Subtract,
1450 Rule::op_mul => BinaryOperatorKind::Multiply,
1451 Rule::op_div => BinaryOperatorKind::Divide,
1452 Rule::op_mod => BinaryOperatorKind::Modulo,
1453 Rule::op_eq => BinaryOperatorKind::Equal,
1454 Rule::op_neq => BinaryOperatorKind::NotEqual,
1455 Rule::op_lt => BinaryOperatorKind::LessThan,
1456 Rule::op_lte => BinaryOperatorKind::LessEqual,
1457 Rule::op_gt => BinaryOperatorKind::GreaterThan,
1458 Rule::op_gte => BinaryOperatorKind::GreaterEqual,
1459 Rule::op_and => BinaryOperatorKind::LogicalAnd,
1460 Rule::op_or => BinaryOperatorKind::LogicalOr,
1461 _ => {
1462 panic!("unknown operator")
1463 }
1464 };
1465
1466 Ok(BinaryOperator {
1467 kind,
1468 node: self.to_node(pair),
1469 })
1470 }
1471
1472 fn parse_unary_operator(&self, pair: &Pair<Rule>) -> Result<UnaryOperator, ParseError> {
1473 let op = match pair.as_rule() {
1474 Rule::prefix_op => &self.next_inner_pair(pair)?,
1475 _ => pair,
1476 };
1477
1478 let node = self.to_node(op);
1479 match op.as_rule() {
1480 Rule::op_neg => Ok(UnaryOperator::Negate(node)),
1481 Rule::op_not => Ok(UnaryOperator::Not(node)),
1482 _ => Err(self.create_error_pair(
1483 SpecificError::UnexpectedUnaryOperator(Self::pair_to_rule(op)),
1484 op,
1485 )),
1486 }
1487 }
1488
1489 fn parse_module_segments(&self, pair: Pair<Rule>) -> Vec<Node> {
1490 pair.into_inner()
1491 .filter_map(|segment| {
1492 if segment.as_rule() == Rule::identifier {
1493 Some(self.to_node(&segment))
1494 } else {
1495 None
1496 }
1497 })
1498 .collect()
1499 }
1500
1501 fn parse_qualified_type_identifier(
1502 &self,
1503 pair: &Pair<Rule>,
1504 ) -> Result<QualifiedTypeIdentifier, ParseError> {
1505 let mut inner_pairs = pair.clone().into_inner();
1506 let mut generic_types = Vec::new();
1507
1508 let first = inner_pairs.next().ok_or_else(|| {
1509 self.create_error_pair(
1510 SpecificError::ExpectedTypeIdentifier(Self::pair_to_rule(pair)),
1511 pair,
1512 )
1513 })?;
1514
1515 match first.as_rule() {
1516 Rule::module_segments => {
1517 let module_path = self.parse_module_segments(first.clone());
1518 let type_id = inner_pairs.next().ok_or_else(|| {
1519 self.create_error_pair(SpecificError::ExpectedTypeIdentifierAfterPath, &first)
1520 })?;
1521
1522 let type_identifier = self.parse_local_type_identifier(&type_id)?;
1523
1524 if let Some(generic_params) = inner_pairs.next() {
1526 if generic_params.as_rule() == Rule::generic_params {
1527 generic_types = self.parse_generic_params(&generic_params)?;
1528 }
1529 }
1530
1531 Ok(QualifiedTypeIdentifier::new_with_generics(
1532 type_identifier,
1533 module_path,
1534 generic_types,
1535 ))
1536 }
1537 Rule::type_identifier => {
1538 let type_identifier = LocalTypeIdentifier(self.to_node(&first));
1539
1540 if let Some(generic_params) = inner_pairs.next() {
1542 if generic_params.as_rule() == Rule::generic_params {
1543 generic_types = self.parse_generic_params(&generic_params)?;
1544 }
1545 }
1546
1547 Ok(QualifiedTypeIdentifier::new_with_generics(
1548 type_identifier,
1549 Vec::new(),
1550 generic_types,
1551 ))
1552 }
1553 _ => Err(self.create_error_pair(
1554 SpecificError::ExpectedTypeIdentifier(Self::pair_to_rule(&first)),
1555 &first,
1556 )),
1557 }
1558 }
1559
1560 fn parse_qualified_identifier(
1561 &self,
1562 pair: &Pair<Rule>,
1563 ) -> Result<QualifiedIdentifier, ParseError> {
1564 let mut inner_pairs = pair.clone().into_inner();
1565 let mut generic_types = Vec::new();
1566
1567 let first = inner_pairs
1568 .next()
1569 .ok_or_else(|| self.create_error_pair(SpecificError::ExpectedIdentifier, pair))?;
1570
1571 match first.as_rule() {
1572 Rule::module_segments => {
1573 let module_path = self.parse_module_segments(first.clone());
1574 let id = inner_pairs.next().ok_or_else(|| {
1575 self.create_error_pair(SpecificError::ExpectedIdentifierAfterPath, &first)
1576 })?;
1577
1578 let identifier = self.to_node(&id);
1579
1580 if let Some(generic_params) = inner_pairs.next() {
1582 if generic_params.as_rule() == Rule::generic_params {
1583 generic_types = self.parse_generic_params(&generic_params)?;
1584 }
1585 }
1586
1587 Ok(QualifiedIdentifier::new_with_generics(
1588 identifier,
1589 module_path,
1590 generic_types,
1591 ))
1592 }
1593 Rule::identifier => {
1594 let type_identifier = self.to_node(&first);
1595
1596 if let Some(generic_params) = inner_pairs.next() {
1598 if generic_params.as_rule() == Rule::generic_params {
1599 generic_types = self.parse_generic_params(&generic_params)?;
1600 }
1601 }
1602
1603 Ok(QualifiedIdentifier::new_with_generics(
1604 type_identifier,
1605 Vec::new(),
1606 generic_types,
1607 ))
1608 }
1609 _ => Err(self.create_error_pair(SpecificError::ExpectedIdentifier, &first)),
1610 }
1611 }
1612
1613 fn parse_qualified_identifier_expression(
1614 &self,
1615 pair: &Pair<Rule>,
1616 ) -> Result<Expression, ParseError> {
1617 let qualified_identifier = self.parse_qualified_identifier(pair)?;
1618 Ok(self.create_expr(
1619 ExpressionKind::IdentifierReference(qualified_identifier),
1620 pair,
1621 ))
1622 }
1623
1624 fn parse_generic_params(&self, pair: &Pair<Rule>) -> Result<Vec<Type>, ParseError> {
1625 let inner_pairs = pair.clone().into_inner();
1626 let mut generic_types = Vec::new();
1627
1628 for type_pair in inner_pairs {
1629 if type_pair.as_rule() == Rule::type_name {
1630 generic_types.push(self.parse_type(type_pair)?);
1631 }
1632 }
1633
1634 Ok(generic_types)
1635 }
1636
1637 fn parse_local_type_identifier_node(&self, pair: &Pair<Rule>) -> Result<Node, ParseError> {
1638 if pair.as_rule() != Rule::type_identifier {
1639 return Err(self.create_error_pair(
1640 SpecificError::ExpectedTypeIdentifier(format!("{:?}", pair.as_rule())),
1641 pair,
1642 ));
1643 }
1644 Ok(self.to_node(pair))
1645 }
1646
1647 fn parse_generic_type_variables(
1648 &self,
1649 pair: &Pair<Rule>,
1650 ) -> Result<Vec<TypeVariable>, ParseError> {
1651 assert_eq!(pair.as_rule(), Rule::generic_type_params);
1652 let mut type_params = Vec::new();
1653 for type_identifier_pair in Self::convert_into_iterator(pair) {
1654 if type_identifier_pair.as_rule() == Rule::type_identifier {
1655 type_params.push(TypeVariable(
1656 self.parse_local_type_identifier_node(&type_identifier_pair)?,
1657 ));
1658 } else {
1659 panic!("internal error generic type params")
1660 }
1661 }
1662 Ok(type_params)
1663 }
1664
1665 fn parse_local_type_identifier_with_optional_type_variables(
1666 &self,
1667 pair: &Pair<Rule>,
1668 ) -> Result<LocalTypeIdentifierWithOptionalTypeVariables, ParseError> {
1669 assert_eq!(pair.as_rule(), Rule::type_identifier_optional_type_params);
1670
1671 let mut inner = pair.clone().into_inner();
1672 let name = self.expect_local_type_identifier_next(&mut inner)?;
1673
1674 let type_variables = if let Some(generic_params_pair) = inner.peek() {
1675 if generic_params_pair.as_rule() == Rule::generic_type_params {
1677 let generic_params_pair = inner.next().unwrap(); self.parse_generic_type_variables(&generic_params_pair)?
1679 } else {
1680 Vec::new()
1681 }
1682 } else {
1683 Vec::new()
1684 };
1685
1686 Ok(LocalTypeIdentifierWithOptionalTypeVariables {
1687 name: name.0,
1688 type_variables,
1689 })
1690 }
1691
1692 fn parse_struct_fields_expressions<'a>(
1693 &self,
1694 field_list_pair: &Pair<Rule>,
1695 ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1696 let mut fields = Vec::new();
1697 let mut has_rest = false;
1698
1699 for field_pair in field_list_pair.clone().into_inner() {
1700 match field_pair.as_rule() {
1701 Rule::struct_field => {
1702 let mut field_inner = field_pair.into_inner();
1703 let ident = self.expect_field_label_next(&mut field_inner)?;
1704 let field_name = FieldName(ident.0);
1705 let field_value = self.parse_expression(&field_inner.next().unwrap())?;
1706
1707 fields.push(FieldExpression {
1708 field_name,
1709 expression: field_value,
1710 });
1711 }
1712 Rule::rest_fields => {
1713 has_rest = true;
1714 }
1715 _ => {
1716 return Err(
1717 self.create_error_pair(SpecificError::ExpectedFieldOrRest, &field_pair)
1718 );
1719 }
1720 }
1721 }
1722
1723 Ok((fields, has_rest))
1724 }
1725
1726 fn parse_anonymous_struct_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1727 let (fields, has_rest) = self.parse_anonymous_struct_literal_fields(&pair)?;
1728 Ok(self.create_expr(
1729 ExpressionKind::AnonymousStructLiteral(fields, has_rest),
1730 pair,
1731 ))
1732 }
1733
1734 fn parse_anonymous_struct_literal_fields(
1735 &self,
1736 pair: &Pair<Rule>,
1737 ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1738 assert_eq!(pair.as_rule(), Rule::anonymous_struct_literal);
1739 let mut inner = Self::convert_into_iterator(pair);
1740 let (field_expressions, detected_rest) =
1741 self.parse_struct_fields_expressions(&inner.next().unwrap())?;
1742
1743 Ok((field_expressions, detected_rest))
1744 }
1745
1746 fn parse_struct_literal_optional_fields(
1747 &self,
1748 pair: &Pair<Rule>,
1749 ) -> Result<(Vec<FieldExpression>, bool), ParseError> {
1750 assert_eq!(pair.as_rule(), Rule::struct_literal_optional_field_list);
1751 let mut inner = Self::convert_into_iterator(pair);
1752 let (field_expressions, detected_rest) = if let Some(field_list) = inner.next() {
1753 self.parse_struct_fields_expressions(&field_list)?
1754 } else {
1755 (vec![], false)
1756 };
1757
1758 Ok((field_expressions, detected_rest))
1759 }
1760
1761 fn parse_struct_literal(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1762 let mut inner = Self::convert_into_iterator(pair);
1763
1764 let type_pair = inner.next().unwrap();
1765
1766 let struct_name = self.parse_qualified_type_identifier(&type_pair)?;
1767
1768 let anon_fields = inner.next().unwrap();
1769
1770 let (fields, has_rest) = self.parse_struct_literal_optional_fields(&anon_fields)?;
1771
1772 Ok(self.create_expr(
1773 ExpressionKind::NamedStructLiteral(struct_name, fields, has_rest),
1774 pair,
1775 ))
1776 }
1777
1778 fn parse_static_member_reference(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1779 let mut inner = pair.clone().into_inner();
1780
1781 let type_identifier = self.parse_qualified_type_identifier(&inner.next().unwrap())?;
1782 let member_name = self.expect_identifier_next(&mut inner)?;
1783
1784 Ok(self.create_expr(
1785 ExpressionKind::StaticMemberFunctionReference(type_identifier, member_name.0),
1786 pair,
1787 ))
1788 }
1789
1790 fn parse_term(&self, pair2: &Pair<Rule>) -> Result<Expression, ParseError> {
1791 assert_eq!(pair2.as_rule(), Rule::term);
1792 let sub = &Self::right_alternative(pair2)?;
1793 match sub.as_rule() {
1794 Rule::qualified_identifier => self.parse_qualified_identifier_expression(sub),
1795 Rule::static_member_reference => self.parse_static_member_reference(sub),
1796
1797 Rule::enum_literal => {
1798 Ok(self.create_expr(ExpressionKind::Literal(self.parse_enum_literal(sub)?), sub))
1799 }
1800 Rule::constant_reference => Ok(self.create_expr(
1801 ExpressionKind::ConstantReference(ConstantIdentifier(self.to_node(sub))),
1802 sub,
1803 )),
1804 Rule::parenthesized => {
1805 let inner = self.next_inner_pair(sub)?;
1806 self.parse_expression(&inner)
1807 }
1808 Rule::basic_literal => {
1809 let (literal, node) = self.parse_basic_literal(sub)?;
1810 Ok(self.create_expr_span(ExpressionKind::Literal(literal), node))
1811 }
1812 Rule::struct_literal => self.parse_struct_literal(sub),
1813 Rule::anonymous_struct_literal => self.parse_anonymous_struct_literal(sub),
1814
1815 Rule::interpolated_string => self.parse_interpolated_string(sub),
1816 _ => {
1823 Err(self
1824 .create_error_pair(SpecificError::UnknownTerm(Self::pair_to_rule(sub)), sub))
1825 }
1826 }
1827 }
1828
1829 fn parse_interpolated_string(&self, pair: &Pair<Rule>) -> Result<Expression, ParseError> {
1830 let mut parts = Vec::new();
1831
1832 for part_pair in Self::convert_into_iterator(pair) {
1833 match part_pair.as_rule() {
1834 Rule::text => {
1835 parts.push(StringPart::Literal(
1836 self.to_node(&part_pair),
1837 self.unescape_string(&part_pair, false)?,
1838 ));
1839 }
1840 Rule::interpolation => {
1841 let inner = self.next_inner_pair(&part_pair.clone())?;
1842 let expr = match inner.as_rule() {
1843 Rule::expression => self.parse_expression(&inner)?,
1844 _ => {
1845 return Err(self.create_error_pair(
1846 SpecificError::ExpectedExpressionInInterpolation,
1847 &inner,
1848 ));
1849 }
1850 };
1851
1852 let format = match Self::convert_into_iterator(&part_pair).nth(1) {
1853 Some(fmt) => {
1854 if fmt.as_rule() == Rule::format_specifier {
1855 Some(self.parse_format_specifier(&fmt)?)
1856 } else {
1857 None
1858 }
1859 }
1860 _ => None,
1861 };
1862
1863 parts.push(StringPart::Interpolation(Box::new(expr), format));
1864 }
1865 _ => {
1866 return Err(self.create_error_pair(
1867 SpecificError::UnexpectedRuleInInterpolation,
1868 &part_pair,
1869 ));
1870 }
1871 }
1872 }
1873
1874 Ok(self.create_expr(ExpressionKind::InterpolatedString(parts), pair))
1875 }
1876
1877 fn parse_format_specifier(&self, pair: &Pair<Rule>) -> Result<FormatSpecifier, ParseError> {
1878 let node = self.to_node(pair);
1879 match pair.as_str() {
1880 "x" => Ok(FormatSpecifier::LowerHex(node)),
1881 "X" => Ok(FormatSpecifier::UpperHex(node)),
1882 "b" => Ok(FormatSpecifier::Binary(node)),
1883 "f" => Ok(FormatSpecifier::Float(node)),
1884 s if s.starts_with("..") => {
1885 let precision: u32 = s[2..s.len() - 1].parse().map_err(|_| {
1886 self.create_error_pair(SpecificError::InvalidPrecisionValue, pair)
1887 })?;
1888 let typ = match s.chars().last().unwrap() {
1889 'f' => PrecisionType::Float(node),
1890 's' => PrecisionType::String(node),
1891 _ => {
1892 return Err(
1893 self.create_error_pair(SpecificError::InvalidPrecisionType, pair)
1894 )?;
1895 }
1896 };
1897 Ok(FormatSpecifier::Precision(
1898 precision,
1899 self.to_node(&pair),
1900 typ,
1901 ))
1902 }
1903 _ => Err(self.create_error_pair(SpecificError::InvalidFormatSpecifier, pair)),
1904 }
1905 }
1906
1907 fn parse_enum_literal(&self, pair: &Pair<Rule>) -> Result<LiteralKind, ParseError> {
1908 let mut inner = Self::convert_into_iterator(pair);
1909
1910 let enum_type = self.parse_qualified_type_identifier(&inner.next().unwrap())?;
1912
1913 let variant_pair = Self::expect_next(&mut inner, Rule::type_identifier)?;
1915 let variant_type_identifier = LocalTypeIdentifier::new(self.to_node(&variant_pair));
1916
1917 let enum_variant_literal = match inner.next() {
1919 Some(fields_pair) => match fields_pair.as_rule() {
1920 Rule::anonymous_struct_literal => {
1921 let (field_expressions, detected_rest) =
1922 self.parse_anonymous_struct_literal_fields(pair)?;
1923 EnumVariantLiteral::Struct(
1924 enum_type,
1925 variant_type_identifier,
1926 field_expressions,
1927 detected_rest,
1928 )
1929 }
1930 Rule::tuple_fields => {
1931 let mut expressions = vec![];
1932 for field in Self::convert_into_iterator(&fields_pair) {
1933 let field_value = self.parse_expression(&field)?;
1934 expressions.push(field_value);
1935 }
1936 EnumVariantLiteral::Tuple(enum_type, variant_type_identifier, expressions)
1937 }
1938 _ => {
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}