cortex_lang/parsing/
parser.rs

1use std::collections::HashMap;
2
3use pest::iterators::Pair;
4use pest::Parser;
5use pest_derive::Parser;
6use thiserror::Error;
7
8use crate::constants::{INDEX_SET_FN_NAME, INDEX_GET_FN_NAME};
9
10use super::ast::{expression::{Expression, BinaryOperator, ConditionBody, IdentExpression, OptionalIdentifier, Parameter, PathIdent, UnaryOperator}, program::Program, statement::Statement, top_level::{BasicBody, Body, Bundle, Function, Struct, ThisArg, TopLevel}, r#type::CortexType};
11
12#[derive(Parser)]
13#[grammar = "grammar.pest"] // relative to src
14struct PestCortexParser;
15
16pub struct CortexParser;
17
18#[derive(Error, Debug)]
19pub enum ParseError {
20    #[error("Failed to parse statement '{0}'")]
21    FailStatement(String),
22    #[error("Failed to parse expression '{0}'")]
23    FailExpression(String),
24    #[error("Failed to parse atom '{0}'")]
25    FailAtom(String),
26    #[error("Failed to parse expression tail '{0}'")]
27    FailTail(String),
28    #[error("Failed to parse path '{0}'")]
29    FailPath(String),
30    #[error("Failed to parse identifier '{0}'")]
31    FailOptionalIdentifier(String),
32    #[error("Failed to parse type '{0}'")]
33    FailType(String),
34    #[error("Failed to parse top level declaration '{0}'")]
35    FailTopLevel(String),
36    #[error("Operator does not exist '{0}'")]
37    OperatorDoesNotExist(String),
38    #[error("Failed to parse program")]
39    FailProgram,
40    #[error("Failed to parse {0}: {1}")]
41    ParseFailure(String, String),
42}
43
44impl CortexParser {
45    pub fn parse_statement(input: &str) -> Result<Statement, ParseError> {
46        let pair = PestCortexParser::parse(Rule::statement, input);
47        match pair {
48            Ok(mut v) => Self::parse_stmt_pair(v.next().unwrap()),
49            Err(e) => {
50                Err(ParseError::ParseFailure(String::from("statement"), String::from(e.line())))
51            },
52        }
53    }
54    pub fn parse_expression(input: &str) -> Result<Expression, ParseError> {
55        let pair = PestCortexParser::parse(Rule::expr, input);
56        match pair {
57            Ok(mut v) => Self::parse_expr_pair(v.next().unwrap()),
58            Err(e) => {
59                Err(ParseError::ParseFailure(String::from("expression"), String::from(e.line())))
60            },
61        }
62    }
63    pub fn parse_type(input: &str) -> Result<CortexType, ParseError> {
64        let pair = PestCortexParser::parse(Rule::typ, input);
65        match pair {
66            Ok(mut v) => Self::parse_type_pair(v.next().unwrap()),
67            Err(e) => {
68                Err(ParseError::ParseFailure(String::from("type"), String::from(e.line())))
69            },
70        }
71    }
72    pub fn parse_function(input: &str) -> Result<Function, ParseError> {
73        let pair = PestCortexParser::parse(Rule::function, input);
74        match pair {
75            Ok(mut v) => Self::parse_func_pair(v.next().unwrap()),
76            Err(e) => {
77                Err(ParseError::ParseFailure(String::from("function"), String::from(e.line())))
78            },
79        }
80    }
81    pub fn parse_struct(input: &str) -> Result<Struct, ParseError> {
82        let pair = PestCortexParser::parse(Rule::r#struct, input);
83        match pair {
84            Ok(mut v) => Self::parse_struct_pair(v.next().unwrap()),
85            Err(e) => {
86                Err(ParseError::ParseFailure(String::from("struct"), String::from(e.line())))
87            },
88        }
89    }
90    pub fn parse_bundle(input: &str) -> Result<Bundle, ParseError> {
91        let pair = PestCortexParser::parse(Rule::bundle, input);
92        match pair {
93            Ok(mut v) => Self::parse_bundle_pair(v.next().unwrap()),
94            Err(e) => {
95                Err(ParseError::ParseFailure(String::from("bundle"), String::from(e.line())))
96            },
97        }
98    }
99    pub fn parse_top_level(input: &str) -> Result<TopLevel, ParseError> {
100        let pair = PestCortexParser::parse(Rule::topLevel, input);
101        match pair {
102            Ok(mut v) => Self::parse_toplevel_pair(v.next().unwrap()),
103            Err(e) => {
104                Err(ParseError::ParseFailure(String::from("top level"), String::from(e.line())))
105            },
106        }
107    }
108    pub fn parse_path(input: &str) -> Result<PathIdent, ParseError> {
109        let pair = PestCortexParser::parse(Rule::pathIdent, input);
110        match pair {
111            Ok(mut v) => Self::parse_path_ident(v.next().unwrap()),
112            Err(e) => {
113                Err(ParseError::ParseFailure(String::from("path"), String::from(e.line())))
114            },
115        }
116    }
117    pub fn parse_program(input: &str) -> Result<Program, ParseError> {
118        let pair = PestCortexParser::parse(Rule::program, input);
119        match pair {
120            Ok(mut v) => Self::parse_program_pair(v.next().unwrap()),
121            Err(e) => {
122                Err(ParseError::ParseFailure(String::from("program"), String::from(e.line())))
123            },
124        }
125    }
126    
127    fn parse_program_pair(pair: Pair<Rule>) -> Result<Program, ParseError> {
128        let pairs = pair.into_inner();
129        let mut content = Vec::<TopLevel>::new();
130        for p in pairs {
131            if p.as_rule() != Rule::EOI {
132                let t = Self::parse_toplevel_pair(p)?;
133                content.push(t);
134            }
135        }
136        Ok(Program { content: content })
137    }
138
139    fn parse_toplevel_pair(mut pair: Pair<Rule>) -> Result<TopLevel, ParseError> {
140        pair = pair.into_inner().next().unwrap();
141        match pair.as_rule() {
142            Rule::function => {
143                Ok(TopLevel::Function(Self::parse_func_pair(pair)?))
144            },
145            Rule::r#struct => {
146                Ok(TopLevel::Struct(Self::parse_struct_pair(pair)?))
147            },
148            Rule::bundle => {
149                Ok(TopLevel::Bundle(Self::parse_bundle_pair(pair)?))
150            },
151            Rule::import => {
152                let name: &str;
153                let mut is_string = false;
154                let p = pair.into_inner().next().unwrap();
155                if p.as_rule() == Rule::string {
156                    name = p.into_inner().next().unwrap().as_str();
157                    is_string = true;
158                } else {
159                    name = p.as_str();
160                }
161                Ok(TopLevel::Import { name: String::from(name), is_string_import: is_string })
162            },
163            Rule::module => {
164                let mut pairs = pair.into_inner();
165                let name = pairs.next().unwrap().as_str();
166                let mut contents = Vec::<TopLevel>::new();
167                for p in pairs {
168                    let toplevel = Self::parse_toplevel_pair(p)?;
169                    contents.push(toplevel);
170                }
171                Ok(TopLevel::Module { name: String::from(name), contents: contents })
172            },
173            _ => Err(ParseError::FailTopLevel(String::from(pair.as_str()))),
174        }
175    }
176
177    fn parse_stmt_pair(mut pair: Pair<Rule>) -> Result<Statement, ParseError> {
178        pair = pair.into_inner().next().unwrap();
179        let orig = pair.as_str();
180        match pair.as_rule() {
181            Rule::expr => {
182                let expression = Self::parse_expr_pair(pair)?;
183                Ok(Statement::Expression(expression))
184            },
185            Rule::throw => {
186                let expression = Self::parse_expr_pair(pair.into_inner().next().unwrap())?;
187                Ok(Statement::Throw(expression))
188            },
189            Rule::varDec => {
190                let is_const = pair.as_str().starts_with("const");
191                let mut pairs = pair.into_inner();
192                let name = Self::parse_opt_ident(pairs.next().unwrap())?;
193                let third_pair = pairs.next().unwrap();
194                let mut typ: Option<CortexType> = None;
195                let init_value = 
196                    if third_pair.as_rule() == Rule::typ {
197                        typ = Some(Self::parse_type_pair(third_pair)?);
198                        Self::parse_expr_pair(pairs.next().unwrap())?
199                    } else {
200                        Self::parse_expr_pair(third_pair)?
201                    };
202                Ok(Statement::VariableDeclaration { 
203                    name: name,
204                    is_const: is_const,
205                    typ: typ,
206                    initial_value: init_value,
207                })
208            },
209            Rule::varAssign => {
210                let mut pairs = pair.into_inner();
211                let left = Self::parse_ident_expr(pairs.next().unwrap())?;
212                let value;
213                let next = pairs.next().unwrap();
214                match next.as_rule() {
215                    Rule::arithLogicBinOp => {
216                        let left_as_expr = left.clone().to_member_access_expr();
217                        let op = Self::parse_binop(next.into_inner().next().unwrap())?;
218                        let right = Self::parse_expr_pair(pairs.next().unwrap())?;
219                        value = Expression::BinaryOperation { 
220                            left: Box::new(left_as_expr),
221                            op,
222                            right: Box::new(right),
223                        };
224                    },
225                    Rule::expr => {
226                        value = Self::parse_expr_pair(next)?;
227                    },
228                    _ => return Err(ParseError::FailStatement(String::from(orig)))
229                }
230
231                Ok(Statement::Assignment { 
232                    name: left,
233                    value: value,
234                })
235            },
236            Rule::indexVarAssign => {
237                let mut pairs = pair.into_inner();
238                let left = Self::parse_ident_expr(pairs.next().unwrap())?;
239                let mut args = Self::parse_expr_list(pairs.next().unwrap())?;
240                let next = pairs.next().unwrap();
241                let value;
242                match next.as_rule() {
243                    Rule::arithLogicBinOp => {
244                        let left_as_expr = left.clone().to_member_access_expr();
245                        let full_left_expr = Expression::MemberCall { 
246                            callee: Box::new(left_as_expr),
247                            member: String::from(INDEX_GET_FN_NAME), 
248                            args: args.clone()
249                        };
250                        let op = Self::parse_binop(next.into_inner().next().unwrap())?;
251                        let right = Self::parse_expr_pair(pairs.next().unwrap())?;
252                        value = Expression::BinaryOperation { 
253                            left: Box::new(full_left_expr), 
254                            op, 
255                            right: Box::new(right), 
256                        };
257                    },
258                    Rule::expr => {
259                        value = Self::parse_expr_pair(next)?;
260                    },
261                    _ => return Err(ParseError::FailStatement(String::from(orig)))
262                }
263                
264                args.push(value);
265
266                Ok(Statement::Expression(
267                    Expression::MemberCall { 
268                        callee: Box::new(left.to_member_access_expr()), 
269                        member: String::from(INDEX_SET_FN_NAME), 
270                        args, 
271                    }
272                ))
273            },
274            Rule::r#while => {
275                let mut pairs = pair.into_inner();
276                let cond = Self::parse_expr_pair(pairs.next().unwrap())?;
277                let body = Self::parse_body(pairs.next().unwrap())?;
278                Ok(Statement::WhileLoop(ConditionBody { condition: cond, body: body }))
279            },
280            _ => Err(ParseError::FailStatement(String::from(pair.as_str()))),
281        }
282    }
283
284    fn parse_expr_pair(pair: Pair<Rule>) -> Result<Expression, ParseError> {
285        Self::parse_logic_result(pair)
286    }
287    fn parse_logic_result(pair: Pair<Rule>) -> Result<Expression, ParseError> {
288        let mut pairs = pair.into_inner().peekable();
289        let mut result = Self::parse_eq_result(pairs.next().unwrap())?;
290        while pairs.peek() != None {
291            let op = Self::parse_binop(pairs.next().unwrap())?;
292            let right = Self::parse_eq_result(pairs.next().unwrap())?;
293            result = Expression::BinaryOperation { 
294                left: Box::new(result), 
295                op, 
296                right: Box::new(right),
297            };
298        }
299        Ok(result)
300    }
301    fn parse_eq_result(pair: Pair<Rule>) -> Result<Expression, ParseError> {
302        let mut pairs = pair.into_inner().peekable();
303        let mut result = Self::parse_sum_result(pairs.next().unwrap())?;
304        while pairs.peek() != None {
305            let op = Self::parse_binop(pairs.next().unwrap())?;
306            let right = Self::parse_sum_result(pairs.next().unwrap())?;
307            result = Expression::BinaryOperation { 
308                left: Box::new(result), 
309                op, 
310                right: Box::new(right),
311            };
312        }
313        Ok(result)
314    }
315    fn parse_sum_result(pair: Pair<Rule>) -> Result<Expression, ParseError> {
316        let mut pairs = pair.into_inner().peekable();
317        let mut result = Self::parse_mul_result(pairs.next().unwrap())?;
318        while pairs.peek() != None {
319            let op = Self::parse_binop(pairs.next().unwrap())?;
320            let right = Self::parse_mul_result(pairs.next().unwrap())?;
321            result = Expression::BinaryOperation { 
322                left: Box::new(result), 
323                op, 
324                right: Box::new(right),
325            };
326        }
327        Ok(result)
328    }
329    fn parse_mul_result(pair: Pair<Rule>) -> Result<Expression, ParseError> {
330        let mut pairs = pair.into_inner().peekable();
331        let mut result = Self::parse_primary(pairs.next().unwrap())?;
332        while pairs.peek() != None {
333            let op = Self::parse_binop(pairs.next().unwrap())?;
334            let right = Self::parse_primary(pairs.next().unwrap())?;
335            result = Expression::BinaryOperation { 
336                left: Box::new(result), 
337                op, 
338                right: Box::new(right),
339            };
340        }
341        Ok(result)
342    }
343
344    fn parse_primary(pair: Pair<Rule>) -> Result<Expression, ParseError> {
345        let mut pairs = pair.into_inner();
346        let atom_pair = pairs.next().unwrap();
347        let atom = Self::parse_atom_pair(atom_pair.into_inner().next().unwrap())?;
348        let next = pairs.next();
349        if next.is_some() {
350            let expr_tail_pair = next.unwrap();
351            Ok(Self::handle_expr_tail_pair(expr_tail_pair, atom)?)
352        } else {
353            Ok(atom)
354        }
355    }
356
357    fn parse_atom_pair(pair: Pair<Rule>) -> Result<Expression, ParseError> {
358        match pair.as_rule() {
359            Rule::number => {
360                let value: f64 = pair.as_str().parse().unwrap();
361                Ok(Expression::Number(value))
362            },
363            Rule::boolean => {
364                let value: bool = pair.as_str().parse().unwrap();
365                Ok(Expression::Boolean(value))
366            },
367            Rule::string => {
368                Ok(Expression::String(String::from(pair.into_inner().next().unwrap().as_str())))
369            },
370            Rule::none => {
371                Ok(Expression::None)
372            },
373            Rule::void => {
374                Ok(Expression::Void)
375            },
376            Rule::pathIdent => {
377                Ok(Expression::PathIdent(Self::parse_path_ident(pair)?))
378            },
379            Rule::expr => {
380                Ok(Self::parse_expr_pair(pair)?)
381            },
382            Rule::call => {
383                let mut pairs = pair.into_inner();
384                let first_pair = pairs.next().unwrap();
385                let name = Self::parse_path_ident(first_pair)?;
386                let args_pair = pairs.next().unwrap();
387                let args = Self::parse_expr_list(args_pair)?;
388                Ok(Expression::Call(name, args))
389            },
390            Rule::structConstruction => {
391                let mut pairs = pair.into_inner().peekable();
392                let name = Self::parse_path_ident(pairs.next().unwrap())?;
393                let type_args;
394                if pairs.peek().unwrap().as_rule() == Rule::typeList {
395                    type_args = pairs.next().unwrap().into_inner().map(|s| Self::parse_type_pair(s)).collect::<Result<Vec<_>, _>>()?;
396                } else {
397                    type_args = vec![];
398                }
399                let mut assignments = Vec::new();
400                for p in pairs {
401                    let mut member_init = p.into_inner();
402                    let name = member_init.next().unwrap().as_str();
403                    let expr = Self::parse_expr_pair(member_init.next().unwrap())?;
404                    assignments.push((String::from(name), expr));
405                }
406                Ok(Expression::Construction { name: name, assignments: assignments, type_args: type_args })
407            },
408            Rule::r#if => {
409                let mut pairs = pair.into_inner();
410                let first_cond = Self::parse_expr_pair(pairs.next().unwrap())?;
411                let first_body = Self::parse_body(pairs.next().unwrap())?;
412                let elifs_pair = pairs.next().unwrap();
413                let elifs_pairs = elifs_pair.into_inner();
414                let mut elifs = Vec::<ConditionBody>::new();
415                for p in elifs_pairs {
416                    elifs.push(Self::parse_condition_body(p)?);
417                }
418                let op_else_pair = pairs.next();
419                let else_body = 
420                    if let Some(else_pair) = op_else_pair {
421                        Some(Box::new(Self::parse_body(else_pair.into_inner().next().unwrap())?))
422                    } else {
423                        None
424                    };
425
426                Ok(Expression::IfStatement { 
427                    first: Box::new(ConditionBody { condition: first_cond, body: first_body }),
428                    conds: elifs,
429                    last: else_body,
430                })
431            },
432            Rule::unOpAtom => {
433                let mut pairs = pair.into_inner();
434                let unop = Self::parse_unop(pairs.next().unwrap())?;
435                let expr = Self::parse_expr_pair(pairs.next().unwrap())?;
436                Ok(Expression::UnaryOperation { op: unop, exp: Box::new(expr) })
437            },
438            Rule::listLiteral => {
439                let mut pairs = pair.into_inner();
440                let items = Self::parse_expr_list(pairs.next().unwrap())?;
441                Ok(Expression::ListLiteral(items))
442            },
443            _ => Err(ParseError::FailAtom(String::from(pair.as_str()))),
444        }
445    }
446
447    fn handle_expr_tail_pair(pair: Pair<Rule>, exp: Expression) -> Result<Expression, ParseError> {
448        match pair.as_rule() {
449            Rule::exprTail => {
450                if let Some(tail_pair) = pair.into_inner().next() {
451                    match tail_pair.as_rule() {
452                        Rule::postfixBangTail => {
453                            Ok(Self::handle_expr_tail_pair(
454                                tail_pair.into_inner().next().unwrap(),
455                                Expression::Bang(Box::new(exp))
456                            )?)
457                        },
458                        Rule::memberAccessTail => {
459                            let mut pairs = tail_pair.into_inner();
460                            let member = pairs.next().unwrap().as_str();
461                            Ok(Self::handle_expr_tail_pair(
462                                pairs.next().unwrap(),
463                                Expression::MemberAccess(Box::new(exp), String::from(member))
464                            )?)
465                        },
466                        Rule::memberCallTail => {
467                            let mut pairs = tail_pair.into_inner();
468                            let member = pairs.next().unwrap().as_str();
469                            let args_pair = pairs.next().unwrap();
470                            let args = Self::parse_expr_list(args_pair)?;
471                            Ok(Self::handle_expr_tail_pair(
472                                pairs.next().unwrap(),
473                                Expression::MemberCall { callee: Box::new(exp), member: String::from(member), args }
474                            )?)
475                        },
476                        Rule::indexTail => {
477                            let mut pairs = tail_pair.into_inner();
478                            let args_pair = pairs.next().unwrap();
479                            let args = Self::parse_expr_list(args_pair)?;
480                            Ok(Self::handle_expr_tail_pair(
481                                pairs.next().unwrap(),
482                                Expression::MemberCall { callee: Box::new(exp), member: String::from(INDEX_GET_FN_NAME), args }
483                            )?)
484                        },
485                        _ => Err(ParseError::FailTail(String::from(tail_pair.as_str()))),
486                    }
487                } else {
488                    Ok(exp)
489                }
490            }
491            _ => Err(ParseError::FailTail(String::from(pair.as_str()))),
492        }
493    }
494
495    fn parse_condition_body(pair: Pair<Rule>) -> Result<ConditionBody, ParseError> {
496        let mut pairs = pair.into_inner();
497        let cond = Self::parse_expr_pair(pairs.next().unwrap())?;
498        let body = Self::parse_body(pairs.next().unwrap())?;
499        Ok(ConditionBody {
500            condition: cond,
501            body: body,
502        })
503    }
504
505    fn parse_binop(pair: Pair<Rule>) -> Result<BinaryOperator, ParseError> {
506        match pair.as_rule() {
507            Rule::add => Ok(BinaryOperator::Add),
508            Rule::sub => Ok(BinaryOperator::Subtract),
509            Rule::mul => Ok(BinaryOperator::Multiply),
510            Rule::div => Ok(BinaryOperator::Divide),
511            Rule::rem => Ok(BinaryOperator::Remainder),
512            Rule::and => Ok(BinaryOperator::LogicAnd),
513            Rule::or => Ok(BinaryOperator::LogicOr),
514            Rule::eq => Ok(BinaryOperator::IsEqual),
515            Rule::neq => Ok(BinaryOperator::IsNotEqual),
516            Rule::lt => Ok(BinaryOperator::IsLessThan),
517            Rule::lte => Ok(BinaryOperator::IsLessThanOrEqualTo),
518            Rule::gt => Ok(BinaryOperator::IsGreaterThan),
519            Rule::gte => Ok(BinaryOperator::IsGreaterThanOrEqualTo),
520            _ => Err(ParseError::OperatorDoesNotExist(String::from(pair.as_str()))),
521        }
522    }
523    fn parse_unop(pair: Pair<Rule>) -> Result<UnaryOperator, ParseError> {
524        match pair.as_rule() {
525            Rule::negate => Ok(UnaryOperator::Negate),
526            Rule::invert => Ok(UnaryOperator::Invert),
527            _ => Err(ParseError::OperatorDoesNotExist(String::from(pair.as_str()))),
528        }
529    }
530
531    fn parse_path_ident(pair: Pair<Rule>) -> Result<PathIdent, ParseError> {
532        let mut names = Vec::<String>::new();
533        for p in pair.into_inner() {
534            let name = String::from(p.as_str());
535            names.push(name);
536        }
537        Ok(PathIdent {
538            path: names,
539        })
540    }
541
542    fn parse_ident_expr(pair: Pair<Rule>) -> Result<IdentExpression, ParseError> {
543        let mut pairs = pair.into_inner();
544        let first = pairs.next().unwrap().as_str();
545        let mut chain = Vec::new();
546        for p in pairs {
547            chain.push(String::from(p.as_str()));
548        }
549        Ok(IdentExpression {
550            base: String::from(first),
551            chain: chain,
552        })
553    }
554
555    fn parse_type_pair(pair: Pair<Rule>) -> Result<CortexType, ParseError> {
556        let pair_str = pair.as_str();
557        let optional = pair_str.ends_with("?");
558        let main = pair.into_inner().next().unwrap();
559        match main.as_rule() {
560            Rule::basicType => {
561                let mut pairs = main.into_inner();
562                let ident = Self::parse_path_ident(pairs.next().unwrap())?;
563                let mut type_args = Vec::new();
564                if let Some(type_args_top_pair) = pairs.next() {
565                    let type_arg_pairs = type_args_top_pair.into_inner();
566                    for typ_pair in type_arg_pairs {
567                        type_args.push(Self::parse_type_pair(typ_pair)?);
568                    }
569                }
570                Ok(CortexType::basic(ident, optional, type_args))
571            },
572            Rule::refType => {
573                let typ = Self::parse_type_pair(main.into_inner().next().unwrap())?;
574                let mutable = pair_str.starts_with("&mut");
575                Ok(CortexType::reference(typ, mutable))
576            },
577            _ => Err(ParseError::FailType(String::from(pair_str)))
578        }
579    }
580
581    fn parse_opt_ident(pair: Pair<Rule>) -> Result<OptionalIdentifier, ParseError> {
582        if pair.as_str() == "~" {
583            Ok(OptionalIdentifier::Ignore)
584        } else {
585            Ok(OptionalIdentifier::Ident(String::from(pair.as_str())))
586        }
587    }
588
589    fn parse_struct_pair(pair: Pair<Rule>) -> Result<Struct, ParseError> {
590        let mut pairs = pair.into_inner();
591        let name = Self::parse_opt_ident(pairs.next().unwrap())?;
592        let mut type_args = Vec::new();
593        let next = pairs.next().unwrap();
594        let field_params;
595        if matches!(next.as_rule(), Rule::typeArgList) {
596            let type_arg_pairs = next.into_inner();
597            for ident in type_arg_pairs {
598                type_args.push(ident.as_str());
599            }
600            field_params = Self::parse_param_list(pairs.next().unwrap())?;
601        } else {
602            field_params = Self::parse_param_list(next)?;
603        }
604        let mut fields = HashMap::new();
605        for p in field_params {
606            fields.insert(p.name, p.typ);
607        }
608        
609        Ok(
610            Struct { 
611                name: name,
612                fields: fields,
613                type_param_names: type_args.into_iter().map(|s| String::from(s)).collect(),
614            }
615        )
616    }
617    fn parse_bundle_pair(pair: Pair<Rule>) -> Result<Bundle, ParseError> {
618        let mut pairs = pair.into_inner();
619        let name = Self::parse_opt_ident(pairs.next().unwrap())?;
620        let mut type_args = Vec::new();
621        let next = pairs.next().unwrap();
622        let field_params;
623        if matches!(next.as_rule(), Rule::typeArgList) {
624            let type_arg_pairs = next.into_inner();
625            for ident in type_arg_pairs {
626                type_args.push(ident.as_str());
627            }
628            field_params = Self::parse_param_list(pairs.next().unwrap())?;
629        } else {
630            field_params = Self::parse_param_list(next)?;
631        }
632        let functions = Self::parse_bundle_func_list(pairs.next().unwrap())?;
633
634        let mut fields = HashMap::new();
635        for p in field_params {
636            fields.insert(p.name, p.typ);
637        }
638        
639        Ok(
640            Bundle { 
641                name: name,
642                fields: fields,
643                functions: functions,
644                type_param_names: type_args.into_iter().map(|s| String::from(s)).collect(),
645            }
646        )
647    }
648
649    fn parse_func_pair(pair: Pair<Rule>) -> Result<Function, ParseError> {
650        let mut pairs = pair.into_inner().peekable();
651        let name = Self::parse_opt_ident(pairs.next().unwrap())?;
652
653        let mut type_args = Vec::new();
654        let next = pairs.next().unwrap();
655        let params;
656        if matches!(next.as_rule(), Rule::typeArgList) {
657            let type_arg_pairs = next.into_inner();
658            for ident in type_arg_pairs {
659                type_args.push(ident.as_str());
660            }
661            params = Self::parse_param_list(pairs.next().unwrap())?;
662        } else {
663            params = Self::parse_param_list(next)?;
664        }
665
666        let return_type = if matches!(pairs.peek().unwrap().as_rule(), Rule::typ) {
667            Self::parse_type_pair(pairs.next().unwrap())?
668        } else {
669            CortexType::void(false)
670        };
671        let body = Self::parse_body(pairs.next().unwrap())?;
672        Ok(Function {
673            name: name,
674            params: params,
675            return_type: return_type,
676            body: Body::Basic(body),
677            this_arg: ThisArg::None,
678            type_param_names: type_args.into_iter().map(|s| String::from(s)).collect(),
679        })
680    }
681    fn parse_bundle_function(pair: Pair<Rule>) -> Result<Function, ParseError> {
682        let mut pairs = pair.into_inner().peekable();
683        let name = Self::parse_opt_ident(pairs.next().unwrap())?;
684
685        let mut type_args = Vec::new();
686        let next = pairs.next().unwrap();
687        let this_arg;
688        if matches!(next.as_rule(), Rule::typeArgList) {
689            let type_arg_pairs = next.into_inner();
690            for ident in type_arg_pairs {
691                type_args.push(ident.as_str());
692            }
693            this_arg = 
694                if matches!(pairs.next().unwrap().as_rule(), Rule::this) {
695                    ThisArg::This
696                } else {
697                    ThisArg::MutThis
698                };
699        } else {
700            this_arg = 
701                if matches!(next.as_rule(), Rule::this) {
702                    ThisArg::This
703                } else {
704                    ThisArg::MutThis
705                };
706        }
707        
708        let params = Self::parse_param_list(pairs.next().unwrap())?;
709        
710        let return_type = if matches!(pairs.peek().unwrap().as_rule(), Rule::typ) {
711            Self::parse_type_pair(pairs.next().unwrap())?
712        } else {
713            CortexType::void(false)
714        };
715        let body = Self::parse_body(pairs.next().unwrap())?;
716        Ok(Function {
717            name: name,
718            params: params,
719            return_type: return_type,
720            body: Body::Basic(body),
721            this_arg: this_arg,
722            type_param_names: type_args.into_iter().map(|s| String::from(s)).collect(),
723        })
724    }
725
726    fn parse_bundle_func_list(pair: Pair<Rule>) -> Result<Vec<Function>, ParseError> {
727        let pairs = pair.into_inner();
728        let mut result = Vec::new();
729        for p in pairs {
730            result.push(Self::parse_bundle_function(p)?);
731        }
732        Ok(result)
733    }
734
735    fn parse_expr_list(pair: Pair<Rule>) -> Result<Vec<Expression>, ParseError> {
736        let pairs = pair.into_inner();
737        let mut result = Vec::new();
738        for p in pairs {
739            result.push(Self::parse_expr_pair(p)?);
740        }
741        Ok(result)
742    }
743
744    fn parse_param_list(pair: Pair<Rule>) -> Result<Vec<Parameter>, ParseError> {
745        let pairs = pair.into_inner();
746        let mut result = Vec::new();
747        for p in pairs {
748            result.push(Self::parse_param(p)?);
749        }
750        Ok(result)
751    }
752    fn parse_param(pair: Pair<Rule>) -> Result<Parameter, ParseError> {
753        let mut pairs = pair.into_inner();
754        let ident = pairs.next().unwrap().as_str();
755        let typ = Self::parse_type_pair(pairs.next().unwrap())?;
756        Ok(
757            Parameter {
758                name: String::from(ident),
759                typ: typ,
760            }
761        )
762    }
763
764    fn parse_body(pair: Pair<Rule>) -> Result<BasicBody, ParseError> {
765        let mut result: Option<Expression> = None;
766        let mut statements = Vec::<Statement>::new();
767
768        let mut iter = pair.into_inner().peekable();
769        while let Some(p) = iter.next() {
770            let is_last = iter.peek().is_none();
771            if is_last {
772                if p.as_rule() == Rule::expr {
773                    result = Some(Self::parse_expr_pair(p)?);
774                } else {
775                    statements.push(Self::parse_stmt_pair(p)?);
776                }
777            } else {
778                statements.push(Self::parse_stmt_pair(p)?);
779            }
780        }
781        Ok(
782            BasicBody {
783                statements: statements,
784                result: result,
785            }
786        )
787    }
788}