ryna/
parser.rs

1use std::collections::{ HashMap, HashSet };
2use std::cell::RefCell;
3use std::str::FromStr;
4use std::sync::Arc;
5
6use malachite::num::conversion::string::options::FromSciStringOptions;
7use malachite::num::conversion::traits::FromSciString;
8use nom::multi::many1;
9use nom::AsChar;
10use nom::bytes::complete::{tag, take_till, take_until};
11use nom::combinator::{cut, map_opt};
12use nom::error::{VerboseError, VerboseErrorKind, context};
13use nom::sequence::preceded;
14use nom::{
15    IResult,
16    combinator::{map, map_res, opt, eof, value, recognize},
17    bytes::complete::{take_while, take_while1, escaped_transform},
18    sequence::{tuple, delimited, terminated},
19    branch::alt,
20    character::complete::{multispace1, satisfy},
21    multi::{separated_list1, separated_list0}
22};
23
24use nom_locate::LocatedSpan;
25use rustc_hash::FxHashSet;
26use malachite::Integer;
27use serde::{Deserialize, Serialize};
28
29use crate::annotations::{parse_annotation, Annotation};
30use crate::config::ImportMap;
31use crate::functions::Function;
32use crate::interfaces::{InterfaceConstraint, Interface};
33use crate::macros::{parse_ryna_macro, RdlMacro, RynaMacroType};
34use crate::operations::Operator;
35use crate::object::{Object, TypeInstance};
36use crate::precedence_cache::PrecedenceCache;
37use crate::types::*;
38use crate::operations::*;
39use crate::context::RynaContext;
40use crate::patterns::*;
41
42pub type Span<'a> = LocatedSpan<&'a str>;
43pub type PResult<'a, T> = IResult<Span<'a>, T, VerboseError<Span<'a>>>;
44pub type PCache<'a> = RefCell<PrecedenceCache<PResult<'a, RynaExpr>>>;
45
46type UnaryOpHeader = (usize, Vec<String>, String, Type, Type);
47type BinaryOpHeader = (usize, Vec<String>, (String, Type), (String, Type), Type);
48type NaryOpHeader = (usize, Vec<String>, (String, Type), Vec<(String, Type)>, Type);
49type FunctionHeader = (String, Option<Vec<String>>, Vec<(String, Type)>, Type);
50
51type AnnotUnaryOpHeader = (Vec<Annotation>, usize, Vec<String>, String, Type, Type);
52type AnnotBinaryOpHeader = (Vec<Annotation>, usize, Vec<String>, (String, Type), (String, Type), Type);
53type AnnotNaryOpHeader = (Vec<Annotation>, usize, Vec<String>, (String, Type), Vec<(String, Type)>, Type);
54type AnnotFunctionHeader = (Vec<Annotation>, String, Option<Vec<String>>, Vec<(String, Type)>, Type);
55
56#[derive(Debug, PartialEq, Clone, Eq)]
57pub enum InterfaceHeader {
58    UnaryOpHeader(Vec<Annotation>, usize, Vec<String>, String, Type, Type),
59    BinaryOpHeader(Vec<Annotation>, usize, Vec<String>, (String, Type), (String, Type), Type),
60    NaryOpHeader(Vec<Annotation>, usize, Vec<String>, (String, Type), Vec<(String, Type)>, Type),
61    FunctionHeader(Vec<Annotation>, String, Option<Vec<String>>, Vec<(String, Type)>, Type)
62}
63
64pub fn verbose_error<'a>(input: Span<'a>, msg: &'static str) -> nom::Err<VerboseError<Span<'a>>> {
65    nom::Err::Error(VerboseError { 
66        errors: vec!(
67            (input, VerboseErrorKind::Context(msg))
68        ) 
69    })
70}
71
72#[allow(clippy::derived_hash_with_manual_eq)]
73#[derive(Debug, Clone, Eq, Hash, Default, Serialize, Deserialize)]
74pub struct Location {
75    pub line: usize,
76    pub column: usize,
77    pub span: String,
78    pub module: Arc<String>
79}
80
81lazy_static! {
82    static ref NO_MOD: Arc<String> = Arc::new(String::new());
83}
84
85impl Location {    
86    pub fn new(line: usize, column: usize, span: String, module: Arc<String>) -> Self {
87        Location { line, column, span, module }
88    }
89
90    pub fn none() -> Self {
91        Self::new(0, 0, "".into(), NO_MOD.clone())
92    }
93}
94
95impl PartialEq for Location {
96    fn eq(&self, _: &Self) -> bool {
97        true// Always equal
98    }
99}
100
101fn normal_comment(input: Span<'_>) -> PResult<'_, Span<'_>> {
102    preceded(
103        tag("//"),
104        alt((
105            recognize(tuple((take_until("\n"), tag("\n")))),
106            recognize(take_till(|_| false))
107        ))
108    )(input)
109}
110
111fn block_comment(input: Span<'_>) -> PResult<'_, Span<'_>> {
112    delimited(
113        tag("/*"),
114        take_until("*/"),
115        tag("*/")
116    )(input)
117}
118
119fn separator(input: Span<'_>) -> PResult<'_, Span<'_>> {
120    alt((
121        multispace1,
122        block_comment,
123        normal_comment
124    ))(input)
125}
126
127fn skip_token(input: Span<'_>) -> PResult<'_, ()> {
128    return alt((
129        map(block_comment, |_| ()),
130        map(normal_comment, |_| ()),
131        map(multispace1, |_| ()),
132        map(|input| identifier_parser(input), |_| ()),
133        map(|input| string_parser(input), |_| ()),
134        map(satisfy(|_| true), |_| ()), // skip one char
135    ))(input);
136}
137
138pub fn empty0(mut input: Span<'_>) -> PResult<'_, ()> {
139    while let Ok((i, _)) = separator(input) {
140        input = i;
141    }
142    
143    Ok((input, ()))
144}
145
146pub fn empty1(mut input: Span<'_>) -> PResult<'_, ()> {
147    input = separator(input)?.0;
148
149    while let Ok((i, _)) = separator(input) {
150        input = i;
151    }
152    
153    Ok((input, ()))
154}
155
156pub fn many_separated0<
157    'a, OP, OS, 
158    P: FnMut(Span<'a>) -> PResult<'a, OP>, 
159    S: FnMut(Span<'a>) -> PResult<'a, OS>
160>(mut separator: S, mut parser: P) -> impl FnMut(Span<'a>) -> PResult<'a, Vec<OP>> {
161    move |mut input| {
162        let mut res = vec!();
163        let mut first = true;
164        
165        loop {
166            if !first {
167                let (new_input, _) = separator(input)?;
168                input = new_input;    
169            }
170
171            match parser(input) {
172                Ok((new_input, elem)) => {
173                    res.push(elem);
174                    input = new_input;
175                },
176
177                Err(nom::Err::Failure(err)) => {
178                    return Err(nom::Err::Failure(err));
179                }
180    
181                Err(_) => return Ok((input, res))
182            }
183
184            first = false;
185        }
186    } 
187}
188
189/*
190                                                  ╒══════════════════╕
191    ============================================= │  IMPLEMENTATION  │ =============================================
192                                                  ╘══════════════════╛
193*/
194
195#[derive(Debug, PartialEq, Clone, Eq, Serialize, Deserialize)]
196pub enum RynaExpr {
197    // Compiled
198    QualifiedName(Location, String, Option<usize>), // In this order, function id, attribute name
199    Variable(Location, usize, String, Type, bool),
200    CompiledVariableDefinition(Location, usize, String, Type, Box<RynaExpr>, bool),
201    CompiledVariableAssignment(Location, usize, String, Type, Box<RynaExpr>, bool),
202    FunctionCall(Location, usize, Vec<Type>, Vec<RynaExpr>),
203    CompiledFor(Location, usize, usize, String, Box<RynaExpr>, Vec<RynaExpr>),
204    DoBlock(Location, Vec<RynaExpr>, Type),
205    AttributeAccess(Location, Box<RynaExpr>, usize),
206    AttributeAssignment(Location, Box<RynaExpr>, Box<RynaExpr>, usize),
207    Break(Location),
208    Continue(Location),
209
210    CompiledLambda(Location, usize, Vec<(String, RynaExpr)>, Vec<(String, Type)>, Type, Vec<RynaExpr>),
211
212    // Macro
213    Macro(Location, Vec<Annotation>, String, RynaMacroType, Pattern, RdlMacro),
214
215    // Uncompiled
216    Literal(Location, Object),
217    Tuple(Location, Vec<RynaExpr>),
218    Lambda(Location, Vec<String>, Vec<(String, Type)>, Type, Vec<RynaExpr>),
219    NameReference(Location, String),
220
221    UnaryOperation(Location, usize, Vec<Type>, Box<RynaExpr>),
222    BinaryOperation(Location, usize, Vec<Type>, Box<RynaExpr>, Box<RynaExpr>),
223    NaryOperation(Location, usize, Vec<Type>, Box<RynaExpr>, Vec<RynaExpr>),
224
225    VariableDefinition(Location, String, Type, Box<RynaExpr>),
226    VariableAssignment(Location, String, Box<RynaExpr>),
227    FunctionDefinition(Location, Vec<Annotation>, usize, Vec<String>, Vec<(String, Type)>, Type, Vec<RynaExpr>),
228    PrefixOperatorDefinition(Location, String, usize),
229    PostfixOperatorDefinition(Location, String, usize),
230    BinaryOperatorDefinition(Location, String, bool, usize),
231    NaryOperatorDefinition(Location, String, String, usize),
232    ClassDefinition(Location, Vec<Annotation>, String, Vec<String>, Vec<(String, Type)>, Option<Type>, Vec<Pattern>),
233    InterfaceDefinition(Location, Vec<Annotation>, String, Vec<String>, Vec<AnnotFunctionHeader>, Vec<AnnotUnaryOpHeader>, Vec<AnnotBinaryOpHeader>, Vec<AnnotNaryOpHeader>),
234    InterfaceImplementation(Location, Vec<String>, Type, String, Vec<Type>),
235
236    PrefixOperationDefinition(Location, Vec<Annotation>, usize, Vec<String>, String, Type, Type, Vec<RynaExpr>),
237    PostfixOperationDefinition(Location, Vec<Annotation>, usize, Vec<String>, String, Type, Type, Vec<RynaExpr>),
238    BinaryOperationDefinition(Location, Vec<Annotation>, usize, Vec<String>, (String, Type), (String, Type), Type, Vec<RynaExpr>),
239    NaryOperationDefinition(Location, Vec<Annotation>, usize, Vec<String>, (String, Type), Vec<(String, Type)>, Type, Vec<RynaExpr>),
240
241    If(Location, Box<RynaExpr>, Vec<RynaExpr>, Vec<(RynaExpr, Vec<RynaExpr>)>, Option<Vec<RynaExpr>>),
242    While(Location, Box<RynaExpr>, Vec<RynaExpr>),
243    For(Location, String, Box<RynaExpr>, Vec<RynaExpr>),
244    Return(Location, Box<RynaExpr>)
245}
246
247impl RynaExpr {
248    pub fn is_definition(&self) -> bool {
249        match self {
250            RynaExpr::Macro(_, _, _, _, _, _) |
251            RynaExpr::PrefixOperatorDefinition(_, _, _) |
252            RynaExpr::PostfixOperatorDefinition(_, _, _) |
253            RynaExpr::BinaryOperatorDefinition(_, _, _, _) |
254            RynaExpr::NaryOperatorDefinition(_, _, _, _) |
255            RynaExpr::ClassDefinition(_, _, _, _, _, _, _) |
256            RynaExpr::InterfaceDefinition(_, _, _, _, _, _, _, _) |
257            RynaExpr::InterfaceImplementation(_, _, _, _, _) |
258            RynaExpr::FunctionDefinition(_, _, _, _, _, _, _) |
259            RynaExpr::PrefixOperationDefinition(_, _, _, _, _, _, _, _) |
260            RynaExpr::PostfixOperationDefinition(_, _, _, _, _, _, _, _) |
261            RynaExpr::BinaryOperationDefinition(_, _, _, _, _, _, _, _) |
262            RynaExpr::NaryOperationDefinition(_, _, _, _, _, _, _, _) => true,
263
264            RynaExpr::VariableDefinition(_, _, _, _) |
265            RynaExpr::VariableAssignment(_, _, _) |
266            RynaExpr::QualifiedName(_, _, _) |
267            RynaExpr::CompiledVariableDefinition(_, _, _, _, _, _) |
268            RynaExpr::CompiledVariableAssignment(_, _, _, _, _, _) |
269            RynaExpr::DoBlock(_, _, _) |
270            RynaExpr::AttributeAccess(_, _, _) |
271            RynaExpr::AttributeAssignment(_, _, _, _) |
272            RynaExpr::Variable(_, _, _, _, _) |
273            RynaExpr::FunctionCall(_, _, _, _) |
274            RynaExpr::CompiledFor(_, _, _, _, _, _) |
275            RynaExpr::CompiledLambda(_, _, _, _, _, _) |
276            RynaExpr::Literal(_, _) |
277            RynaExpr::Tuple(_, _) |
278            RynaExpr::Lambda(_, _, _, _, _) |
279            RynaExpr::NameReference(_, _) |
280            RynaExpr::UnaryOperation(_, _, _, _) |
281            RynaExpr::BinaryOperation(_, _, _, _, _) |
282            RynaExpr::NaryOperation(_, _, _, _, _) |
283            RynaExpr::If(_, _, _, _, _) |
284            RynaExpr::While(_, _, _) |
285            RynaExpr::Break(_) |
286            RynaExpr::Continue(_) |
287            RynaExpr::For(_, _, _, _) |
288            RynaExpr::Return(_, _) => false,
289        }
290    }
291
292    pub fn is_expr(&self) -> bool {
293        match self {
294            RynaExpr::AttributeAssignment(_, _, _, _) |
295            RynaExpr::NameReference(_, _) |
296            RynaExpr::CompiledVariableDefinition(_, _, _, _, _, _) |
297            RynaExpr::CompiledVariableAssignment(_, _, _, _, _, _) |
298            RynaExpr::Macro(_, _, _, _, _, _) |
299            RynaExpr::VariableDefinition(_, _, _, _) |
300            RynaExpr::VariableAssignment(_, _, _) |
301            RynaExpr::PrefixOperatorDefinition(_, _, _) |
302            RynaExpr::PostfixOperatorDefinition(_, _, _) |
303            RynaExpr::BinaryOperatorDefinition(_, _, _, _) |
304            RynaExpr::NaryOperatorDefinition(_, _, _, _) |
305            RynaExpr::ClassDefinition(_, _, _, _, _, _, _) |
306            RynaExpr::InterfaceDefinition(_, _, _, _, _, _, _, _) |
307            RynaExpr::InterfaceImplementation(_, _, _, _, _) |
308            RynaExpr::PrefixOperationDefinition(_, _, _, _, _, _, _, _) |
309            RynaExpr::PostfixOperationDefinition(_, _, _, _, _, _, _, _) |
310            RynaExpr::BinaryOperationDefinition(_, _, _, _, _, _, _, _) |
311            RynaExpr::NaryOperationDefinition(_, _, _, _, _, _, _, _) |
312            RynaExpr::FunctionDefinition(_, _, _, _, _, _, _) |
313            RynaExpr::If(_, _, _, _, _) |
314            RynaExpr::While(_, _, _) |
315            RynaExpr::Break(_) |
316            RynaExpr::Continue(_) |
317            RynaExpr::For(_, _, _, _) |
318            RynaExpr::CompiledFor(_, _, _, _, _, _) |
319            RynaExpr::Return(_, _) => false,
320
321            RynaExpr::DoBlock(_, _, _) |
322            RynaExpr::QualifiedName(_, _, _) |
323            RynaExpr::AttributeAccess(_, _, _) |
324            RynaExpr::Variable(_, _, _, _, _) |
325            RynaExpr::FunctionCall(_, _, _, _) |
326            RynaExpr::CompiledLambda(_, _, _, _, _, _) |
327            RynaExpr::Literal(_, _) |
328            RynaExpr::Tuple(_, _) |
329            RynaExpr::Lambda(_, _, _, _, _) |
330            RynaExpr::UnaryOperation(_, _, _, _) |
331            RynaExpr::BinaryOperation(_, _, _, _, _) |
332            RynaExpr::NaryOperation(_, _, _, _, _)  => true,
333        }
334    }
335}
336
337#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
338pub enum ImportType {
339    Interface, Class, Fn, Prefix, Postfix, Binary, Nary, Syntax, Line(usize), All
340}
341
342pub fn get_op_chain(expr: RynaExpr, id: usize) -> (Vec<RynaExpr>, Vec<Vec<Type>>) {
343    match expr {
344        RynaExpr::BinaryOperation(_, id2, t, a, b) if id == id2 => {
345            let (mut chain_a, mut t_a) = get_op_chain(*a, id);
346            let (chain_b, t_b) = get_op_chain(*b, id);
347
348            t_a.push(t);
349            t_a.extend(t_b);
350            chain_a.extend(chain_b);
351
352            (chain_a, t_a)
353        }
354
355        _ => (vec!(expr), vec!())
356
357    }
358}
359
360pub fn to_right_assoc(expr: RynaExpr) -> RynaExpr {
361    let (l, id) = match &expr {
362        RynaExpr::BinaryOperation(l, id, _, _, _) => (l.clone(), *id),
363        _ => unreachable!()
364    };
365
366    let (exprs, ts) = get_op_chain(expr, id);
367    let mut chain = exprs.into_iter();
368    let mut res = chain.next().unwrap();
369    
370    if chain.len() > 0 {
371        for (e, t) in chain.zip(ts) {
372            res = RynaExpr::BinaryOperation(
373                l.clone(), id, t,
374                Box::new(res), Box::new(e)
375            );    
376        }
377    }
378
379    res
380}
381
382pub fn identifier_parser(input: Span<'_>) -> PResult<'_, String> {
383    map(
384        tuple((
385            take_while1(|c: char| c == '_' || c.is_alphabetic()),
386            take_while(|c: char| c == '_' || c.is_alphanumeric())
387        )),
388        |(a, b)| format!("{}{}", a, b)
389    )(input)
390}
391
392pub fn string_parser(input: Span<'_>) -> PResult<'_, String> {
393    delimited(
394        tag("\""), 
395        alt((
396            escaped_transform(
397                satisfy(|i| i != '"' && i != '\\'), 
398                '\\', 
399                alt((
400                    value("\n", tag("n")),
401                    value("\t", tag("t")),
402                    value("\"", tag("\"")),
403                    value("\\", tag("\\"))
404                ))
405            ),
406            value(String::new(), tag(""))
407        )),
408        tag("\"")
409    )(input)
410}
411
412fn parse_import_location(input: Span<'_>, module: Arc<String>) -> PResult<String> {
413    alt((
414        identifier_parser,
415        map(
416            preceded(
417                tag("/"),
418                separated_list1(tag("/"), identifier_parser)
419            ),
420            |s| format!(
421                "{}/{}", 
422                module.split('/').next().unwrap(), // Append parent module's name
423                s.join("/")
424            )
425        )
426    ))(input)
427}
428
429fn module_import_parser(input: Span<'_>, module: Arc<String>) -> PResult<'_, (String, ImportType, HashSet<String>)> {
430    map(
431        tuple((
432            tag("import"),
433            empty1,
434            alt((
435                map(
436                    tuple((
437                        tag("*"),
438                        empty1
439                    )),
440                    |_| (ImportType::All, (), vec!("*".into()))
441                ),
442                tuple((
443                    context(
444                        "Expected import type after 'import' keyword",
445                        cut(alt((
446                            value(ImportType::Interface, tag("interface")),
447                            value(ImportType::Class, tag("class")),
448                            value(ImportType::Fn, tag("fn")),
449                            value(ImportType::Syntax, tag("syntax")),
450                            value(ImportType::Prefix, tuple((tag("prefix"), empty1, tag("op")))),
451                            value(ImportType::Postfix, tuple((tag("postfix"), empty1, tag("op")))),
452                            value(ImportType::Binary, tuple((tag("binary"), empty1, tag("op")))),
453                            value(ImportType::Nary, tuple((tag("nary"), empty1, tag("op")))),
454                        )))
455                    ),
456                    empty1,
457                    context(
458                        "Expected a String, an identifier or a brace-enclosed list of identifiers after import type",
459                        cut(alt((
460                            map(
461                                tuple((
462                                    alt((
463                                        string_parser,
464                                        identifier_parser,
465                                        map(tag("*"), |i: Span<'_>| i.to_string())
466                                    )),
467                                    empty1
468                                )),
469                                |(s, _)| vec!(s)
470                            ),
471                            map(
472                                tuple((
473                                    tag("{"),
474                                    empty0,
475                                    separated_list1(
476                                        tuple((empty0, tag(","), empty0)),
477                                        alt((
478                                            string_parser,
479                                            identifier_parser
480                                        ))
481                                    ),
482                                    empty0,
483                                    tag("}"),
484                                    empty0
485                                )),
486                                |(_, _, v, _, _, _)| v
487                            )
488                        )))
489                    )
490                ))
491            )),
492            context("Expected 'from' after import type", cut(tag("from"))),
493            empty1,
494            context("Expected identifier after 'from' in import statement", cut(|i| parse_import_location(i, module.clone()))),
495            empty0,
496            context("Expected ';' at the end of import statement", cut(tag(";")))
497        )),
498        |(_, _, (t, _, v), _, _, n, _, _)| (n, t, v.into_iter().collect())
499    )(input)
500}
501
502pub fn ryna_info_parser(input: Span<'_>, module: Arc<String>) -> PResult<'_, ()> {
503    delimited(
504        empty0,
505        value((), |i| module_import_parser(i, module.clone())),
506        empty0
507    )(input)
508}
509
510pub fn ryna_module_imports_parser(mut input: Span<'_>, module: Arc<String>) -> PResult<'_, ImportMap> {
511    let mut ops: HashMap<String, HashMap<ImportType, HashSet<String>>> = HashMap::new();
512
513    while input.len() > 0 {
514        if let Ok((i, (n, t, v))) = module_import_parser(input, module.clone()) {
515            input = i;
516            ops.entry(n).or_default().entry(t).or_default().extend(v);
517        
518        } else {
519            input = skip_token(input)?.0;
520        }
521    }
522
523    Ok(("".into(), ops))
524}
525
526impl RynaExpr {
527    pub fn compile_types(&mut self, templates: &Vec<String>) {
528        match self {
529            RynaExpr::VariableDefinition(_, _, t, e) => {
530                t.compile_templates(templates);
531                e.compile_types(templates);
532            }
533
534            RynaExpr::Tuple(_, e) => {
535                e.iter_mut().for_each(|i| i.compile_types(templates));
536            }
537
538            RynaExpr::UnaryOperation(_, _, t, e) => {
539                t.iter_mut().for_each(|i| i.compile_templates(templates));
540                e.compile_types(templates);
541            },
542
543            RynaExpr::BinaryOperation(_, _, t, a, b) => {
544                t.iter_mut().for_each(|i| i.compile_templates(templates));
545                a.compile_types(templates);
546                b.compile_types(templates);
547            },
548            RynaExpr::NaryOperation(_, _, t, a, b) => {
549                t.iter_mut().for_each(|i| i.compile_templates(templates));
550                a.compile_types(templates);
551                b.iter_mut().for_each(|i| i.compile_types(templates));
552            },
553
554            RynaExpr::If(_, h, ib, ei, eb) => {
555                h.compile_types(templates);
556                ib.iter_mut().for_each(|i| i.compile_types(templates));
557
558                ei.iter_mut().for_each(|(ei_h, ei_b)| {
559                    ei_h.compile_types(templates); 
560                    ei_b.iter_mut().for_each(|i| i.compile_types(templates));                   
561                });
562
563                if let Some(eb_inner) = eb {
564                    eb_inner.iter_mut().for_each(|i| i.compile_types(templates));
565                }
566            }
567
568            RynaExpr::Lambda(_, _, a, r, b) => {
569                a.iter_mut().for_each(|(_, t)| {
570                    t.compile_templates(templates);
571                });
572
573                r.compile_templates(templates);
574
575                b.iter_mut().for_each(|i| i.compile_types(templates));
576            }
577            
578            RynaExpr::While(_, c, b) |
579            RynaExpr::For(_, _, c, b) => {
580                c.compile_types(templates);
581                b.iter_mut().for_each(|i| i.compile_types(templates));
582            },
583
584            RynaExpr::Return(_, e) => e.compile_types(templates),
585
586            _ => {}
587        }
588    }
589}
590
591impl RynaContext {
592    // Parser combinator that allows to store the precise location of an element
593    pub fn located<'a, O, P1: FnMut(Span<'a>) -> PResult<'a, O>>(&'a self, mut parser: P1) -> impl FnMut(Span<'a>) -> PResult<'a, (Location, O)> {
594        move |input| {
595            let (rest, res) = parser(input)?;
596
597            let line = input.location_line() as usize;
598            let column = input.get_column();
599            let span = &input[..(input.len() - rest.len())];
600
601            Ok((rest, (Location::new(line, column, span.to_string(), self.module_name.clone()), res)))
602        }
603    }
604
605    /*
606        ╒═══════════════════╕
607        │ Auxiliary methods │
608        ╘═══════════════════╛
609    */
610    
611    pub fn get_type_id(&self, name: String) -> Result<usize, String> {
612        return self.cache.class_id.get(name, |name| {
613            self.type_templates.iter().find(|t| t.name == name).map(|i| i.id).ok_or(format!("No type with name {}", name))
614        });
615    }
616    
617    pub fn get_interface_id(&self, name: String) -> Result<usize, String> {
618        return self.cache.interface_id.get(name, |name| {
619            self.interfaces.iter().find(|t| t.name == name).map(|i| i.id).ok_or(format!("No interface with name {}", name))
620        });
621    }
622    
623    pub fn get_function_id(&self, name: String) -> Result<usize, String> {
624        return self.cache.function_id.get(name, |name| {
625            self.functions.iter().find(|t| t.name == name).map(|i| i.id).ok_or(format!("No function with name {}", name))
626        });
627    }
628    
629    pub fn get_function(&self, name: &str) -> Option<&Function> {
630        match self.get_function_id(name.to_string()) {
631            Ok(id) => Some(&self.functions[id]),
632            Err(_) => None,
633        }
634    }
635    
636    pub fn get_interface(&self, name: &str) -> Option<&Interface> {
637        match self.get_interface_id(name.to_string()) {
638            Ok(id) => Some(&self.interfaces[id]),
639            Err(_) => None,
640        }
641    }
642    
643    pub fn get_type_template(&self, name: &str) -> Option<&TypeTemplate> {
644        match self.get_type_id(name.to_string()) {
645            Ok(id) => Some(&self.type_templates[id]),
646            Err(_) => None,
647        }
648    }
649
650    /*
651        ╒═════════════════╕
652        │ Type subparsers │
653        ╘═════════════════╛
654    */
655
656    fn wildcard_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
657        map(tag("*"), |_| Type::Wildcard)(input)
658    }
659
660    fn empty_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
661        map(tag("()"), |_| Type::Empty)(input)
662    }
663
664    fn self_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
665        map(tag("Self"), |_| Type::SelfType)(input)
666    }
667
668    fn basic_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
669        map_res(identifier_parser, |n| Result::<_, String>::Ok(Type::Basic(self.get_type_id(n)?)))(input)
670    }
671
672    fn interface_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, usize> {
673        map_res(identifier_parser, |n| self.get_interface_id(n))(input)
674    }
675
676    fn template_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
677        return map(
678            tuple((
679                tag("'"),
680                context("Invalid template identifier", cut(identifier_parser)),
681                opt(tuple((
682                    empty0,
683                    tag("["),
684                    empty0,
685                    separated_list1(
686                        tuple((empty0, tag(","), empty0)), 
687                        tuple((
688                            context("Invalid interface name", cut(|input| self.interface_parser(input))),
689                            opt(delimited(
690                                tuple((tag("<"), empty0)),
691                                separated_list1(
692                                    tuple((empty0, tag(","), empty0)), 
693                                    |input| self.type_parser(input)
694                                ),
695                                tuple((empty0, tag(">"))),
696                            ))
697                        ))
698                    ),
699                    empty0,
700                    tag("]"),
701                )))
702            )), 
703            |(_, n, w)| Type::TemplateParamStr(n, w.map(|(_, _, _, v, _, _)| {
704                v.into_iter().map(|(id, t)| InterfaceConstraint::new(id, t.unwrap_or_default())).collect()
705            }).unwrap_or_default())
706        )(input);
707    }
708
709    fn constant_reference_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
710        return map(
711            tuple((
712                tag("&"),
713                context("Invalid constant refence type", cut(|input| self.type_parser(input)))
714            )), 
715            |(_, t)| Type::Ref(Box::new(t))
716        )(input);
717    }
718
719    fn mutable_reference_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
720        return map(
721            tuple((
722                tag("@"),
723                context("Invalid mutable reference type", cut(|input| self.type_parser(input)))
724            )), 
725            |(_, t)| Type::MutRef(Box::new(t))
726        )(input);
727    }
728
729    fn or_type_parser<'a>(&'a self, input: Span<'a>, func: bool) -> PResult<'a, Type> {
730        return map(
731            separated_list1(
732                tuple((empty0, tag("|"), empty0)), 
733                |input| self.type_parser_wrapper(input, func, false)
734            ),
735            |t| if t.len() > 1 { Type::Or(t) } else { t[0].clone() }
736        )(input);
737    }
738
739    fn and_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
740        return map(
741            delimited(
742                tag("("),
743                tuple((
744                    separated_list1(
745                        tuple((empty0, tag(","), empty0)), 
746                        |input| self.type_parser(input)
747                    ),
748                    delimited(empty0, opt(tag(",")), empty0)
749                )),
750                tag(")")
751            ),
752            |(t, c)| if c.is_some() || t.len() > 1 { Type::And(t) } else { t[0].clone() }
753        )(input);
754    }
755
756    fn parametric_type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
757        return map_res(
758            tuple((
759                identifier_parser,
760                empty0,
761                tag("<"),
762                empty0,
763                separated_list1(
764                    tuple((empty0, tag(","), empty0)), 
765                    |input| self.type_parser(input)
766                ),
767                empty0,
768                context("Expected '>' at the end of parametric type", cut(tag(">")))
769            )),
770            |(n, _, _, _, t, _, _)| Result::<_, String>::Ok(Type::Template(self.get_type_id(n)?, t))
771        )(input);
772    }
773
774    fn function_type_parser<'a>(&'a self, input: Span<'a>, or: bool) -> PResult<'a, Type> {
775        return map(
776            tuple((
777                |input| self.type_parser_wrapper(input, false, or),
778                empty0,
779                tag("=>"),
780                empty0,
781                |input| self.type_parser_wrapper(input, false, or),
782            )),
783            |(f, _, _, _, t)| Type::Function(Box::new(f), Box::new(t))
784        )(input);
785    }
786
787    fn type_parser_wrapper<'a>(&'a self, input: Span<'a>, func: bool, or: bool) -> PResult<'a, Type> {
788        return match (func, or) {
789            (true, true) => alt((
790                |input| self.function_type_parser(input, or),
791                |input| self.and_type_parser(input),
792                |input| self.or_type_parser(input, func),
793                |input| self.empty_type_parser(input),
794                |input| self.self_type_parser(input),
795                |input| self.wildcard_type_parser(input),
796                |input| self.mutable_reference_type_parser(input),
797                |input| self.constant_reference_type_parser(input),
798                |input| self.parametric_type_parser(input),
799                |input| self.template_type_parser(input),
800                |input| self.basic_type_parser(input)
801            ))(input),
802
803            (false, true) => alt((
804                |input| self.and_type_parser(input),
805                |input| self.or_type_parser(input, func),
806                |input| self.empty_type_parser(input),
807                |input| self.self_type_parser(input),
808                |input| self.wildcard_type_parser(input),
809                |input| self.mutable_reference_type_parser(input),
810                |input| self.constant_reference_type_parser(input),
811                |input| self.parametric_type_parser(input),
812                |input| self.template_type_parser(input),
813                |input| self.basic_type_parser(input)
814            ))(input),
815
816            (true, false) => alt((
817                |input| self.function_type_parser(input, or),
818                |input| self.and_type_parser(input),
819                |input| self.empty_type_parser(input),
820                |input| self.self_type_parser(input),
821                |input| self.wildcard_type_parser(input),
822                |input| self.mutable_reference_type_parser(input),
823                |input| self.constant_reference_type_parser(input),
824                |input| self.parametric_type_parser(input),
825                |input| self.template_type_parser(input),
826                |input| self.basic_type_parser(input)
827            ))(input),
828            
829            (false, false) => alt((
830                |input| self.and_type_parser(input),
831                |input| self.empty_type_parser(input),
832                |input| self.self_type_parser(input),
833                |input| self.wildcard_type_parser(input),
834                |input| self.mutable_reference_type_parser(input),
835                |input| self.constant_reference_type_parser(input),
836                |input| self.parametric_type_parser(input),
837                |input| self.template_type_parser(input),
838                |input| self.basic_type_parser(input)
839            ))(input),
840        };
841    }
842
843    pub fn type_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Type> {
844        return self.type_parser_wrapper(input, true, true);
845    }
846
847    /*
848        ╒═════════════════╕
849        │ Expr subparsers │
850        ╘═════════════════╛
851    */
852
853    fn bool_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, bool> {
854        alt((
855            map(tag("true"), |_| true),
856            map(tag("false"), |_| false),
857        ))(input)
858    }
859
860    fn char_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Integer> {
861        map(
862            delimited(
863                tag("'"),
864                alt((
865                    satisfy(|i| i != '\'' && i != '\\'), 
866                    map_res(
867                        preceded(
868                            tag("\\"),
869                            satisfy(|i| i != '\'' && i != '\\'), 
870                        ),
871                        |i| match i {
872                            'n'=> Ok('\n'),
873                            't'=> Ok('\t'),
874                            '\"'=> Ok('\"'),
875                            '\\'=> Ok('\\'),        
876                            _ => Err(())
877                        }
878                    ), 
879                )),
880                tag("'")
881            ),
882            |c| Integer::from(c as u64)
883        )(input)
884    }
885
886    fn integer_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Integer> {
887        return map(
888            tuple((
889                opt(tag("-")),
890                take_while1(|c: char| c.is_ascii_digit())
891            )),
892            |(s, n)| Integer::from_str(format!("{}{}", s.unwrap_or(Span::new("")), n).as_str()).unwrap()
893        )(input);
894    }
895
896    fn binary_integer_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Integer> {
897        return map(
898            preceded(
899                tag("0b"),
900                take_while1(|c: char| c == '0' || c == '1')
901            ),
902            |n: Span<'a>| {
903                let mut options = FromSciStringOptions::default();
904                options.set_base(2);
905
906                Integer::from_sci_string_with_options(n.to_string().as_str(), options).unwrap()
907            }
908        )(input);
909    }
910
911    fn hex_integer_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Integer> {
912        return map(
913            preceded(
914                tag("0x"),
915                take_while1(|c: char| c.is_hex_digit())
916            ),
917            |n: Span<'a>| {
918                let mut options = FromSciStringOptions::default();
919                options.set_base(16);
920
921                Integer::from_sci_string_with_options(n.to_string().as_str(), options).unwrap()
922            }
923        )(input);
924    }
925
926    fn float_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, f64> {
927        map(
928            tuple((
929                opt(tag("-")),
930                take_while1(|c: char| c.is_ascii_digit()),
931                map_opt(
932                    tuple((
933                        opt(
934                            map(
935                                preceded(
936                                    tag("."),
937                                    take_while1(|c: char| c.is_ascii_digit()),        
938                                ),
939                                |s| format!(".{s}")
940                            )
941                        ),
942                        opt(
943                            preceded(
944                                alt((tag("e"), tag("E"))),
945                                map(
946                                    tuple((
947                                        opt(tag("-")),
948                                        take_while1(|c: char| c.is_ascii_digit())                
949                                    )),
950                                    |(s, n)| format!("e{}{}", s.unwrap_or_else(|| "".into()), n)
951                                )
952                            )
953                        )
954                    )),
955                    |r| {
956                        match r {
957                            (None, None) => None,
958                            (None, Some(a)) => Some(a),
959                            (Some(a), None) => Some(a),
960                            (Some(a), Some(b)) => Some(format!("{a}{b}")),
961                        }
962                    }
963                )
964            )),
965            |(s, n, d)| format!("{}{}{}", s.unwrap_or(Span::new("")), n, d).parse().unwrap()
966        )(input)
967    }
968
969    pub fn parse_literal_type<'a>(&'a self, c_type: &'a TypeTemplate, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, Object> {
970        for p in &c_type.patterns {
971            let res = map_res(
972                |input| p.extract(input, self, cache),
973                |args| Result::<Object, String>::Ok(Object::new(TypeInstance {
974                    id: c_type.id,
975                    params: vec!(),
976                    attributes: c_type.attributes.iter().map(|(n, t)| {
977                        if !args.contains_key(n) {
978                            return Err(format!("RDL extraction results map does not contain the attribute {}", n));
979                        }
980
981                        if let Type::Basic(t_id) = t {  
982                            return self.type_templates[*t_id].parser.unwrap()(self, &self.type_templates[*t_id], &args[n][0]);
983                        }
984
985                        if let Type::Template(ARR_ID, t) = t {  
986                            if let &[Type::Basic(t_id)] = &t[..] {
987                                return args[n].iter().cloned()
988                                    .map(|arg| self.type_templates[t_id].parser.unwrap()(self, &self.type_templates[t_id], &arg))
989                                    .collect::<Result<Vec<_>, _>>()
990                                    .map(|r| Object::arr(r, Type::Basic(t_id)));
991                            }
992
993                            unimplemented!();
994                        }
995
996                        unimplemented!();
997
998                    }).collect::<Result<Vec<Object>, String>>()?
999                }))
1000            )(input);
1001
1002            if res.is_ok() {
1003                return res;
1004            }
1005        }
1006
1007        return Err(verbose_error(input, "Unable to parse"));
1008    }
1009
1010    fn custom_literal_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, Object> {
1011        for c in &self.type_templates {
1012            let res = self.parse_literal_type(c, input, cache);
1013
1014            if res.is_ok() {
1015                return res;
1016            }
1017        }
1018
1019        return Err(verbose_error(input, "Unable to parse"));
1020    }
1021    
1022    fn literal_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1023        return map(
1024            self.located(
1025                alt((
1026                    |input| self.custom_literal_parser(input, cache),
1027                    map(|input| self.bool_parser(input), Object::new),
1028                    map(|input| self.float_parser(input), Object::new),
1029                    map(|input| self.binary_integer_parser(input), Object::new),
1030                    map(|input| self.hex_integer_parser(input), Object::new),
1031                    map(|input| self.integer_parser(input), Object::new),
1032                    map(|input| self.char_parser(input), Object::new),
1033                    map(string_parser, Object::new),
1034                ))
1035            ),
1036            |(l, o)| RynaExpr::Literal(l, o)
1037        )(input);
1038    }
1039    
1040    fn custom_syntax_parser<'a>(&'a self, mut input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1041        for m in self.macros.iter().filter(|i| i.m_type != RynaMacroType::Block) {
1042            if let Ok((new_input, args)) = m.pattern.extract(input, self, cache) {
1043                let span = &input[..input.len() - new_input.len()];
1044                let loc = Location::new(input.location_line() as usize, input.get_column(), span.to_string(), self.module_name.clone());
1045
1046                input = new_input;
1047
1048                match m.generator.expand(&args, self) {
1049                    Ok(code) => {
1050                        let parsed_code = match m.m_type {
1051                            RynaMacroType::Function => {
1052                                cut(
1053                                    map(
1054                                        many_separated0(
1055                                            empty0, 
1056                                            |input| self.ryna_line_parser(input, &RefCell::default()) // Fresh cache for macro parsing
1057                                        ),
1058                                        |i| i.into_iter().flatten().collect()
1059                                    )
1060                                )(Span::new(&code))
1061                            },
1062                            
1063                            RynaMacroType::Expression => {
1064                                cut(
1065                                    map(
1066                                        |input| self.ryna_expr_parser(input, &RefCell::default()),
1067                                        |i| vec!(i)
1068                                    )
1069                                )(Span::new(&code))
1070                            },
1071                            
1072                            RynaMacroType::Rdl |
1073                            RynaMacroType::Block => unreachable!(),
1074                        };
1075                        
1076                        match parsed_code {
1077                            Ok((rest, mut lines)) if rest.trim().is_empty() => {
1078                                return match m.m_type {
1079                                    RynaMacroType::Function => {
1080                                        Ok((
1081                                            input, 
1082                                            RynaExpr::DoBlock(loc.clone(), lines, Type::InferenceMarker)
1083                                        ))
1084                                    },
1085
1086                                    RynaMacroType::Expression => {                                        
1087                                        if lines.len() == 1 {
1088                                            let expr = lines.pop().unwrap();
1089
1090                                            if expr.is_expr() {
1091                                                Ok((input, expr))
1092                                            
1093                                            } else {
1094                                                Err(nom::Err::Failure(VerboseError { errors: vec!((
1095                                                    input, 
1096                                                    VerboseErrorKind::Context("Expression macro did not get an expression after expansion")
1097                                                )) }))    
1098                                            }
1099                                        
1100                                        } else {
1101                                            Err(nom::Err::Failure(VerboseError { errors: vec!((
1102                                                input, 
1103                                                VerboseErrorKind::Context("Expression macro got more than one expression")
1104                                            )) }))
1105                                        }
1106                                    },
1107
1108                                    RynaMacroType::Rdl |
1109                                    RynaMacroType::Block => unreachable!(),
1110                                }
1111                            },
1112
1113                            Ok(_) |
1114                            Err(nom::Err::Error(_)) |
1115                            Err(nom::Err::Failure(_)) => {                                
1116                                return Err(nom::Err::Failure(VerboseError { errors: vec!((
1117                                    input, 
1118                                    VerboseErrorKind::Context("Error while parsing expanded code")
1119                                )) }));
1120                            }
1121
1122                            _ => unreachable!()
1123                        }
1124                    },
1125
1126                    Err(_) => {
1127                        return Err(verbose_error(input, "Unable to parse"))
1128                    }
1129                }
1130            }
1131        }
1132
1133        return Err(verbose_error(input, "Unable to parse"))
1134    }
1135
1136    fn custom_syntax_block_parser<'a>(&'a self, mut input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, Vec<RynaExpr>> {
1137        let prev_input = input;
1138
1139        for m in self.macros.iter().filter(|i| i.m_type == RynaMacroType::Block) {            
1140            if let Ok((new_input, args)) = m.pattern.extract(input, self, cache) {
1141                input = new_input;
1142
1143                match m.generator.expand(&args, self) {
1144                    Ok(code) => {
1145                        let parsed_code = cut(
1146                            map(
1147                                many_separated0(
1148                                    empty0, 
1149                                    |input| self.ryna_line_parser(input, &RefCell::default()) // Fresh cache for macro parsing
1150                                ),
1151                                |i| i.into_iter().flatten().collect()
1152                            )
1153                        )(Span::new(&code));
1154
1155                        match parsed_code {
1156                            Ok((rest, lines)) if rest.trim().is_empty() => {
1157                                return match m.m_type {
1158                                    RynaMacroType::Block => Ok((input, lines)),
1159                                    _ => unreachable!(),
1160                                }
1161                            },
1162
1163                            Ok(_) |
1164                            Err(nom::Err::Error(_)) |
1165                            Err(nom::Err::Failure(_)) => {                                
1166                                return Err(nom::Err::Failure(VerboseError { errors: vec!((
1167                                    prev_input, 
1168                                    VerboseErrorKind::Context("Error while parsing expanded code")
1169                                )) }));
1170                            }
1171
1172                            _ => unreachable!()
1173                        }
1174                    }
1175
1176                    Err(_) => {
1177                        return Err(verbose_error(prev_input, "Unable to parse"))
1178                    }
1179                }
1180            }
1181        }
1182
1183        return Err(verbose_error(prev_input, "Unable to parse"))
1184    }
1185    
1186    fn variable_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1187        return map(
1188            self.located(identifier_parser),
1189            |(l, v)| RynaExpr::NameReference(l, v)
1190        )(input);
1191    }
1192    
1193    fn prefix_operation_parser<'a>(&'a self, input: Span<'a>, id: usize, rep: &str, checked_precs: &mut FxHashSet<usize>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1194        return map(
1195            self.located(
1196                tuple((
1197                    tag(rep),
1198                    empty0,
1199                    opt(
1200                        map(
1201                            tuple((
1202                                tag("<"),
1203                                empty0,
1204                                separated_list1(
1205                                    tuple((empty0, tag(","), empty0)), 
1206                                    |input| self.type_parser(input)
1207                                ),
1208                                empty0,
1209                                tag(">"),
1210                                empty0,
1211                            )),
1212                            |(_, _, t, _, _, _)| t
1213                        )
1214                    ),
1215                    |input| self.ryna_expr_parser_wrapper(input, checked_precs, cache)
1216                ))
1217            ),
1218            |(l, (_, _, t, e))| RynaExpr::UnaryOperation(l, id, t.unwrap_or_default(), Box::new(e))
1219        )(input);
1220    }
1221    
1222    fn postfix_operation_parser<'a>(&'a self, input: Span<'a>, id: usize, rep: &str, prec: usize, checked_precs: &mut FxHashSet<usize>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1223        let mut checked_cpy = checked_precs.clone();
1224        checked_cpy.insert(prec);
1225
1226        map(
1227            self.located(
1228                tuple((
1229                    move |input| self.ryna_expr_parser_wrapper(input, &mut checked_cpy, cache),
1230                    empty0,
1231                    opt(
1232                        map(
1233                            tuple((
1234                                tag("<"),
1235                                empty0,
1236                                separated_list1(
1237                                    tuple((empty0, tag(","), empty0)), 
1238                                    |input| self.type_parser(input)
1239                                ),
1240                                empty0,
1241                                tag(">"),
1242                                empty0,
1243                            )),
1244                            |(_, _, t, _, _, _)| t
1245                        )
1246                    ),
1247                    tag(rep)
1248                ))
1249            ),
1250            |(l, (e, _, t, _))| RynaExpr::UnaryOperation(l, id, t.unwrap_or_default(), Box::new(e))
1251        )(input)
1252    }
1253    
1254    fn binary_operation_parser<'a>(&'a self, input: Span<'a>, id: usize, rep: &str, prec: usize, checked_precs: &mut FxHashSet<usize>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1255        let mut checked_cpy = checked_precs.clone();
1256        checked_cpy.insert(prec);
1257
1258        let (input, a) = self.ryna_expr_parser_wrapper(input, &mut checked_cpy, cache)?;
1259
1260        map(
1261            self.located(
1262                tuple((
1263                    empty0,
1264                    opt(
1265                        map(
1266                            tuple((
1267                                tag("<"),
1268                                empty0,
1269                                separated_list1(
1270                                    tuple((empty0, tag(","), empty0)), 
1271                                    |input| self.type_parser(input)
1272                                ),
1273                                empty0,
1274                                tag(">"),
1275                                empty0,
1276                            )),
1277                            |(_, _, t, _, _, _)| t
1278                        )
1279                    ),
1280                    tag(rep),
1281                    empty0,
1282                    |input| self.ryna_expr_parser_wrapper(input, checked_precs, cache)
1283                ))
1284            ),
1285            move |(l, (_, t, _, _, b))| {
1286                let mut res = RynaExpr::BinaryOperation(l, id, t.unwrap_or_default(), Box::new(a.clone()), Box::new(b));
1287                
1288                if self.binary_ops[id].is_right_associative() {
1289                    res = to_right_assoc(res);
1290                }
1291
1292                res
1293            }
1294        )(input)
1295    }
1296    
1297    fn nary_operation_parser<'a>(&'a self, input: Span<'a>, id: usize, open: &str, close: &str, prec: usize, checked_precs: &mut FxHashSet<usize>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1298        let mut checked_cpy = checked_precs.clone();
1299        checked_cpy.insert(prec);
1300        checked_cpy.insert(LT_BINOP_PREC);
1301
1302        let (input, a) = self.ryna_expr_parser_wrapper(input, &mut checked_cpy, cache)?;
1303
1304        map(
1305            many1(
1306                terminated(
1307                    self.located(
1308                        tuple((
1309                            empty0,
1310                            opt(
1311                                map(
1312                                    tuple((
1313                                        tag("<"),
1314                                        empty0,
1315                                        separated_list1(
1316                                            tuple((empty0, tag(","), empty0)), 
1317                                            |input| self.type_parser(input)
1318                                        ),
1319                                        empty0,
1320                                        tag(">"),
1321                                        empty0,
1322                                    )),
1323                                    |(_, _, t, _, _, _)| t
1324                                )
1325                            ),
1326                            tag(open),
1327                            empty0,
1328                            separated_list0(
1329                                tuple((empty0, tag(","), empty0)),
1330                                |input| self.ryna_expr_parser_wrapper(input, &mut FxHashSet::default(), cache)
1331                            ),
1332                            empty0,
1333                            opt(tuple((tag(","), empty0))),
1334                            tag(close)
1335                        ))
1336                    ),
1337                    empty0
1338                )
1339            ),
1340            move |v| {
1341                let mut res = a.clone();
1342
1343                for (l, (_, t, _, _, b, _, _, _)) in v {
1344                    res = RynaExpr::NaryOperation(l, id, t.unwrap_or_default(), Box::new(res), b);
1345                }
1346
1347                res
1348            }
1349        )(input)
1350    }
1351
1352    fn operation_parser<'a>(&'a self, input: Span<'a>, checked_precs: &mut FxHashSet<usize>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1353        for o in self.sorted_ops.iter().rev() {
1354            // Skip already checked precedences
1355            if checked_precs.contains(&o.get_precedence()) {
1356                continue;
1357            }
1358
1359            if let Some(res) = cache.borrow().get(input.len(), o.get_precedence()) {
1360                return res.clone();
1361            } 
1362
1363            let mut checked_precs_cpy = checked_precs.clone();
1364
1365            let res = match o {
1366                Operator::Unary { id, representation, prefix, precedence, .. } => {
1367                    if *prefix {
1368                        self.prefix_operation_parser(input, *id, representation, &mut checked_precs_cpy, cache)
1369                    
1370                    } else {
1371                        self.postfix_operation_parser(input, *id,representation, *precedence, &mut checked_precs_cpy, cache)
1372                    }
1373                },
1374
1375                Operator::Binary { id, representation, precedence, .. } => {
1376                    self.binary_operation_parser(input, *id, representation, *precedence, &mut checked_precs_cpy, cache)
1377                },
1378
1379                Operator::Nary { id, open_rep, close_rep, precedence, .. } => {
1380                    self.nary_operation_parser(input, *id, open_rep, close_rep, *precedence, &mut checked_precs_cpy, cache)
1381                }
1382            };
1383
1384            if res.is_ok() {
1385                cache.borrow_mut().set(input.len(), o.get_precedence(), res.clone());
1386                return res;
1387            }
1388        }
1389
1390        cache.borrow_mut().set(input.len(), 0, Err(verbose_error(input, "Unable to parse")));
1391
1392        return Err(verbose_error(input, "Unable to parse"));
1393    }
1394    
1395    fn variable_definition_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1396        return map(
1397            self.located(
1398                tuple((
1399                    tag("let"),
1400                    empty0,
1401                    identifier_parser,
1402                    empty0,
1403                    opt(
1404                        tuple((
1405                            tag(":"),
1406                            empty0,
1407                            context("Invalid type on variable definition", cut(|input| self.type_parser(input))),
1408                            empty0
1409                        ))
1410                    ),
1411                    tag("="),
1412                    empty0,
1413                    context("Invalid right handside on variable definition", cut(|input| self.ryna_expr_parser(input, cache))),
1414                    empty0,
1415                    context("Expected ';' at the end of variable definition", cut(tag(";")))
1416                ))
1417            ),
1418            |(l, (_, _, n, _, t, _, _, e, _, _))| RynaExpr::VariableDefinition(l, n, t.unwrap_or(("".into(), (), Type::InferenceMarker, ())).2, Box::new(e))
1419        )(input);
1420    }
1421    
1422    fn variable_assignment_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1423        return map(
1424            self.located(
1425                tuple((
1426                    identifier_parser,
1427                    empty0,
1428                    tag("="),
1429                    empty0,
1430                    context("Invalid right handside on variable assignment", cut(|input| self.ryna_expr_parser(input, cache))),
1431                    empty0,
1432                    context("Expected ';' at the end of variable assignment", cut(tag(";")))
1433                ))
1434            ),
1435            |(l, (n, _, _, _, e, _, _))| RynaExpr::VariableAssignment(l, n, Box::new(e))
1436        )(input);
1437    }
1438    
1439    fn return_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1440        return map(
1441            self.located(
1442                tuple((
1443                    tag("return"),
1444                    empty0,
1445                    opt(
1446                        terminated(
1447                            |input| self.ryna_expr_parser(input, cache),
1448                            empty0
1449                        )
1450                    ),
1451                    context("Expected ';' at the end of return statement", cut(tag(";")))
1452                ))
1453            ),
1454            |(l, (_, _, e, _))| RynaExpr::Return(l.clone(), Box::new(e.unwrap_or_else(|| RynaExpr::Literal(l, Object::empty()))))
1455        )(input);
1456    }
1457
1458    fn macro_header_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, (RynaMacroType, String, Pattern)> {
1459        map(
1460            tuple((
1461                tag("syntax"),
1462                empty1,
1463                opt(alt((
1464                    map(terminated(tag("fn"), empty1), |_| RynaMacroType::Function),
1465                    map(terminated(tag("expr"), empty1), |_| RynaMacroType::Expression),
1466                    map(terminated(tag("block"), empty1), |_| RynaMacroType::Block),
1467                    map(terminated(tag("rdl"), empty1), |_| RynaMacroType::Rdl),
1468                ))),
1469                context("Expected identifier after 'syntax' in syntax definition", cut(identifier_parser)),
1470                empty1,
1471                context("Expected 'from' after identifier in syntax definition", cut(tag("from"))),
1472                empty1,
1473                cut(|input| parse_rdl_pattern(input, true, true, self)),
1474                empty0
1475            )),
1476            |(_, _, t, n, _, _, _, p, _)| (t.unwrap_or(RynaMacroType::Function), n, p)
1477        )(input)
1478    }
1479
1480    fn if_header_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1481        return map(
1482            tuple((
1483                tag("if"),
1484                empty1,
1485                context("Invalid if condition", cut(|input| self.ryna_expr_parser(input, cache)))
1486            )),
1487            |(_, _, e)| e
1488        )(input);
1489    }
1490    
1491    fn while_header_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1492        return map(
1493            tuple((
1494                tag("while"),
1495                empty1,
1496                context("Invalid while condition", cut(|input| self.ryna_expr_parser(input, cache)))
1497            )),
1498            |(_, _, e)| e
1499        )(input);
1500    }
1501    
1502    fn else_if_header_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1503        return map(
1504            tuple((
1505                tag("else"),
1506                empty1,
1507                tag("if"),
1508                empty1,
1509                context("Invalid else if condition", cut(|input| self.ryna_expr_parser(input, cache)))
1510            )),
1511            |(_, _, _, _, e)| e
1512        )(input);
1513    }
1514    
1515    fn macro_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1516        return map(
1517            self.located(
1518                tuple((
1519                    terminated(
1520                        separated_list0(
1521                            empty0, 
1522                            parse_annotation
1523                        ),
1524                        empty0
1525                    ),
1526                    |input| self.macro_header_parser(input),
1527                    empty0,
1528                    cut(|input| self.macro_body_parser(input)),
1529                ))
1530            ),
1531            |(l, (an, (t, n, p), _, m))| RynaExpr::Macro(l, an, n, t, p, m)
1532        )(input);
1533    }
1534    
1535    fn if_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1536        return map(
1537            self.located(
1538                tuple((
1539                    |input| self.if_header_parser(input, cache),
1540                    empty0,
1541                    cut(|input| self.code_block_parser(input, cache)),
1542                    separated_list0(
1543                        empty0,
1544                        map(
1545                            tuple((
1546                                empty0,
1547                                |input| self.else_if_header_parser(input, cache),
1548                                empty0,
1549                                cut(|input| self.code_block_parser(input, cache))
1550                            )),
1551                            |(_, eih, _, eib)| (eih, eib)
1552                        )
1553                    ),
1554                    opt(
1555                        map(
1556                            tuple((
1557                                empty0,
1558                                tag("else"),
1559                                empty0,
1560                                cut(|input| self.code_block_parser(input, cache))
1561                            )),
1562                            |(_, _, _, e)| e   
1563                        )
1564                    )
1565                ))
1566            ),
1567            |(l, (ih, _, ib, ei, e))| RynaExpr::If(l, Box::new(ih), ib, ei, e)
1568        )(input);
1569    }
1570
1571    fn break_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1572        return map(
1573            self.located(delimited(
1574                empty0, 
1575                tag("break"), 
1576                tuple((
1577                    empty0,
1578                    context("Expected ';' at the end of break statement", cut(tag(";")))
1579                ))
1580            )),
1581            |(l, _)| RynaExpr::Break(l)
1582        )(input);
1583    }
1584
1585    fn continue_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1586        return map(
1587            self.located(delimited(
1588                empty0, 
1589                tag("continue"), 
1590                tuple((
1591                    empty0,
1592                    context("Expected ';' at the end of continue statement", cut(tag(";")))
1593                ))
1594            )),
1595            |(l, _)| RynaExpr::Continue(l)
1596        )(input);
1597    }
1598    
1599    fn for_header_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, (String, RynaExpr)> {
1600        return map(
1601            tuple((
1602                tag("for"),
1603                empty1,
1604                context("Invalid for iterator identifier", cut(identifier_parser)),
1605                empty1,
1606                context("Expected 'in' after for iterator identifier", cut(tag("in"))),
1607                empty1,
1608                cut(|input| self.ryna_expr_parser(input, cache))
1609            )),
1610            |(_, _, n, _, _, _, e)| (n, e)
1611        )(input);
1612    }
1613    
1614    fn while_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1615        return map(
1616            self.located(
1617                tuple((
1618                    |input| self.while_header_parser(input, cache),
1619                    empty0,
1620                    cut(|input| self.code_block_parser(input, cache)),
1621                ))
1622            ),
1623            |(l, (c, _, b))| RynaExpr::While(l, Box::new(c), b)
1624        )(input);
1625    }
1626    
1627    fn for_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1628        return map(
1629            self.located(
1630                tuple((
1631                    |input| self.for_header_parser(input, cache),
1632                    empty0,
1633                    cut(|input| self.code_block_parser(input, cache)),
1634                ))
1635            ),
1636            |(l, ((n, c), _, b))| RynaExpr::For(l, n, Box::new(c), b)
1637        )(input);
1638    }
1639
1640    fn function_header_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, FunctionHeader> {
1641        return map(
1642            tuple((
1643                tag("fn"),
1644                opt(
1645                    map(
1646                        tuple((
1647                            empty0,
1648                            tag("<"),
1649                            empty0,
1650                            separated_list1(
1651                                tuple((empty0, tag(","), empty0)), 
1652                                identifier_parser
1653                            ),
1654                            empty0,
1655                            tag(">"),
1656                        )),
1657                        |(_, _, _, t, _, _)| t
1658                    )
1659                ),
1660                empty1,
1661                context("Invalid function name", cut(identifier_parser)),
1662                empty0,
1663                context("Expected '(' after function name in function definition", cut(tag("("))),
1664                empty0,
1665                separated_list0(
1666                    tuple((empty0, tag(","), empty0)), 
1667                    tuple((
1668                        identifier_parser,
1669                        map(
1670                            opt(
1671                                map(
1672                                    tuple((
1673                                        empty0,
1674                                        tag(":"),
1675                                        empty0,
1676                                        cut(|input| self.type_parser(input)),
1677                                        empty0
1678                                    )),
1679                                    |(_, _, _, t, _)| t
1680                                )
1681                            ),
1682                            |t| t.unwrap_or(Type::Wildcard)
1683                        )
1684                    ))
1685                ),
1686                empty0,
1687                opt(tuple((tag(","), empty0))),
1688                context("Expected ')' after parameters in function definition", cut(tag(")"))),
1689                opt(
1690                    preceded(
1691                        tuple((empty0, tag("->"), empty0)),
1692                        context("Expected return type after '->' in function definition", cut(|input| self.type_parser(input)))
1693                    )
1694                )
1695            )),
1696            |(_, t, _, n, _, _, _, a, _, _, _, r)| (n, t, a, r.unwrap_or(Type::Empty))
1697        )(input);
1698    }
1699
1700    fn function_definition_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
1701        return map(
1702            self.located(
1703                tuple((
1704                    terminated(
1705                        separated_list0(
1706                            empty0, 
1707                            parse_annotation
1708                        ),
1709                        empty0
1710                    ),
1711                    |input| self.function_header_parser(input),
1712                    empty0,
1713                    cut(|input| self.code_block_parser(input, cache)),
1714                ))
1715            ),
1716            |(l, (an, (n, t, mut a, mut r), _, mut b))| {
1717                RynaContext::check_forbidden_fn_names(&n);
1718
1719                let u_t = t.unwrap_or_default();
1720
1721                a.iter_mut().for_each(|(_, i)| i.compile_templates(&u_t));
1722                r.compile_templates(&u_t);
1723                b.iter_mut().for_each(|e| e.compile_types(&u_t));
1724
1725                RynaExpr::FunctionDefinition(l, an, self.get_function_id(n).unwrap(), u_t, a, r, b)
1726            }
1727        )(input);
1728    }
1729
1730    fn prefix_operator_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1731        return map(
1732            self.located(
1733                tuple((
1734                    tag("unary"),
1735                    empty1,
1736                    tag("prefix"),
1737                    empty1,
1738                    context("Expected 'op' after operator type in unary operator definition", cut(tag("op"))),
1739                    empty1,
1740                    context("Expected operator representation after 'op' in unary operator definition", cut(string_parser)),
1741                    empty0,
1742                    map(
1743                        context(
1744                            "Expected precedence after operator representation in operator definition", 
1745                            cut(delimited(
1746                                tuple((tag("("), empty0)),
1747                                take_while1(|c: char| c.is_ascii_digit()),
1748                                tuple((empty0, tag(")")))
1749                            ))
1750                        ),
1751                        |s: Span<'a>| s.parse::<usize>().unwrap()
1752                    ),
1753                    empty0,
1754                    context("Expected ';' at the end of operator definition", cut(tag(";")))
1755                ))
1756            ),
1757            |(l, (_, _, _, _, _, _, n, _, p, _, _))| RynaExpr::PrefixOperatorDefinition(l, n, p)
1758        )(input);
1759    }
1760
1761    fn postfix_operator_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1762        return map(
1763            self.located(
1764                tuple((
1765                    tag("unary"),
1766                    empty1,
1767                    tag("postfix"),
1768                    empty1,
1769                    context("Expected 'op' after operator type in unary operator definition", cut(tag("op"))),
1770                    empty1,
1771                    context("Expected operator representation after 'op' in unary operator definition", cut(string_parser)),
1772                    empty0,
1773                    map(
1774                        context(
1775                            "Expected precedence after operator representation in operator definition",
1776                            cut(delimited(
1777                                tuple((tag("("), empty0)),
1778                                take_while1(|c: char| c.is_ascii_digit()),
1779                                tuple((empty0, tag(")")))
1780                            ))
1781                        ),
1782                        |s: Span<'a>| s.parse::<usize>().unwrap()
1783                    ),
1784                    empty0,
1785                    context("Expected ';' at the end of operator definition", cut(tag(";")))
1786                ))
1787            ),
1788            |(l, (_, _, _, _, _, _, n, _, p, _, _))| RynaExpr::PostfixOperatorDefinition(l, n, p)
1789        )(input);
1790    }
1791
1792    fn binary_operator_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1793        return map(
1794            self.located(
1795                tuple((
1796                    tag("binary"),
1797                    opt(
1798                        tuple((
1799                            empty1,
1800                            tag("right")
1801                        ))
1802                    ),
1803                    empty1,
1804                    context("Expected 'op' after operator type in binary operator definition", cut(tag("op"))),
1805                    empty1,
1806                    context("Expected operator representation after 'op' in binary operator definition", cut(string_parser)),
1807                    empty0,
1808                    map(
1809                        context(
1810                            "Expected precedence after operator representation in operator definition",
1811                            cut(delimited(
1812                                tuple((tag("("), empty0)),
1813                                take_while1(|c: char| c.is_ascii_digit()),
1814                                tuple((empty0, tag(")")))
1815                            ))
1816                        ),
1817                        |s: Span<'a>| s.parse::<usize>().unwrap()
1818                    ),
1819                    empty0,
1820                    context("Expected ';' at the end of operator definition", cut(tag(";")))
1821                ))
1822            ),
1823            |(l, (_, f, _, _, _, n, _, p, _, _))| RynaExpr::BinaryOperatorDefinition(l, n, f.is_some(), p)
1824        )(input);
1825    }
1826
1827    fn nary_operator_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1828        return map(
1829            self.located(
1830                tuple((
1831                    tag("nary"),
1832                    empty1,
1833                    context("Expected 'op' after operator type in n-ary operator definition", cut(tag("op"))),
1834                    empty1,
1835                    context("Expected 'from' after 'op' in n-ary operator definition", cut(tag("from"))),
1836                    empty1,
1837                    context("Expected operator opening after 'from' in n-ary operator definition", cut(string_parser)),
1838                    empty1,
1839                    context("Expected 'to' after operator opening in n-ary operator definition", cut(tag("to"))),
1840                    empty1,
1841                    context("Expected operator closing after 'to' in n-ary operator definition", cut(string_parser)),
1842                    empty0,
1843                    map(
1844                        context(
1845                            "Expected precedence after operator representation in operator definition",
1846                            cut(delimited(
1847                                tuple((tag("("), empty0)),
1848                                take_while1(|c: char| c.is_ascii_digit()),
1849                                tuple((empty0, tag(")")))
1850                            ))
1851                        ),
1852                        |s: Span<'a>| s.parse::<usize>().unwrap()
1853                    ),
1854                    empty0,
1855                    context("Expected ';' at the end of operator definition", cut(tag(";")))
1856                ))
1857            ),
1858            |(l, (_, _, _, _, _, _, f, _, _, _, t, _, p, _, _))| RynaExpr::NaryOperatorDefinition(l, f, t, p)
1859        )(input);
1860    }
1861
1862    fn operator_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
1863        return alt((
1864            |input| self.prefix_operator_definition_parser(input),
1865            |input| self.postfix_operator_definition_parser(input),
1866            |input| self.binary_operator_definition_parser(input),
1867            |input| self.nary_operator_definition_parser(input)
1868        ))(input)
1869    }
1870
1871    fn prefix_operator_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, usize> {
1872        let mut sorted_ops = self.unary_ops.clone();
1873        sorted_ops.sort_by_key(|op| -(op.get_repr().len() as i64));
1874
1875        for o in &sorted_ops {
1876            if let Operator::Unary{id, representation, prefix, ..} = o {
1877                if *prefix {
1878                    let res = map(tag(representation.as_str()), |_| *id)(input);
1879
1880                    if res.is_ok() {
1881                        return res;
1882                    }
1883                }
1884            }
1885        }
1886
1887        return Err(verbose_error(input, "Unable to parse"));
1888    }
1889
1890    fn postfix_operator_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, usize> {
1891        let mut sorted_ops = self.unary_ops.clone();
1892        sorted_ops.sort_by_key(|op| -(op.get_repr().len() as i64));
1893
1894        for o in &sorted_ops {
1895            if let Operator::Unary{id, representation, prefix, ..} = o {
1896                if !*prefix {
1897                    let res = map(tag(representation.as_str()), |_| *id)(input);
1898
1899                    if res.is_ok() {
1900                        return res;
1901                    }
1902                }
1903            }
1904        }
1905
1906        return Err(verbose_error(input, "Unable to parse"));
1907    }
1908
1909    fn binary_operator_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, usize> {
1910        let mut sorted_ops = self.binary_ops.clone();
1911        sorted_ops.sort_by_key(|op| -(op.get_repr().len() as i64));
1912
1913        for o in &sorted_ops {
1914            if let Operator::Binary{id, representation, ..} = o {
1915                let res = map(tag(representation.as_str()), |_| *id)(input);
1916
1917                if res.is_ok() {
1918                    return res;
1919                }
1920            }
1921        }
1922
1923        return Err(verbose_error(input, "Unable to parse"));
1924    }
1925
1926    fn nary_operator_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, (usize, Vec<(String, Type)>)> {
1927        let mut sorted_ops = self.nary_ops.clone();
1928        sorted_ops.sort_by_key(|op| {
1929            if let Operator::Nary { open_rep, .. } = op {
1930                return -(open_rep.len() as i64);
1931            }
1932
1933            unreachable!()
1934        });
1935
1936        for o in &sorted_ops {
1937            if let Operator::Nary{id, open_rep, close_rep, ..} = o {
1938                let res = map(
1939                    tuple((
1940                        tag(open_rep.as_str()),
1941                        empty0,
1942                        separated_list0(
1943                            tuple((empty0, tag(","), empty0)), 
1944                            tuple((
1945                                identifier_parser,
1946                                map(
1947                                    opt(
1948                                        map(
1949                                            tuple((
1950                                                empty0,
1951                                                tag(":"),
1952                                                empty0,
1953                                                cut(|input| self.type_parser(input)),
1954                                                empty0
1955                                            )),
1956                                            |(_, _, _, t, _)| t
1957                                        )
1958                                    ),
1959                                    |t| t.unwrap_or(Type::Wildcard)
1960                                )
1961                            ))
1962                        ),
1963                        empty0,
1964                        tag(close_rep.as_str())
1965                    )),
1966                    |(_, _, a, _, _)| (*id, a)
1967                )(input);
1968
1969                if res.is_ok() {
1970                    return res;
1971                }
1972            }
1973        }
1974
1975        return Err(verbose_error(input, "Unable to parse"));
1976    }
1977
1978    fn prefix_operation_header_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, UnaryOpHeader> {
1979        return map(
1980            tuple((
1981                tag("op"),
1982                opt(
1983                    map(
1984                        tuple((
1985                            empty0,
1986                            tag("<"),
1987                            empty0,
1988                            separated_list1(
1989                                tuple((empty0, tag(","), empty0)), 
1990                                identifier_parser
1991                            ),
1992                            empty0,
1993                            tag(">")
1994                        )),
1995                        |(_, _, _, t, _, _)| t
1996                    )
1997                ),
1998                empty1,
1999                |input| self.prefix_operator_parser(input),
2000                empty0,
2001                delimited(
2002                    context("Expected '(' in operation definition", cut(tuple((tag("("), empty0)))),
2003                    tuple((
2004                        identifier_parser,
2005                        map(
2006                            opt(
2007                                map(
2008                                    tuple((
2009                                        empty0,
2010                                        tag(":"),
2011                                        empty0,
2012                                        cut(|input| self.type_parser(input)),
2013                                        empty0
2014                                    )),
2015                                    |(_, _, _, t, _)| t
2016                                )
2017                            ),
2018                            |t| t.unwrap_or(Type::Wildcard)
2019                        )
2020                    )),
2021                    context("Expected ')' in operation definition", cut(tuple((empty0, tag(")")))))
2022                ),
2023                opt(
2024                    preceded(
2025                        tuple((empty0, tag("->"), empty0)),
2026                        context("Expected return type after '->' in operation definition", cut(|input| self.type_parser(input)))
2027                    )
2028                )
2029            )),
2030            |(_, tm, _, id, _, (n, t), r)| (id, tm.unwrap_or_default(), n, t, r.unwrap_or(Type::Empty))
2031        )(input);
2032    }
2033
2034    fn postfix_operation_header_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, UnaryOpHeader> {
2035        return map(
2036            tuple((
2037                tag("op"),
2038                opt(
2039                    map(
2040                        tuple((
2041                            empty0,
2042                            tag("<"),
2043                            empty0,
2044                            separated_list1(
2045                                tuple((empty0, tag(","), empty0)), 
2046                                identifier_parser
2047                            ),
2048                            empty0,
2049                            tag(">"),
2050                        )),
2051                        |(_, _, _, t, _, _)| t
2052                    )
2053                ),
2054                empty1,
2055                delimited(
2056                    context("Expected '(' in operation definition", cut(tuple((tag("("), empty0)))),
2057                    tuple((
2058                        identifier_parser,
2059                        map(
2060                            opt(
2061                                map(
2062                                    tuple((
2063                                        empty0,
2064                                        tag(":"),
2065                                        empty0,
2066                                        cut(|input| self.type_parser(input)),
2067                                        empty0
2068                                    )),
2069                                    |(_, _, _, t, _)| t
2070                                )
2071                            ),
2072                            |t| t.unwrap_or(Type::Wildcard)
2073                        )
2074                    )),
2075                    context("Expected '(' in operation definition", cut(tuple((empty0, tag(")")))))
2076                ),
2077                empty0,
2078                |input| self.postfix_operator_parser(input),
2079                opt(
2080                    preceded(
2081                        tuple((empty0, tag("->"), empty0)),
2082                        context("Expected return type after '->' in operation definition", cut(|input| self.type_parser(input)))
2083                    )
2084                )
2085            )),
2086            |(_, tm, _, (n, t), _, id, r)| (id, tm.unwrap_or_default(), n, t, r.unwrap_or(Type::Empty))
2087        )(input);
2088    }
2089
2090    fn binary_operation_header_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, BinaryOpHeader> {
2091        return map(
2092            tuple((
2093                tag("op"),
2094                opt(
2095                    map(
2096                        tuple((
2097                            empty0,
2098                            tag("<"),
2099                            empty0,
2100                            separated_list1(
2101                                tuple((empty0, tag(","), empty0)), 
2102                                identifier_parser
2103                            ),
2104                            empty0,
2105                            tag(">"),
2106                        )),
2107                        |(_, _, _, t, _, _)| t
2108                    )
2109                ),
2110                empty1,
2111                delimited(
2112                    context("Expected '(' in operation definition", cut(tuple((tag("("), empty0)))),
2113                    tuple((
2114                        identifier_parser,
2115                        map(
2116                            opt(
2117                                map(
2118                                    tuple((
2119                                        empty0,
2120                                        tag(":"),
2121                                        empty0,
2122                                        cut(|input| self.type_parser(input)),
2123                                        empty0
2124                                    )),
2125                                    |(_, _, _, t, _)| t
2126                                )
2127                            ),
2128                            |t| t.unwrap_or(Type::Wildcard)
2129                        )
2130                    )),
2131                    context("Expected ')' in operation definition", cut(tuple((empty0, tag(")")))))
2132                ),
2133                empty0,
2134                |input| self.binary_operator_parser(input),
2135                empty0,
2136                delimited(
2137                    context("Expected '(' in operation definition", cut(tuple((tag("("), empty0)))),
2138                    tuple((
2139                        identifier_parser,
2140                        map(
2141                            opt(
2142                                map(
2143                                    tuple((
2144                                        empty0,
2145                                        tag(":"),
2146                                        empty0,
2147                                        cut(|input| self.type_parser(input)),
2148                                        empty0
2149                                    )),
2150                                    |(_, _, _, t, _)| t
2151                                )
2152                            ),
2153                            |t| t.unwrap_or(Type::Wildcard)
2154                        )
2155                    )),
2156                    context("Expected ')' in operation definition", cut(tuple((empty0, tag(")")))))
2157                ),
2158                opt(
2159                    preceded(
2160                        tuple((empty0, tag("->"), empty0)),
2161                        context("Expected return type after '->' in operation definition", cut(|input| self.type_parser(input)))
2162                    )
2163                )
2164            )),
2165            |(_, tm, _, a, _, id, _, b, r)| (id, tm.unwrap_or_default(), a, b, r.unwrap_or(Type::Empty))
2166        )(input);
2167    }
2168
2169    fn nary_operation_header_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, NaryOpHeader> {
2170        return map(
2171            tuple((
2172                tag("op"),
2173                opt(
2174                    map(
2175                        tuple((
2176                            empty0,
2177                            tag("<"),
2178                            empty0,
2179                            separated_list1(
2180                                tuple((empty0, tag(","), empty0)), 
2181                                identifier_parser
2182                            ),
2183                            empty0,
2184                            tag(">"),
2185                        )),
2186                        |(_, _, _, t, _, _)| t
2187                    )
2188                ),
2189                empty1,
2190                delimited(
2191                    context("Expected '(' in operation definition", cut(tuple((tag("("), empty0)))),
2192                    tuple((
2193                        identifier_parser,
2194                        map(
2195                            opt(
2196                                map(
2197                                    tuple((
2198                                        empty0,
2199                                        tag(":"),
2200                                        empty0,
2201                                        cut(|input| self.type_parser(input)),
2202                                        empty0
2203                                    )),
2204                                    |(_, _, _, t, _)| t
2205                                )
2206                            ),
2207                            |t| t.unwrap_or(Type::Wildcard)
2208                        )
2209                    )),
2210                    context("Expected ')' in operation definition", cut(tuple((empty0, opt(tuple((tag(","), empty0))), tag(")")))))
2211                ),
2212                empty0,
2213                |input| self.nary_operator_parser(input),
2214                opt(
2215                    preceded(
2216                        tuple((empty0, tag("->"), empty0)),
2217                        context("Expected return type after '->' in operation definition", cut(|input| self.type_parser(input)))
2218                    )
2219                )
2220            )),
2221            |(_, tm, _, a, _, (id, b), r)| (id, tm.unwrap_or_default(), a, b, r.unwrap_or(Type::Empty))
2222        )(input);
2223    }
2224
2225    fn prefix_operation_definition_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2226        return map(
2227            self.located(
2228                tuple((
2229                    terminated(
2230                        separated_list0(
2231                            empty0, 
2232                            parse_annotation
2233                        ),
2234                        empty0
2235                    ),
2236                    |input| self.prefix_operation_header_definition_parser(input),
2237                    empty0,
2238                    cut(|input| self.code_block_parser(input, cache)),
2239                ))
2240            ),
2241            |(l, (an, (id, tm, n, mut t, mut r), _, mut b))| {
2242                t.compile_templates(&tm);
2243                r.compile_templates(&tm);
2244                b.iter_mut().for_each(|e| e.compile_types(&tm));
2245
2246                RynaExpr::PrefixOperationDefinition(l, an, id, tm, n, t, r, b)
2247            }
2248        )(input);
2249    }
2250
2251    fn postfix_operation_definition_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2252        return map(
2253            self.located(
2254                tuple((
2255                    terminated(
2256                        separated_list0(
2257                            empty0, 
2258                            parse_annotation
2259                        ),
2260                        empty0
2261                    ),
2262                    |input| self.postfix_operation_header_definition_parser(input),
2263                    empty0,
2264                    cut(|input| self.code_block_parser(input, cache)),
2265                ))
2266            ),
2267            |(l, (an, (id, tm, n, mut t, mut r), _, mut b))| {
2268                t.compile_templates(&tm);
2269                r.compile_templates(&tm);
2270                b.iter_mut().for_each(|e| e.compile_types(&tm));
2271
2272                RynaExpr::PostfixOperationDefinition(l, an, id, tm, n, t, r, b)
2273            }
2274        )(input);
2275    }
2276
2277    fn binary_operation_definition_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2278        return map(
2279            self.located(
2280                tuple((
2281                    terminated(
2282                        separated_list0(
2283                            empty0, 
2284                            parse_annotation
2285                        ),
2286                        empty0
2287                    ),
2288                    |input| self.binary_operation_header_definition_parser(input),
2289                    empty0,
2290                    cut(|input| self.code_block_parser(input, cache)),
2291                ))
2292            ),
2293            |(l, (an, (id, tm, mut a1, mut a2, mut r), _, mut b))| {
2294                a1.1.compile_templates(&tm);
2295                a2.1.compile_templates(&tm);
2296                r.compile_templates(&tm);
2297                b.iter_mut().for_each(|e| e.compile_types(&tm));
2298
2299                RynaExpr::BinaryOperationDefinition(l, an, id, tm, a1, a2, r, b)
2300            }
2301        )(input);
2302    }
2303
2304    fn nary_operation_definition_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2305        return map(
2306            self.located(
2307                tuple((
2308                    terminated(
2309                        separated_list0(
2310                            empty0, 
2311                            parse_annotation
2312                        ),
2313                        empty0
2314                    ),
2315                    |input| self.nary_operation_header_definition_parser(input),
2316                    empty0,
2317                    cut(|input| self.code_block_parser(input, cache)),
2318                ))
2319            ),
2320            |(l, (an, (id, tm, mut a1, mut a2, mut r), _, mut b))| {
2321                a1.1.compile_templates(&tm);
2322                a2.iter_mut().for_each(|(_, i)| i.compile_templates(&tm));
2323                r.compile_templates(&tm);
2324                b.iter_mut().for_each(|e| e.compile_types(&tm));
2325
2326                RynaExpr::NaryOperationDefinition(l, an, id, tm, a1, a2, r, b)
2327            }
2328        )(input);
2329    }
2330
2331    fn operation_definition_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2332        return alt((
2333            |input| self.prefix_operation_definition_parser(input, cache),
2334            |input| self.postfix_operation_definition_parser(input, cache),
2335            |input| self.binary_operation_definition_parser(input, cache),
2336            |input| self.nary_operation_definition_parser(input, cache)
2337        ))(input);
2338    }
2339
2340    fn code_block_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, Vec<RynaExpr>> {
2341        return map(
2342            delimited(
2343                tuple((tag("{"), empty0)),
2344                many_separated0(empty0, |input| self.ryna_line_parser(input, cache)),
2345                tuple((empty0, tag("}")))
2346            ),
2347            |i| i.into_iter().flatten().collect()
2348        )(input);
2349    }
2350
2351    fn macro_body_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RdlMacro> {
2352        delimited(
2353            tuple((tag("{"), empty0)),
2354            parse_ryna_macro,
2355            tuple((empty0, tag("}")))
2356        )(input)
2357    }
2358
2359    fn inline_class_syntax_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, Pattern> {
2360        return map(
2361            tuple((
2362                tag("syntax"),
2363                empty1,
2364                context("Expected 'from' after 'syntax' in class syntax definition", cut(tag("from"))),
2365                empty1,
2366                cut(|input| parse_rdl_pattern(input, true, true, self)),
2367                empty0,
2368                context("Expected ';' at the end of class syntax definition", cut(tag(";")))
2369            )),
2370            |(_, _, _, _, p, _, _)| p
2371        )(input);
2372    }
2373
2374    fn alias_name_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, String> {
2375        map(
2376            tuple((
2377                tag("type"),
2378                empty1,
2379                context("Invalid type identifier", cut(identifier_parser)),
2380                empty0,
2381                opt(
2382                    map(
2383                        tuple((
2384                            tag("<"),
2385                            empty0,
2386                            separated_list1(
2387                                tuple((empty0, tag(","), empty0)), 
2388                                identifier_parser
2389                            ),
2390                            empty0,
2391                            tag(">"),
2392                            empty0,
2393                        )),
2394                        |(_, _, t, _, _, _)| t
2395                    )
2396                ),
2397                context("Expected '=' after type name", cut(tag("=")))
2398            )),
2399            |(_, _, n, _, _, _)| n
2400        )(input)
2401    }
2402
2403    fn alias_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
2404        return map(
2405            self.located(
2406                tuple((
2407                    tag("type"),
2408                    empty1,
2409                    context("Invalid type identifier", cut(identifier_parser)),
2410                    empty0,
2411                    opt(
2412                        map(
2413                            tuple((
2414                                tag("<"),
2415                                empty0,
2416                                separated_list1(
2417                                    tuple((empty0, tag(","), empty0)), 
2418                                    identifier_parser
2419                                ),
2420                                empty0,
2421                                tag(">"),
2422                                empty0,
2423                            )),
2424                            |(_, _, t, _, _, _)| t
2425                        )
2426                    ),
2427                    context("Expected '=' after type name", cut(tag("="))),
2428                    empty0,
2429                    cut(|input| self.type_parser(input)),
2430                    empty0,
2431                    context("Expected ';' at the end of type alias definition", cut(tag(";")))
2432                ))
2433            ),
2434            |(l, (_, _, n, _, tm, _, _, mut t, _, _))| {
2435                let u_t = tm.unwrap_or_default();
2436
2437                t.compile_templates(&u_t);
2438
2439                RynaExpr::ClassDefinition(l, vec!(), n, u_t, vec!(), Some(t), vec!())
2440            }
2441        )(input);
2442    }
2443
2444    fn class_name_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, String> {
2445        map(
2446            tuple((
2447                tag("class"),
2448                empty1,
2449                context("Invalid class identifier", cut(identifier_parser)),
2450                empty0,
2451                opt(
2452                    map(
2453                        tuple((
2454                            tag("<"),
2455                            empty0,
2456                            separated_list1(
2457                                tuple((empty0, tag(","), empty0)), 
2458                                identifier_parser
2459                            ),
2460                            empty0,
2461                            tag(">"),
2462                            empty0,
2463                        )),
2464                        |(_, _, t, _, _, _)| t
2465                    )
2466                ),
2467                tag("{")
2468            )),
2469            |(_, _, n, _, _, _)| n
2470        )(input)
2471    }
2472
2473    fn class_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
2474        return map(
2475            self.located(
2476                tuple((
2477                    terminated(
2478                        separated_list0(
2479                            empty0, 
2480                            parse_annotation
2481                        ),
2482                        empty0
2483                    ),
2484                    tag("class"),
2485                    empty1,
2486                    context("Invalid class identifier", cut(identifier_parser)),
2487                    empty0,
2488                    opt(
2489                        map(
2490                            tuple((
2491                                tag("<"),
2492                                empty0,
2493                                separated_list1(
2494                                    tuple((empty0, tag(","), empty0)), 
2495                                    identifier_parser
2496                                ),
2497                                empty0,
2498                                tag(">"),
2499                                empty0,
2500                            )),
2501                            |(_, _, t, _, _, _)| t
2502                        )
2503                    ),
2504                    tag("{"),
2505                    empty0,
2506                    separated_list0(
2507                        empty0,
2508                        |input| self.inline_class_syntax_parser(input)
2509                    ),
2510                    empty0,
2511                    separated_list0(
2512                        empty0,
2513                        map(
2514                            tuple((
2515                                identifier_parser,
2516                                map(
2517                                    opt(
2518                                        map(
2519                                            tuple((
2520                                                empty0,
2521                                                tag(":"),
2522                                                empty0,
2523                                                cut(|input| self.type_parser(input)),
2524                                                empty0
2525                                            )),
2526                                            |(_, _, _, t, _)| t
2527                                        )
2528                                    ),
2529                                    |t| t.unwrap_or(Type::Wildcard)
2530                                ),
2531                                empty0,
2532                                context("Expected ';' at the end of class attribute definition", cut(tag(";")))
2533                            )),
2534                            |(a, b, _, _)| (a, b)
2535                        )
2536                    ),
2537                    empty0,
2538                    tag("}")
2539                ))
2540            ),
2541            |(l, (an, _, _, n, _, t, _, _, p, _, mut f, _, _))| {
2542                let u_t = t.unwrap_or_default();
2543
2544                f.iter_mut().for_each(|(_, tp)| tp.compile_templates(&u_t));
2545
2546                RynaExpr::ClassDefinition(l, an, n, u_t, f, None, p)
2547            }
2548        )(input);
2549    }
2550
2551    fn interface_definition_name_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, String> {
2552        map(
2553            tuple((
2554                tag("interface"),
2555                empty1,
2556                context("Invalid interface identifier", cut(identifier_parser)),
2557                empty0,
2558                opt(
2559                    map(
2560                        tuple((
2561                            tag("<"),
2562                            empty0,
2563                            separated_list1(
2564                                tuple((empty0, tag(","), empty0)), 
2565                                identifier_parser
2566                            ),
2567                            empty0,
2568                            tag(">"),
2569                            empty0,
2570                        )),
2571                        |(_, _, t, _, _, _)| t
2572                    )
2573                ),
2574                tag("{")
2575            )),
2576            |(_, _, n, _, _, _)| n
2577        )(input)
2578    }
2579
2580    fn interface_definition_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
2581        return map(
2582            self.located(
2583                tuple((
2584                    terminated(
2585                        separated_list0(
2586                            empty0, 
2587                            parse_annotation
2588                        ),
2589                        empty0
2590                    ),
2591                    tag("interface"),
2592                    empty1,
2593                    context("Invalid interface identifier", cut(identifier_parser)),
2594                    empty0,
2595                    opt(
2596                        map(
2597                            tuple((
2598                                tag("<"),
2599                                empty0,
2600                                separated_list1(
2601                                    tuple((empty0, tag(","), empty0)), 
2602                                    identifier_parser
2603                                ),
2604                                empty0,
2605                                tag(">"),
2606                                empty0,
2607                            )),
2608                            |(_, _, t, _, _, _)| t
2609                        )
2610                    ),
2611                    tag("{"),
2612                    empty0,
2613                    separated_list0(
2614                        empty0,
2615                        delimited(
2616                            empty0, 
2617                            alt((
2618                                map(
2619                                    tuple((
2620                                        terminated(
2621                                            separated_list0(
2622                                                empty0, 
2623                                                parse_annotation
2624                                            ),
2625                                            empty0
2626                                        ),
2627                                        |input| self.function_header_parser(input),
2628                                    )),
2629                                    |(an, (a, b, c, d))| InterfaceHeader::FunctionHeader(an, a, b, c, d)
2630                                ),
2631                                map(
2632                                    tuple((
2633                                        terminated(
2634                                            separated_list0(
2635                                                empty0, 
2636                                                parse_annotation
2637                                            ),
2638                                            empty0
2639                                        ),
2640                                        |input| self.prefix_operation_header_definition_parser(input),
2641                                    )),
2642                                    |(an, (a, b, c, d, e))| InterfaceHeader::UnaryOpHeader(an, a, b, c, d, e)
2643                                ),
2644                                map(
2645                                    tuple((
2646                                        terminated(
2647                                            separated_list0(
2648                                                empty0, 
2649                                                parse_annotation
2650                                            ),
2651                                            empty0
2652                                        ),
2653                                        |input| self.postfix_operation_header_definition_parser(input),
2654                                    )),
2655                                    |(an, (a, b, c, d, e))| InterfaceHeader::UnaryOpHeader(an, a, b, c, d, e)
2656                                ),
2657                                map(
2658                                    tuple((
2659                                        terminated(
2660                                            separated_list0(
2661                                                empty0, 
2662                                                parse_annotation
2663                                            ),
2664                                            empty0
2665                                        ),
2666                                        |input| self.binary_operation_header_definition_parser(input),
2667                                    )),
2668                                    |(an, (a, b, c, d, e))| InterfaceHeader::BinaryOpHeader(an, a, b, c, d, e)
2669                                ),
2670                                map(
2671                                    tuple((
2672                                        terminated(
2673                                            separated_list0(
2674                                                empty0, 
2675                                                parse_annotation
2676                                            ),
2677                                            empty0
2678                                        ),
2679                                        |input| self.nary_operation_header_definition_parser(input),
2680                                    )),
2681                                    |(an, (a, b, c, d, e))| InterfaceHeader::NaryOpHeader(an, a, b, c, d, e)
2682                                )
2683                            )),
2684                            context("Expected ';' at the end of interface function signature", cut(tag(";")))
2685                        )
2686                    ),
2687                    empty0,
2688                    tag("}")
2689                ))
2690            ),
2691            |(l, (an, _, _, n, _, t, _, _, p, _, _))| {
2692                let u_t = t.unwrap_or_default();
2693
2694                let mut fns: Vec<AnnotFunctionHeader> = vec!();
2695                let mut unary: Vec<AnnotUnaryOpHeader> = vec!();
2696                let mut binary: Vec<AnnotBinaryOpHeader> = vec!();
2697                let mut nary: Vec<AnnotNaryOpHeader> = vec!();
2698
2699                p.into_iter().for_each(|h| {
2700                    match h {
2701                        InterfaceHeader::FunctionHeader(an, n, tm, mut args, mut ret) => {
2702                            let u_tm = tm.clone().unwrap_or_default();
2703                            let all_tm = u_t.iter().cloned().chain(u_tm).collect::<Vec<_>>();
2704        
2705                            args.iter_mut().for_each(|(_, tp)| {
2706                                tp.compile_templates(&all_tm);
2707                            });
2708        
2709                            ret.compile_templates(&all_tm);
2710
2711                            fns.push((an, n, tm, args, ret));
2712                        },
2713
2714                        InterfaceHeader::UnaryOpHeader(an, id, tm, a, mut at, mut ret) => {
2715                            let u_tm = tm.clone();
2716                            let all_tm = u_t.iter().cloned().chain(u_tm).collect::<Vec<_>>();
2717
2718                            at.compile_templates(&all_tm);
2719                            ret.compile_templates(&all_tm);
2720
2721                            unary.push((an, id, tm, a, at, ret));
2722                        },
2723
2724                        InterfaceHeader::BinaryOpHeader(an, id, tm, (a0, mut a0t), (a1, mut a1t), mut ret) => {
2725                            let u_tm = tm.clone();
2726                            let all_tm = u_t.iter().cloned().chain(u_tm).collect::<Vec<_>>();
2727
2728                            a0t.compile_templates(&all_tm);
2729                            a1t.compile_templates(&all_tm);
2730                            ret.compile_templates(&all_tm);
2731
2732                            binary.push((an, id, tm, (a0, a0t), (a1, a1t), ret));
2733                        }
2734
2735                        InterfaceHeader::NaryOpHeader(an, id, tm, (a0, mut a0t), mut args, mut ret) => {
2736                            let u_tm = tm.clone();
2737                            let all_tm = u_t.iter().cloned().chain(u_tm).collect::<Vec<_>>();
2738
2739                            a0t.compile_templates(&all_tm);
2740
2741                            args.iter_mut().for_each(|(_, tp)| {
2742                                tp.compile_templates(&all_tm);
2743                            });
2744
2745                            ret.compile_templates(&all_tm);
2746
2747                            nary.push((an, id, tm, (a0, a0t), args, ret));
2748                        }
2749                    }
2750                });
2751
2752                RynaExpr::InterfaceDefinition(l, an, n, u_t, fns, unary, binary, nary)
2753            }
2754        )(input);
2755    }
2756
2757    fn interface_implementation_parser<'a>(&'a self, input: Span<'a>) -> PResult<'a, RynaExpr> {
2758        return map(
2759            self.located(
2760                tuple((
2761                    tag("implement"),
2762                    empty0,
2763                    opt(
2764                        map(
2765                            tuple((
2766                                tag("<"),
2767                                empty0,
2768                                separated_list1(
2769                                    tuple((empty0, tag(","), empty0)), 
2770                                    identifier_parser
2771                                ),
2772                                empty0,
2773                                tag(">"),
2774                                empty0,
2775                            )),
2776                            |(_, _, t, _, _, _)| t
2777                        )
2778                    ),
2779                    context("Invalid interface name", cut(identifier_parser)),
2780                    empty0,
2781                    opt(
2782                        map(
2783                            tuple((
2784                                tag("<"),
2785                                empty0,
2786                                separated_list1(
2787                                    tuple((empty0, tag(","), empty0)), 
2788                                    cut(|input|self.type_parser(input))
2789                                ),
2790                                empty0,
2791                                tag(">"),
2792                                empty0,
2793                            )),
2794                            |(_, _, t, _, _, _)| t
2795                        )
2796                    ),
2797                    tag("for"),
2798                    empty1,
2799                    cut(|input|self.type_parser(input)),
2800                    empty0,
2801                    context("Expected ';' at the end of interface implementation", cut(tag(";")))
2802                ))
2803            ),
2804            |(l, (_, _, t, n, _, ts, _, _, mut tf, _, _))| {
2805                let u_tm = t.unwrap_or_default();
2806                let mut u_ts = ts.unwrap_or_default();
2807                tf.compile_templates(&u_tm);
2808                u_ts.iter_mut().for_each(|i| i.compile_templates(&u_tm));
2809
2810                RynaExpr::InterfaceImplementation(l, u_tm, tf, n, u_ts)
2811            }
2812        )(input);
2813    }
2814
2815    fn tuple_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2816        return map(
2817            self.located(
2818                tuple((
2819                    tag("("),
2820                    empty0,
2821                    separated_list0(
2822                        tuple((empty0, tag(","), empty0)),
2823                        |input| self.ryna_expr_parser(input, cache)
2824                    ),
2825                    empty0,
2826                    opt(tuple((tag(","), empty0))),
2827                    tag(")")
2828                ))
2829            ),
2830            |(l, (_, _, e, _, _, _))| {
2831                if e.is_empty() {
2832                    RynaExpr::Literal(l, Object::empty())
2833
2834                } else {
2835                    RynaExpr::Tuple(l, e)
2836                }
2837            }
2838        )(input);
2839    }
2840
2841    fn do_block_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2842        map(
2843            self.located(preceded(
2844                terminated(tag("do"), empty0),
2845                |input| self.code_block_parser(input, cache)
2846            )),
2847            |(l, c)| RynaExpr::DoBlock(l, c, Type::InferenceMarker)
2848        )(input)
2849    }
2850
2851    fn lambda_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2852        return map(
2853            self.located(
2854                tuple((
2855                    opt(delimited(
2856                        tuple((tag("["), empty0)),
2857                        separated_list1(
2858                            tuple((empty0, tag(","), empty0)),
2859                            identifier_parser
2860                        ),
2861                        tuple((empty0, tag("]"), empty0))
2862                    )),
2863                    tag("("),
2864                    empty0,
2865                    separated_list0(
2866                        tuple((empty0, tag(","), empty0)), 
2867                        tuple((
2868                            identifier_parser,
2869                            map(
2870                                opt(
2871                                    map(
2872                                        tuple((
2873                                            empty0,
2874                                            tag(":"),
2875                                            empty0,
2876                                            cut(|input| self.type_parser(input)),
2877                                            empty0
2878                                        )),
2879                                        |(_, _, _, t, _)| t
2880                                    )
2881                                ),
2882                                |t| t.unwrap_or(Type::Wildcard)
2883                            )
2884                        ))
2885                    ),
2886                    empty0,
2887                    opt(tuple((tag(","), empty0))),
2888                    tag(")"),
2889                    empty0,
2890                    opt(
2891                        map(
2892                            tuple((
2893                                tag("->"),
2894                                empty0,
2895                                cut(|input| self.type_parser(input)),
2896                                empty0,
2897                            )),
2898                            |(_, _, t, _)| t
2899                        ),
2900                    ),
2901                    alt((
2902                        |input| self.code_block_parser(input, cache),
2903                        map(
2904                            self.located(|input| self.ryna_expr_parser(input, cache)),
2905                            |(l, e)| vec!(RynaExpr::Return(l, Box::new(e))) // Implicit return
2906                        )
2907                    ))
2908                ))   
2909            ),
2910            |(l, (c, _, _, a, _, _, _, _, r, b))| RynaExpr::Lambda(l, c.unwrap_or_default(), a, r.unwrap_or(Type::InferenceMarker), b)
2911        )(input);
2912    }
2913
2914    fn ryna_expr_parser_wrapper<'a>(&'a self, input: Span<'a>, checked_precs: &mut FxHashSet<usize>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2915        return alt((
2916            |input| self.operation_parser(input, checked_precs, cache),
2917            |input| self.custom_syntax_parser(input, cache),
2918            |input| self.do_block_parser(input, cache),
2919            |input| self.lambda_parser(input, cache),
2920            |input| self.tuple_parser(input, cache),
2921            |input| self.literal_parser(input, cache),
2922            |input| self.variable_parser(input)
2923        ))(input);
2924    }
2925
2926    pub fn ryna_expr_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, RynaExpr> {
2927        return self.ryna_expr_parser_wrapper(input, &mut FxHashSet::default(), cache);
2928    }
2929
2930    fn ryna_line_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, Vec<RynaExpr>> {
2931        return alt((
2932            |input| self.custom_syntax_block_parser(input, cache),
2933            map(
2934                alt((
2935                    |input| self.variable_definition_parser(input, cache),
2936                    |input| self.variable_assignment_parser(input, cache),
2937                    |input| self.return_parser(input, cache),
2938                    |input| self.while_parser(input, cache),
2939                    |input| self.for_parser(input, cache),
2940                    |input| self.if_parser(input, cache),
2941                    |input| self.break_parser(input),
2942                    |input| self.continue_parser(input),
2943                    |input| terminated(|input| self.ryna_expr_parser(input, cache), cut(tuple((empty0, tag(";")))))(input)
2944                )),
2945                |i| vec!(i)
2946            )
2947        ))(input);
2948    }
2949
2950    fn ryna_global_parser<'a>(&'a self, input: Span<'a>, cache: &PCache<'a>) -> PResult<'a, Vec<RynaExpr>> {
2951        return alt((
2952            |input| self.custom_syntax_block_parser(input, cache),
2953            map(
2954                alt((
2955                    |input| self.variable_definition_parser(input, cache),
2956                    |input| self.variable_assignment_parser(input, cache),
2957                    |input| self.return_parser(input, cache),
2958                    |input| self.while_parser(input, cache),
2959                    |input| self.for_parser(input, cache),
2960                    |input| self.if_parser(input, cache),
2961                    |input| self.function_definition_parser(input, cache),
2962                    |input| self.operator_definition_parser(input),
2963                    |input| self.operation_definition_parser(input, cache),
2964                    |input| self.class_definition_parser(input),
2965                    |input| self.alias_definition_parser(input),
2966                    |input| self.interface_definition_parser(input),
2967                    |input| self.interface_implementation_parser(input),
2968                    |input| self.macro_parser(input), 
2969                    |input| terminated(|input| self.ryna_expr_parser(input, cache), cut(tuple((empty0, tag(";")))))(input)
2970                )),
2971                |i| vec!(i)
2972            )
2973        ))(input);
2974    }
2975
2976    pub fn ryna_operators_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<RynaExpr>> {
2977        let mut ops = vec!();
2978
2979        while input.len() > 0 {
2980            if let Ok((i, o)) = self.operator_definition_parser(input) {
2981                input = i;
2982                ops.push(o);
2983            
2984            } else {
2985                input = skip_token(input)?.0;
2986            }
2987        }
2988
2989        Ok(("".into(), ops))
2990    }
2991
2992    pub fn ryna_function_headers_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<FunctionHeader>> {
2993        let mut ops = vec!();
2994
2995        while input.len() > 0 {
2996            if let Ok((i, o)) = self.function_header_parser(input) {
2997                input = i;
2998                ops.push(o);
2999            
3000            } else {
3001                input = skip_token(input)?.0;
3002            }
3003        }
3004
3005        Ok(("".into(), ops))
3006    }
3007
3008    pub fn ryna_operations_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<RynaExpr>> {
3009        let mut ops = vec!();
3010
3011        while input.len() > 0 {
3012            if let Ok((i, o)) = self.operation_definition_parser(input, &RefCell::default()) {
3013                input = i;
3014                ops.push(o);
3015            
3016            } else {
3017                input = skip_token(input)?.0;
3018            }
3019        }
3020
3021        Ok(("".into(), ops))
3022    }
3023
3024    pub fn ryna_macros_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<RynaExpr>> {
3025        let mut ops = vec!();
3026
3027        while input.len() > 0 {
3028            if let Ok((i, o)) = self.macro_parser(input) {
3029                input = i;
3030                ops.push(o);
3031            
3032            } else {
3033                input = skip_token(input)?.0;
3034            }
3035        }
3036
3037        Ok(("".into(), ops))
3038    }
3039
3040    pub fn ryna_interface_implementation_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<RynaExpr>> {
3041        let mut ops = vec!();
3042
3043        while input.len() > 0 {
3044            if let Ok((i, o)) = self.interface_implementation_parser(input) {
3045                input = i;
3046                ops.push(o);
3047            
3048            } else {
3049                input = skip_token(input)?.0;
3050            }
3051        }
3052
3053        Ok(("".into(), ops))
3054    }
3055
3056    pub fn ryna_interface_definition_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<RynaExpr>> {
3057        let mut ops = vec!();
3058
3059        while input.len() > 0 {
3060            if let Ok((i, o)) = self.interface_definition_parser(input) {
3061                input = i;
3062                ops.push(o);
3063            
3064            } else {
3065                input = skip_token(input)?.0;
3066            }
3067        }
3068
3069        Ok(("".into(), ops))
3070    }
3071
3072    pub fn ryna_interface_definition_names_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<String>> {
3073        let mut ops = vec!();
3074
3075        while input.len() > 0 {
3076            if let Ok((i, o)) = self.interface_definition_name_parser(input) {
3077                input = i;
3078                ops.push(o);
3079            
3080            } else {
3081                input = skip_token(input)?.0;
3082            }
3083        }
3084
3085        Ok(("".into(), ops))
3086    }
3087
3088    pub fn ryna_class_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<RynaExpr>> {
3089        let mut ops = vec!();
3090
3091        while input.len() > 0 {
3092            if let Ok((i, o)) = self.class_definition_parser(input) {
3093                input = i;
3094                ops.push(o);
3095            
3096            } else if let Ok((i, o)) = self.alias_definition_parser(input) {
3097                input = i;
3098                ops.push(o);
3099            
3100            } else {
3101                input = skip_token(input)?.0;
3102            }
3103        }
3104
3105        Ok(("".into(), ops))
3106    }
3107
3108    pub fn ryna_class_names_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, HashSet<String>> {
3109        let mut ops = HashSet::new();
3110
3111        while input.len() > 0 {
3112            if let Ok((i, o)) = self.class_name_definition_parser(input) {
3113                input = i;
3114                ops.insert(o);
3115            
3116            } else if let Ok((i, o)) = self.alias_name_definition_parser(input) {
3117                input = i;
3118                ops.insert(o);
3119            
3120            } else {
3121                input = skip_token(input)?.0;
3122            }
3123        }
3124
3125        Ok(("".into(), ops))
3126    }
3127
3128    pub fn ryna_parser<'a>(&'a self, mut input: Span<'a>) -> PResult<'a, Vec<RynaExpr>> {
3129        while let Ok((i, _)) = ryna_info_parser(input, self.module_name.clone()) {
3130            input = i;
3131        }
3132
3133        let cache = RefCell::default();
3134
3135        return map(
3136            delimited(
3137                empty0,
3138                many_separated0(empty0, |input| self.ryna_global_parser(input, &cache)),
3139                tuple((empty0, eof))
3140            ),
3141            |i| i.into_iter().flatten().collect()
3142        )(input);
3143    }
3144}
3145
3146/*
3147                                                  ╒═════════╕
3148    ============================================= │  TESTS  │ =============================================
3149                                                  ╘═════════╛
3150*/
3151
3152#[cfg(test)]
3153mod tests {
3154    use crate::ARR_OF;
3155    use crate::context::*;
3156    use crate::interfaces::ITERABLE_ID;
3157    use crate::interfaces::PRINTABLE_ID;
3158    use crate::parser::*;
3159    use crate::object::*;
3160
3161    #[test]
3162    fn type_parsing() {
3163        let mut ctx = standard_ctx();
3164
3165        ctx.define_type(Location::none(), vec!(), "Map".into(), vec!("Key".into(), "Value".into()), vec!(), None, vec!(), None).unwrap();
3166        let map_id = ctx.get_type_id("Map".into()).unwrap();
3167
3168        let wildcard_str = "*";
3169        let empty_str = "()";
3170
3171        let number_str = "Int";
3172        let number_ref_str = "&Int";
3173        let string_mut_str = "@String";
3174        let wildcard_mut_str = "@*";
3175
3176        let or_str = "Int | @String";
3177        let and_str = "(Int, @String, &Bool)";
3178        let and_one_str = "(Int)";
3179
3180        let array_str = "Array<Int>";
3181        let map_str = "Map<(Int), String>";
3182        let map_refs_str = "&Map<&Int, @String>";
3183
3184        let basic_func_str = "Int => (String)";
3185        let complex_func_str = "(Int, Array<Bool>) => Map<Int, *>";
3186
3187        let template_str = "'T";
3188        let template_bounded_str = "'T [Printable, Iterable<Int>]";
3189
3190        let (_, wildcard) = ctx.type_parser(Span::new(wildcard_str)).unwrap();
3191        let (_, empty) = ctx.type_parser(Span::new(empty_str)).unwrap();
3192
3193        assert_eq!(wildcard, Type::Wildcard);
3194        assert_eq!(empty, Type::Empty);
3195
3196        let (_, number) = ctx.type_parser(Span::new(number_str)).unwrap();
3197        let (_, number_ref) = ctx.type_parser(Span::new(number_ref_str)).unwrap();
3198        let (_, string_mut) = ctx.type_parser(Span::new(string_mut_str)).unwrap();
3199        let (_, wildcard_mut) = ctx.type_parser(Span::new(wildcard_mut_str)).unwrap();
3200
3201        assert_eq!(number, INT);
3202        assert_eq!(number_ref, Type::Ref(Box::new(INT)));
3203        assert_eq!(string_mut, Type::MutRef(Box::new(STR)));
3204        assert_eq!(wildcard_mut, Type::MutRef(Box::new(Type::Wildcard)));
3205
3206        let (_, or) = ctx.type_parser(Span::new(or_str)).unwrap();
3207        let (_, and) = ctx.type_parser(Span::new(and_str)).unwrap();
3208        let (_, and_one) = ctx.type_parser(Span::new(and_one_str)).unwrap();
3209
3210        assert_eq!(or, Type::Or(vec!(INT, Type::MutRef(Box::new(STR)))));
3211        assert_eq!(and, Type::And(vec!(INT, Type::MutRef(Box::new(STR)), Type::Ref(Box::new(BOOL)))));
3212        assert_eq!(and_one, INT);
3213
3214        let (_, array) = ctx.type_parser(Span::new(array_str)).unwrap();
3215        let (_, map) = ctx.type_parser(Span::new(map_str)).unwrap();
3216        let (_, map_refs) = ctx.type_parser(Span::new(map_refs_str)).unwrap();
3217
3218        assert_eq!(array, ARR_OF!(INT));
3219        assert_eq!(map, Type::Template(map_id, vec!(INT, STR)));
3220        assert_eq!(map_refs, Type::Ref(Box::new(Type::Template(map_id, vec!(Type::Ref(Box::new(INT)), Type::MutRef(Box::new(STR)))))));
3221        
3222        let (_, basic_func) = ctx.type_parser(Span::new(basic_func_str)).unwrap();
3223        let (_, complex_func) = ctx.type_parser(Span::new(complex_func_str)).unwrap();
3224
3225        assert_eq!(basic_func, Type::Function(Box::new(INT), Box::new(STR)));
3226        assert_eq!(complex_func, Type::Function(
3227            Box::new(Type::And(vec!(
3228                INT,
3229                ARR_OF!(BOOL)
3230            ))), 
3231            Box::new(Type::Template(map_id, vec!(
3232                INT,
3233                Type::Wildcard
3234            )))
3235        ));
3236
3237        let (_, template) = ctx.type_parser(Span::new(template_str)).unwrap();
3238        let (_, template_bounded) = ctx.type_parser(Span::new(template_bounded_str)).unwrap();
3239
3240        assert_eq!(template, Type::TemplateParamStr("T".into(), vec!()));
3241        assert_eq!(template_bounded, Type::TemplateParamStr("T".into(), vec!(
3242            InterfaceConstraint::new(PRINTABLE_ID, vec!()),
3243            InterfaceConstraint::new(ITERABLE_ID, vec!(INT))
3244        )));
3245    }
3246
3247    #[test]
3248    fn literal_parsing() {
3249        let mut ctx = standard_ctx();
3250
3251        let number_str = "123";
3252        let binary_str = "0b1001101";
3253        let hex_str = "0x1A6F0";
3254        let bool_v_str = "true";
3255        let string_str = "\"test\"";
3256        let escaped_string_str = "\"test\\ntest2\\ttest3\\\"\\\\\"";
3257
3258        let (_, number) = ctx.literal_parser(Span::new(number_str), &RefCell::default()).unwrap();
3259        let (_, binary) = ctx.literal_parser(Span::new(binary_str), &RefCell::default()).unwrap();
3260        let (_, hex) = ctx.literal_parser(Span::new(hex_str), &RefCell::default()).unwrap();
3261        let (_, bool_v) = ctx.literal_parser(Span::new(bool_v_str), &RefCell::default()).unwrap();
3262        let (_, string) = ctx.literal_parser(Span::new(string_str), &RefCell::default()).unwrap();
3263        let (_, escaped_string) = ctx.literal_parser(Span::new(escaped_string_str), &RefCell::default()).unwrap();
3264
3265        assert_eq!(number, RynaExpr::Literal(Location::none(), Object::new(Integer::from(123))));
3266        assert_eq!(binary, RynaExpr::Literal(Location::none(), Object::new(Integer::from(77))));
3267        assert_eq!(hex, RynaExpr::Literal(Location::none(), Object::new(Integer::from(108272))));
3268        assert_eq!(bool_v, RynaExpr::Literal(Location::none(), Object::new(true)));
3269        assert_eq!(string, RynaExpr::Literal(Location::none(), Object::new("test".to_string())));
3270        assert_eq!(escaped_string, RynaExpr::Literal(Location::none(), Object::new("test\ntest2\ttest3\"\\".to_string())));
3271
3272        ctx.define_type(Location::none(), vec!(), "Dice".into(), vec!(), vec!(
3273            ("rolls".into(), INT),
3274            ("sides".into(), INT)
3275        ), 
3276        None,
3277        vec!(
3278            Pattern::And(vec!(
3279                Pattern::Arg(Box::new(Pattern::Repeat(Box::new(Pattern::Symbol('d')), Some(1), None)), "rolls".into()),
3280                Pattern::Str("D".into()),
3281                Pattern::Arg(Box::new(Pattern::Repeat(Box::new(Pattern::Symbol('d')), Some(1), None)), "sides".into()),
3282            ))
3283        ), Some(
3284            |ctx, c_type, s| {
3285                if let Ok((_, o)) = ctx.parse_literal_type(c_type, Span::new(s.as_str()), &RefCell::default()) {
3286                    return Ok(o);
3287                }
3288
3289                Err(format!("Unable to parse {} from {}", c_type.name, s))
3290            }
3291        )).unwrap();
3292        
3293
3294        let dice_str = "2D20";
3295
3296        let (_, dice) = ctx.literal_parser(Span::new(dice_str), &RefCell::default()).unwrap();
3297
3298        let id = ctx.get_type_id("Dice".into()).unwrap();
3299
3300        assert_eq!(dice, RynaExpr::Literal(Location::none(), Object::new(TypeInstance {
3301            id,
3302            params: vec!(),
3303            attributes: vec!(
3304                Object::new(Integer::from(2)),
3305                Object::new(Integer::from(20))
3306            )
3307        })));
3308
3309        assert_eq!(ctx.type_templates.last().unwrap().parser.unwrap()(&ctx, &ctx.type_templates[id], &"2D20".into()), Ok(Object::new(TypeInstance {
3310            id,
3311            params: vec!(),
3312            attributes: vec!(
3313                Object::new(Integer::from(2)),
3314                Object::new(Integer::from(20))
3315            )
3316        })));
3317
3318        ctx.define_type(Location::none(), vec!(), "InnerDice".into(), vec!(), vec!(
3319            ("inner_dice".into(), Type::Basic(id))
3320        ),
3321        None,
3322        vec!(
3323            Pattern::And(vec!(
3324                Pattern::Str("[".into()),
3325                Pattern::Arg(
3326                    Box::new(
3327                        Pattern::And(vec!(
3328                            Pattern::Repeat(Box::new(Pattern::Symbol('d')), Some(1), None),
3329                            Pattern::Str("D".into()),
3330                            Pattern::Repeat(Box::new(Pattern::Symbol('d')), Some(1), None),
3331                        ))
3332                    ),
3333                    "inner_dice".into(),
3334                ),
3335                Pattern::Str("]".into())
3336            ))
3337        ), None).unwrap();
3338
3339        let inner_dice_str = "[2D20]";
3340        
3341        let (_, inner_dice) = ctx.literal_parser(Span::new(inner_dice_str), &RefCell::default()).unwrap();
3342
3343        let inner_id = ctx.get_type_id("InnerDice".into()).unwrap();
3344
3345        assert_eq!(inner_dice, RynaExpr::Literal(Location::none(), Object::new(TypeInstance {
3346            id: inner_id,
3347            params: vec!(),
3348            attributes: vec!(
3349                Object::new(TypeInstance {
3350                    id,
3351                    params: vec!(),
3352                    attributes: vec!(
3353                        Object::new(Integer::from(2)),
3354                        Object::new(Integer::from(20))
3355                    )
3356                })
3357            )
3358        })));
3359    }
3360
3361    #[test]
3362    fn import_parsing() {
3363        let import_fns_str = "import fn test from module;";
3364        let import_fns_2_str = "import fn { test, test2 } from module;";
3365        let import_prefix_str = "import prefix op \"**\" from module;";
3366        let import_all_classes_str = "import class * from module;";
3367        let import_everything_str = "import * from module;";
3368        let import_everything_local_str = "import * from /module;";
3369
3370        let (_, import_fns) = module_import_parser(Span::new(import_fns_str), Arc::new("test".into())).unwrap();
3371        let (_, import_fns_2) = module_import_parser(Span::new(import_fns_2_str), Arc::new("test".into())).unwrap();
3372        let (_, import_prefix) = module_import_parser(Span::new(import_prefix_str), Arc::new("test".into())).unwrap();
3373        let (_, import_all_classes) = module_import_parser(Span::new(import_all_classes_str), Arc::new("test".into())).unwrap();
3374        let (_, import_everything) = module_import_parser(Span::new(import_everything_str), Arc::new("test".into())).unwrap();
3375        let (_, import_everything_local) = module_import_parser(Span::new(import_everything_local_str), Arc::new("test/test2".into())).unwrap();
3376
3377        assert_eq!(import_fns, ("module".into(), ImportType::Fn, ["test".into()].iter().cloned().collect()));
3378        assert_eq!(import_fns_2, ("module".into(), ImportType::Fn, ["test".into(), "test2".into()].iter().cloned().collect()));
3379        assert_eq!(import_prefix, ("module".into(), ImportType::Prefix, ["**".into()].iter().cloned().collect()));
3380        assert_eq!(import_all_classes, ("module".into(), ImportType::Class, ["*".into()].iter().cloned().collect()));
3381        assert_eq!(import_everything, ("module".into(), ImportType::All, ["*".into()].iter().cloned().collect()));
3382        assert_eq!(import_everything_local, ("test/module".into(), ImportType::All, ["*".into()].iter().cloned().collect()));
3383    }
3384
3385    #[test]
3386    fn variable_definition_parsing() {
3387        let ctx = standard_ctx();
3388
3389        let def_1_str = "let var: Int = a;";
3390        let def_str = "let foo: Array<Int | &String> = 5;";
3391        let def_3_str = "let bar = \"test\";";
3392        let def_4_str = "let foobar = false;";
3393        let def_5_str = "let lambda = (a: Int, b: Int) -> Bool { return a < b; };";
3394        let def_6_str = "let lambda = (n: Int) -> Int n * 2;";
3395        let def_7_str = "let lambda = (n: Int) n + 1;";
3396        let def_8_str = "let lambda = [a](n: Int) n + a;";
3397        let def_9_str = "let lambda = [a, b](n: Int) n + b;";
3398
3399        let (_, def_1) = ctx.variable_definition_parser(Span::new(def_1_str), &RefCell::default()).unwrap();
3400        let (_, def) = ctx.variable_definition_parser(Span::new(def_str), &RefCell::default()).unwrap();
3401        let (_, def_3) = ctx.variable_definition_parser(Span::new(def_3_str), &RefCell::default()).unwrap();
3402        let (_, def_4) = ctx.variable_definition_parser(Span::new(def_4_str), &RefCell::default()).unwrap();
3403        let (_, def_5) = ctx.variable_definition_parser(Span::new(def_5_str), &RefCell::default()).unwrap();
3404        let (_, def_6) = ctx.variable_definition_parser(Span::new(def_6_str), &RefCell::default()).unwrap();
3405        let (_, def_7) = ctx.variable_definition_parser(Span::new(def_7_str), &RefCell::default()).unwrap();
3406        let (_, def_8) = ctx.variable_definition_parser(Span::new(def_8_str), &RefCell::default()).unwrap();
3407        let (_, def_9) = ctx.variable_definition_parser(Span::new(def_9_str), &RefCell::default()).unwrap();
3408
3409        assert_eq!(def_1, RynaExpr::VariableDefinition(Location::none(), "var".into(), INT, Box::new(RynaExpr::NameReference(Location::none(), "a".into()))));
3410        assert_eq!(def, RynaExpr::VariableDefinition(Location::none(), 
3411            "foo".into(), 
3412            ARR_OF!(Type::Or(vec!(INT, STR.to_ref()))), 
3413            Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5))))
3414        ));
3415        assert_eq!(def_3, RynaExpr::VariableDefinition(Location::none(), "bar".into(), Type::InferenceMarker, Box::new(RynaExpr::Literal(Location::none(), Object::new("test".to_string())))));
3416        assert_eq!(def_4, RynaExpr::VariableDefinition(Location::none(), "foobar".into(), Type::InferenceMarker, Box::new(RynaExpr::Literal(Location::none(), Object::new(false)))));
3417        assert_eq!(def_5, RynaExpr::VariableDefinition(Location::none(), 
3418            "lambda".into(), 
3419            Type::InferenceMarker, 
3420            Box::new(RynaExpr::Lambda(Location::none(), 
3421                vec!(),
3422                vec!(
3423                    ("a".into(), INT),
3424                    ("b".into(), INT)
3425                ),
3426                BOOL,
3427                vec!(
3428                    RynaExpr::Return(Location::none(), Box::new(
3429                        RynaExpr::BinaryOperation(Location::none(), 
3430                            LT_BINOP_ID, 
3431                            vec!(),
3432                            Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
3433                            Box::new(RynaExpr::NameReference(Location::none(), "b".into()))
3434                        )
3435                    ))
3436                )
3437            ))
3438        ));
3439        assert_eq!(def_6, RynaExpr::VariableDefinition(Location::none(), 
3440            "lambda".into(), 
3441            Type::InferenceMarker, 
3442            Box::new(RynaExpr::Lambda(Location::none(), 
3443                vec!(),
3444                vec!(
3445                    ("n".into(), INT)
3446                ),
3447                INT,
3448                vec!(
3449                    RynaExpr::Return(Location::none(), Box::new(
3450                        RynaExpr::BinaryOperation(Location::none(), 
3451                            2, 
3452                            vec!(),
3453                            Box::new(RynaExpr::NameReference(Location::none(), "n".into())),
3454                            Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(2))))
3455                        )
3456                    ))
3457                )
3458            ))
3459        ));
3460        assert_eq!(def_7, RynaExpr::VariableDefinition(Location::none(), 
3461            "lambda".into(), 
3462            Type::InferenceMarker, 
3463            Box::new(RynaExpr::Lambda(Location::none(), 
3464                vec!(),
3465                vec!(
3466                    ("n".into(), INT)
3467                ),
3468                Type::InferenceMarker,
3469                vec!(
3470                    RynaExpr::Return(Location::none(), Box::new(
3471                        RynaExpr::BinaryOperation(Location::none(), 
3472                            0, 
3473                            vec!(),
3474                            Box::new(RynaExpr::NameReference(Location::none(), "n".into())),
3475                            Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1))))
3476                        )
3477                    ))
3478                )
3479            ))
3480        ));
3481        
3482        assert_eq!(def_8, RynaExpr::VariableDefinition(Location::none(), 
3483            "lambda".into(), 
3484            Type::InferenceMarker, 
3485            Box::new(RynaExpr::Lambda(Location::none(), 
3486                vec!("a".into()),
3487                vec!(
3488                    ("n".into(), INT)
3489                ),
3490                Type::InferenceMarker,
3491                vec!(
3492                    RynaExpr::Return(Location::none(), Box::new(
3493                        RynaExpr::BinaryOperation(Location::none(), 
3494                            0, 
3495                            vec!(),
3496                            Box::new(RynaExpr::NameReference(Location::none(), "n".into())),
3497                            Box::new(RynaExpr::NameReference(Location::none(), "a".into()))
3498                        )
3499                    ))
3500                )
3501            ))
3502        ));
3503        
3504        assert_eq!(def_9, RynaExpr::VariableDefinition(Location::none(), 
3505            "lambda".into(), 
3506            Type::InferenceMarker, 
3507            Box::new(RynaExpr::Lambda(Location::none(), 
3508                vec!("a".into(), "b".into()),
3509                vec!(
3510                    ("n".into(), INT)
3511                ),
3512                Type::InferenceMarker,
3513                vec!(
3514                    RynaExpr::Return(Location::none(), Box::new(
3515                        RynaExpr::BinaryOperation(Location::none(), 
3516                            0, 
3517                            vec!(),
3518                            Box::new(RynaExpr::NameReference(Location::none(), "n".into())),
3519                            Box::new(RynaExpr::NameReference(Location::none(), "b".into()))
3520                        )
3521                    ))
3522                )
3523            ))
3524        ));
3525    }
3526
3527    #[test]
3528    fn operation_parsing_edge_cases() {
3529        let mut ctx = RynaContext::default();
3530
3531        ctx.define_unary_operator("-".into(), true, 200).unwrap();
3532        ctx.define_binary_operator("+".into(), false, 150).unwrap();
3533        ctx.define_binary_operator("*".into(), false, 50).unwrap();
3534        ctx.define_binary_operator("-".into(), true, 75).unwrap();
3535
3536        let number_str = "-10";
3537        let var_str = "-5 + a";
3538        let two_bin_str = "a + b * c";
3539        let two_bin_rev_str = "a * b + c";
3540        let two_bin_grp_str = "(a + b) * c";
3541        let three_bin_left_str = "a + b + c";
3542        let three_bin_right_str = "a - b - c";
3543
3544        let (_, number) = ctx.ryna_expr_parser(Span::new(number_str), &RefCell::default()).unwrap();
3545        let (_, var) = ctx.ryna_expr_parser(Span::new(var_str), &RefCell::default()).unwrap();
3546        let (_, two_bin) = ctx.ryna_expr_parser(Span::new(two_bin_str), &RefCell::default()).unwrap();
3547        let (_, two_bin_rev) = ctx.ryna_expr_parser(Span::new(two_bin_rev_str), &RefCell::default()).unwrap();
3548        let (_, two_bin_grp) = ctx.ryna_expr_parser(Span::new(two_bin_grp_str), &RefCell::default()).unwrap();
3549        let (_, three_bin_left) = ctx.ryna_expr_parser(Span::new(three_bin_left_str), &RefCell::default()).unwrap();
3550        let (_, three_bin_right) = ctx.ryna_expr_parser(Span::new(three_bin_right_str), &RefCell::default()).unwrap();
3551
3552        assert_eq!(number, RynaExpr::UnaryOperation(Location::none(), 0, vec!(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(10))))));
3553        assert_eq!(var, 
3554            RynaExpr::UnaryOperation(Location::none(), 0, vec!(), Box::new(
3555                RynaExpr::BinaryOperation(
3556                    Location::none(), 0, vec!(), 
3557                    Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5)))),
3558                    Box::new(RynaExpr::NameReference(Location::none(), "a".into()))
3559                )
3560            ))
3561        );
3562        assert_eq!(two_bin, 
3563            RynaExpr::BinaryOperation(
3564                Location::none(), 0, vec!(), 
3565                Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
3566                Box::new(
3567                    RynaExpr::BinaryOperation(
3568                        Location::none(), 1, vec!(), 
3569                        Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
3570                        Box::new(RynaExpr::NameReference(Location::none(), "c".into()))
3571                    )
3572                ),
3573            )
3574        );
3575        assert_eq!(two_bin_rev, 
3576            RynaExpr::BinaryOperation(
3577                Location::none(), 0, vec!(), 
3578                Box::new(
3579                    RynaExpr::BinaryOperation(
3580                        Location::none(), 1, vec!(), 
3581                        Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
3582                        Box::new(RynaExpr::NameReference(Location::none(), "b".into()))
3583                    )
3584                ),
3585                Box::new(RynaExpr::NameReference(Location::none(), "c".into())),
3586            )
3587        );
3588        assert_eq!(two_bin_grp, 
3589            RynaExpr::BinaryOperation(
3590                Location::none(), 1, vec!(), 
3591                Box::new(RynaExpr::Tuple(Location::none(), vec!(
3592                    RynaExpr::BinaryOperation(
3593                        Location::none(), 0, vec!(), 
3594                        Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
3595                        Box::new(RynaExpr::NameReference(Location::none(), "b".into()))
3596                    )
3597                ))),
3598                Box::new(RynaExpr::NameReference(Location::none(), "c".into())),
3599            )
3600        );
3601        assert_eq!(three_bin_left, 
3602            RynaExpr::BinaryOperation(
3603                Location::none(), 0, vec!(), 
3604                Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
3605                Box::new(
3606                    RynaExpr::BinaryOperation(
3607                        Location::none(), 0, vec!(), 
3608                        Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
3609                        Box::new(RynaExpr::NameReference(Location::none(), "c".into()))
3610                    )
3611                ),
3612            )
3613        );
3614        assert_eq!(three_bin_right, 
3615            RynaExpr::BinaryOperation(
3616                Location::none(), 2, vec!(), 
3617                Box::new(
3618                    RynaExpr::BinaryOperation(
3619                        Location::none(), 2, vec!(), 
3620                        Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
3621                        Box::new(RynaExpr::NameReference(Location::none(), "b".into()))
3622                    )
3623                ),
3624                Box::new(RynaExpr::NameReference(Location::none(), "c".into())),
3625            )
3626        );
3627    }
3628
3629    #[test]
3630    fn complex_operation_parsing() {
3631        let mut ctx = standard_ctx();
3632
3633        ctx.define_unary_operator("?".into(), false, 150).unwrap();
3634
3635        let var_str = "-!a";
3636        let n_var_str = "-5 + a?";
3637        let n_call_str = "5(-b + !10)";
3638        let template_func_str = "funct<Int>(5)";
3639        let template_prefix_str = "!<Int>7";
3640        let template_postfix_str = "false<&String>?";
3641        let template_binary_str = "\"test\" <String, Bool>+ true";
3642        let nested_op_str = "(1 + 2) * 3";
3643
3644        let (_, var) = ctx.ryna_expr_parser(Span::new(var_str), &RefCell::default()).unwrap();
3645        let (_, n_var) = ctx.ryna_expr_parser(Span::new(n_var_str), &RefCell::default()).unwrap();
3646        let (_, n_call) = ctx.ryna_expr_parser(Span::new(n_call_str), &RefCell::default()).unwrap();
3647        let (_, template_func) = ctx.ryna_expr_parser(Span::new(template_func_str), &RefCell::default()).unwrap();
3648        let (_, template_prefix) = ctx.ryna_expr_parser(Span::new(template_prefix_str), &RefCell::default()).unwrap();
3649        let (_, template_postfix) = ctx.ryna_expr_parser(Span::new(template_postfix_str), &RefCell::default()).unwrap();
3650        let (_, template_binary) = ctx.ryna_expr_parser(Span::new(template_binary_str), &RefCell::default()).unwrap();
3651        let (_, nested_op) = ctx.ryna_expr_parser(Span::new(nested_op_str), &RefCell::default()).unwrap();
3652
3653        assert_eq!(
3654            var, 
3655            RynaExpr::UnaryOperation(Location::none(), 0, vec!(), 
3656            Box::new(RynaExpr::UnaryOperation(Location::none(), 1, vec!(), Box::new(RynaExpr::NameReference(Location::none(), "a".into()))))
3657        ));
3658        assert_eq!(n_var, RynaExpr::BinaryOperation(Location::none(), 
3659            0, 
3660            vec!(),
3661            Box::new(RynaExpr::UnaryOperation(Location::none(), 0, vec!(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5)))))),
3662            Box::new(RynaExpr::UnaryOperation(Location::none(), 3, vec!(), Box::new(RynaExpr::NameReference(Location::none(), "a".into())))),
3663        ));
3664        assert_eq!(n_call, RynaExpr::NaryOperation(Location::none(), 
3665            0, 
3666            vec!(),
3667            Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5)))),
3668            vec!(
3669                RynaExpr::BinaryOperation(Location::none(), 
3670                    0, 
3671                    vec!(),
3672                    Box::new(RynaExpr::UnaryOperation(Location::none(), 0, vec!(), Box::new(RynaExpr::NameReference(Location::none(), "b".into())))),
3673                    Box::new(RynaExpr::UnaryOperation(Location::none(), 1, vec!(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(10)))))),
3674                )
3675            )
3676        ));
3677        assert_eq!(template_func, RynaExpr::NaryOperation(Location::none(), 
3678            0, 
3679            vec!(INT),
3680            Box::new(RynaExpr::NameReference(Location::none(), "funct".into())),
3681            vec!(
3682                RynaExpr::Literal(Location::none(), Object::new(Integer::from(5)))
3683            )
3684        ));
3685        assert_eq!(
3686            template_prefix, 
3687            RynaExpr::UnaryOperation(Location::none(), 
3688                1, 
3689                vec!(INT), 
3690                Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(7))))
3691            )
3692        );
3693        assert_eq!(
3694            template_postfix, 
3695            RynaExpr::UnaryOperation(Location::none(), 
3696                3, 
3697                vec!(Type::Ref(Box::new(STR))), 
3698                Box::new(RynaExpr::Literal(Location::none(), Object::new(false)))
3699            )
3700        );
3701        assert_eq!(
3702            template_binary, 
3703            RynaExpr::BinaryOperation(Location::none(), 
3704                0, 
3705                vec!(STR, BOOL), 
3706                Box::new(RynaExpr::Literal(Location::none(), Object::new("test".to_string()))),
3707                Box::new(RynaExpr::Literal(Location::none(), Object::new(true)))
3708            )
3709        );
3710        assert_eq!(
3711            nested_op, 
3712            RynaExpr::BinaryOperation(Location::none(), 
3713                2, 
3714                vec!(), 
3715                Box::new(RynaExpr::Tuple(Location::none(), vec!(
3716                    RynaExpr::BinaryOperation(Location::none(), 
3717                        0, 
3718                        vec!(), 
3719                        Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1)))),
3720                        Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(2))))
3721                    )
3722                ))),
3723                Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(3))))
3724            )
3725        );
3726    }
3727
3728    #[test]
3729    fn function_header_parsing() {
3730        let mut ctx = standard_ctx();
3731
3732        ctx.define_type(Location::none(), vec!(), "Map".into(), vec!("Key".into(), "Value".into()), vec!(), None, vec!(), None).unwrap();
3733        let map_id = ctx.get_type_id("Map".into()).unwrap();
3734
3735        let number_header_str = "fn test(a: Int) -> Int";
3736        let ref_header_str = "fn test(arg: &Int) -> @Int";
3737        let two_args_header_str = "fn test_3(arg_1: &Int, arg: String | Int) -> Int | String";
3738        let complex_args_header_str = "fn test_4(a: String | &Int, b: &Array<(Bool, Int)>, c: @*) -> Map<Int, String>";
3739
3740        let (_, number_header) = ctx.function_header_parser(Span::new(number_header_str)).unwrap();
3741        let (_, ref_header) = ctx.function_header_parser(Span::new(ref_header_str)).unwrap();
3742        let (_, two_args_header) = ctx.function_header_parser(Span::new(two_args_header_str)).unwrap();
3743        let (_, complex_args_header) = ctx.function_header_parser(Span::new(complex_args_header_str)).unwrap();
3744
3745        assert_eq!(number_header, ("test".into(), None, vec!(("a".into(), INT)), INT));
3746        assert_eq!(ref_header, ("test".into(), None, vec!(("arg".into(), Type::Ref(Box::new(INT)))), Type::MutRef(Box::new(INT))));
3747        assert_eq!(two_args_header, (
3748            "test_3".into(), 
3749            None,
3750            vec!(
3751                ("arg_1".into(), Type::Ref(Box::new(INT))),
3752                ("arg".into(), Type::Or(vec!(
3753                    INT,
3754                    STR
3755                )))
3756            ),
3757            Type::Or(vec!(
3758                INT,
3759                STR
3760            ))
3761        ));
3762        assert_eq!(complex_args_header, (
3763            "test_4".into(), 
3764            None, 
3765            vec!(
3766                ("a".into(), Type::Or(vec!(
3767                    Type::Ref(Box::new(INT)),
3768                    STR
3769                ))),
3770                ("b".into(), Type::Ref(Box::new(
3771                    Type::Template(
3772                        ARR_ID,
3773                        vec!(Type::And(vec!(
3774                            BOOL,
3775                            INT
3776                        )))
3777                    ))
3778                )),
3779                ("c".into(), Type::MutRef(Box::new(Type::Wildcard)))
3780            ),
3781            Type::Template(
3782                map_id,
3783                vec!(
3784                    INT,
3785                    STR
3786                )
3787            )
3788        ));
3789    }
3790
3791    #[test]
3792    fn function_definition_and_flow_control_parsing() {
3793        let mut ctx = standard_ctx();
3794
3795        ctx.define_type(Location::none(), vec!(), "Map".into(), vec!("Key".into(), "Value".into()), vec!(), None, vec!(), None).unwrap();
3796        let map_id = ctx.get_type_id("Map".into()).unwrap();
3797
3798        let test_1_str = "fn inc() -> Int {
3799            let res = 5;
3800
3801            for i in arr {
3802                return 7;
3803            }
3804
3805            return res;
3806        }";
3807
3808        let test_str = "fn inc(arg: &Int) -> Int | String {
3809            let r: Int = arg + 1;
3810
3811            if r + 1 {
3812                return \"a\";
3813            
3814            } else if arg + 2 {
3815                r = r + 1;    
3816            
3817            } else {
3818                return 5;    
3819            }
3820
3821            return r;
3822        }";
3823
3824        let test_3_str = "fn<K, V> inc(key: 'K, value: 'V) -> Map<'K, 'V> {
3825            let a: 'V | 'K = value + key;
3826            return a;
3827        }";
3828
3829        let (_, test_1) = ctx.function_definition_parser(Span::new(test_1_str), &RefCell::default()).unwrap();
3830        let (_, test) = ctx.function_definition_parser(Span::new(test_str), &RefCell::default()).unwrap();
3831        let (_, test_3) = ctx.function_definition_parser(Span::new(test_3_str), &RefCell::default()).unwrap();
3832
3833        assert_eq!(
3834            test_1,
3835            RynaExpr::FunctionDefinition(Location::none(), 
3836                vec!(),
3837                0,
3838                vec!(),
3839                vec!(),
3840                INT,
3841                vec!(
3842                    RynaExpr::VariableDefinition(Location::none(), "res".into(), Type::InferenceMarker, Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5))))),
3843                    RynaExpr::For(Location::none(), 
3844                        "i".into(),
3845                        Box::new(RynaExpr::NameReference(Location::none(), "arr".into())),
3846                        vec!(
3847                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(7)))))
3848                        )
3849                    ),
3850                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::NameReference(Location::none(), "res".into())))
3851                )
3852            ) 
3853        );
3854
3855        assert_eq!(
3856            test,
3857            RynaExpr::FunctionDefinition(Location::none(), 
3858                vec!(),
3859                0,
3860                vec!(),
3861                vec!(
3862                    (
3863                        "arg".into(), 
3864                        Type::Ref(Box::new(INT))
3865                    )
3866                ),
3867                Type::Or(vec!(
3868                    INT,
3869                    STR
3870                )),
3871                vec!(
3872                    RynaExpr::VariableDefinition(Location::none(), 
3873                        "r".into(), 
3874                        INT, 
3875                        Box::new(RynaExpr::BinaryOperation(Location::none(), 
3876                            0,
3877                            vec!(),
3878                            Box::new(RynaExpr::NameReference(Location::none(), "arg".into())),
3879                            Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1))))
3880                        ))
3881                    ),
3882                    RynaExpr::If(Location::none(), 
3883                        Box::new(RynaExpr::BinaryOperation(Location::none(), 
3884                            0,
3885                            vec!(),
3886                            Box::new(RynaExpr::NameReference(Location::none(), "r".into())),
3887                            Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1))))
3888                        )),
3889                        vec!(
3890                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new("a".to_string()))))
3891                        ),
3892                        vec!(
3893                            (
3894                                RynaExpr::BinaryOperation(Location::none(), 
3895                                    0,
3896                                    vec!(),
3897                                    Box::new(RynaExpr::NameReference(Location::none(), "arg".into())),
3898                                    Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(2))))
3899                                ),
3900                                vec!(
3901                                    RynaExpr::VariableAssignment(Location::none(), 
3902                                        "r".into(),
3903                                        Box::new(RynaExpr::BinaryOperation(Location::none(), 
3904                                            0,
3905                                            vec!(),
3906                                            Box::new(RynaExpr::NameReference(Location::none(), "r".into())),
3907                                            Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1))))
3908                                        ))
3909                                    )
3910                                )
3911                            )
3912                        ),
3913                        Some(vec!(
3914                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5)))))
3915                        ))
3916                    ),
3917                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::NameReference(Location::none(), "r".into())))
3918                )
3919            ) 
3920        );
3921        assert_eq!(
3922            test_3,
3923            RynaExpr::FunctionDefinition(Location::none(), 
3924                vec!(),
3925                0,
3926                vec!("K".into(), "V".into()),
3927                vec!(
3928                    ("key".into(), T_0),
3929                    ("value".into(), T_1)
3930                ),
3931                Type::Template(map_id, vec!(T_0, T_1)),
3932                vec!(
3933                    RynaExpr::VariableDefinition(Location::none(), 
3934                        "a".into(), 
3935                        Type::Or(vec!(T_0, T_1)), 
3936                        Box::new(RynaExpr::BinaryOperation(Location::none(), 
3937                            0,
3938                            vec!(),
3939                            Box::new(RynaExpr::NameReference(Location::none(), "value".into())),
3940                            Box::new(RynaExpr::NameReference(Location::none(), "key".into())),
3941                        ))
3942                    ),
3943                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::NameReference(Location::none(), "a".into())))
3944                )
3945            ) 
3946        );
3947    }
3948
3949    #[test]
3950    fn operator_definition_parsing() {
3951        let ctx = standard_ctx();
3952
3953        let prefix_str = "unary prefix op \"~\" (200);";
3954        let postfix_str = "unary postfix op \"&\" (300);";
3955        let binary_str = "binary op \"$\" (400);";
3956        let nary_str = "nary op from \"`\" to \"´\" (500);";
3957
3958        let (_, prefix) = ctx.operator_definition_parser(Span::new(prefix_str)).unwrap();
3959        let (_, postfix) = ctx.operator_definition_parser(Span::new(postfix_str)).unwrap();
3960        let (_, binary) = ctx.operator_definition_parser(Span::new(binary_str)).unwrap();
3961        let (_, nary) = ctx.operator_definition_parser(Span::new(nary_str)).unwrap();
3962
3963        assert_eq!(prefix, RynaExpr::PrefixOperatorDefinition(Location::none(), "~".into(), 200));
3964        assert_eq!(postfix, RynaExpr::PostfixOperatorDefinition(Location::none(), "&".into(), 300));
3965        assert_eq!(binary, RynaExpr::BinaryOperatorDefinition(Location::none(), "$".into(), false, 400));
3966        assert_eq!(nary, RynaExpr::NaryOperatorDefinition(Location::none(), "`".into(), "´".into(), 500));
3967    }
3968
3969    #[test]
3970    fn operation_definition_and_flow_control_parsing() {
3971        let mut ctx = standard_ctx();
3972
3973        ctx.define_unary_operator("?".into(), false, 150).unwrap();
3974
3975        let test_1_str = "op !(arg: Bool) -> Bool {
3976            if arg {
3977                return false;
3978            }
3979
3980            return true;
3981        }";
3982
3983        let test_str = "op (arg: Bool)? -> Int | Bool {
3984            if arg {
3985                return 5;
3986            }
3987
3988            for i in arr {
3989                return i;
3990            }
3991
3992            return true;
3993        }";
3994
3995        let test_3_str = "op (a: Bool) + (b: Bool) -> Int {
3996            if a {
3997                if b {
3998                    return 2;
3999                }
4000
4001                return 1;
4002            }
4003
4004            if b {
4005                return 1;
4006            }
4007
4008            return 0;
4009        }";
4010
4011        let test_4_str = "op (a: Int)[b: Int, c: Int] -> (Int, Bool) {
4012            return (a + b * c, true);
4013        }";
4014
4015        let (_, test_1) = ctx.operation_definition_parser(Span::new(test_1_str), &RefCell::default()).unwrap();
4016        let (_, test) = ctx.operation_definition_parser(Span::new(test_str), &RefCell::default()).unwrap();
4017        let (_, test_3) = ctx.operation_definition_parser(Span::new(test_3_str), &RefCell::default()).unwrap();
4018        let (_, test_4) = ctx.operation_definition_parser(Span::new(test_4_str), &RefCell::default()).unwrap();
4019
4020        assert_eq!(
4021            test_1,
4022            RynaExpr::PrefixOperationDefinition(Location::none(), 
4023                vec!(),
4024                1,
4025                vec!(),
4026                "arg".into(),
4027                BOOL,
4028                BOOL,
4029                vec!(
4030                    RynaExpr::If(Location::none(), 
4031                        Box::new(RynaExpr::NameReference(Location::none(), "arg".into())),
4032                        vec!(
4033                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(false))))
4034                        ),
4035                        vec!(),
4036                        None
4037                    ),
4038                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(true))))
4039                )
4040            ) 
4041        );
4042
4043        assert_eq!(
4044            test,
4045            RynaExpr::PostfixOperationDefinition(Location::none(),
4046                vec!(),
4047                3,
4048                vec!(),
4049                "arg".into(),
4050                BOOL,
4051                Type::Or(vec!(
4052                    INT,
4053                    BOOL
4054                )),
4055                vec!(
4056                    RynaExpr::If(Location::none(), 
4057                        Box::new(RynaExpr::NameReference(Location::none(), "arg".into())),
4058                        vec!(
4059                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5)))))
4060                        ),
4061                        vec!(),
4062                        None
4063                    ),
4064                    RynaExpr::For(Location::none(), 
4065                        "i".into(),
4066                        Box::new(RynaExpr::NameReference(Location::none(), "arr".into())),
4067                        vec!(
4068                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::NameReference(Location::none(), "i".into())))
4069                        )
4070                    ),
4071                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(true))))
4072                )
4073            ) 
4074        );
4075
4076        assert_eq!(
4077            test_3,
4078            RynaExpr::BinaryOperationDefinition(Location::none(), 
4079                vec!(),
4080                0,
4081                vec!(),
4082                ("a".into(), BOOL),
4083                ("b".into(), BOOL),
4084                INT,
4085                vec!(
4086                    RynaExpr::If(Location::none(), 
4087                        Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
4088                        vec!(
4089                            RynaExpr::If(Location::none(), 
4090                                Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
4091                                vec!(
4092                                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(2)))))
4093                                ),
4094                                vec!(),
4095                                None
4096                            ),
4097                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1)))))
4098                        ),
4099                        vec!(),
4100                        None
4101                    ),
4102                    RynaExpr::If(Location::none(), 
4103                        Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
4104                        vec!(
4105                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1)))))
4106                        ),
4107                        vec!(),
4108                        None
4109                    ),
4110                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(0)))))
4111                )
4112            ) 
4113        );
4114
4115        assert_eq!(
4116            test_4,
4117            RynaExpr::NaryOperationDefinition(Location::none(), 
4118                vec!(),
4119                1,
4120                vec!(),
4121                ("a".into(), INT),
4122                vec!(
4123                    ("b".into(), INT),
4124                    ("c".into(), INT)
4125                ),
4126                Type::And(vec!(INT, BOOL)),
4127                vec!(
4128                    RynaExpr::Return(Location::none(), Box::new(
4129                        RynaExpr::Tuple(Location::none(), vec!(
4130                            RynaExpr::BinaryOperation(Location::none(), 
4131                                0,
4132                                vec!(),
4133                                Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
4134                                Box::new(RynaExpr::BinaryOperation(Location::none(), 
4135                                    2,
4136                                    vec!(),
4137                                    Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
4138                                    Box::new(RynaExpr::NameReference(Location::none(), "c".into()))
4139                                )
4140                            )),
4141                            RynaExpr::Literal(Location::none(), Object::new(true))
4142                        ))
4143                    ))
4144                )
4145            )
4146        );
4147
4148        let test_template_1_str = "op<T> !(arg: 'T) -> 'T {
4149            if arg {
4150                return false;
4151            }
4152
4153            return true;
4154        }";
4155
4156        let test_template_str = "op<T> (arg: 'T)? -> Int | 'T {
4157            if arg {
4158                return 5;
4159            }
4160
4161            for i in arr {
4162                return i;
4163            }
4164
4165            return true;
4166        }";
4167
4168        let test_template_3_str = "op<T, G> (a: 'T) + (b: 'T) -> 'G {
4169            if a {
4170                if b {
4171                    return 2;
4172                }
4173
4174                return 1;
4175            }
4176
4177            if b {
4178                return 1;
4179            }
4180
4181            return 0;
4182        }";
4183
4184        let test_template_4_str = "op<T, G> (a: 'T)[b: 'G, c: Int] -> ('T, Array<'G>) {
4185            return (a + b * c, true);
4186        }";
4187
4188        let (_, test_template_1) = ctx.operation_definition_parser(Span::new(test_template_1_str), &RefCell::default()).unwrap();
4189        let (_, test_template) = ctx.operation_definition_parser(Span::new(test_template_str), &RefCell::default()).unwrap();
4190        let (_, test_template_3) = ctx.operation_definition_parser(Span::new(test_template_3_str), &RefCell::default()).unwrap();
4191        let (_, test_template_4) = ctx.operation_definition_parser(Span::new(test_template_4_str), &RefCell::default()).unwrap();
4192
4193        assert_eq!(
4194            test_template_1,
4195            RynaExpr::PrefixOperationDefinition(Location::none(), 
4196                vec!(),
4197                1,
4198                vec!("T".into()),
4199                "arg".into(),
4200                T_0,
4201                T_0,
4202                vec!(
4203                    RynaExpr::If(Location::none(), 
4204                        Box::new(RynaExpr::NameReference(Location::none(), "arg".into())),
4205                        vec!(
4206                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(false))))
4207                        ),
4208                        vec!(),
4209                        None
4210                    ),
4211                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(true))))
4212                )
4213            ) 
4214        );
4215
4216        assert_eq!(
4217            test_template,
4218            RynaExpr::PostfixOperationDefinition(Location::none(), 
4219                vec!(),
4220                3,
4221                vec!("T".into()),
4222                "arg".into(),
4223                T_0,
4224                Type::Or(vec!(
4225                    INT,
4226                    T_0
4227                )),
4228                vec!(
4229                    RynaExpr::If(Location::none(), 
4230                        Box::new(RynaExpr::NameReference(Location::none(), "arg".into())),
4231                        vec!(
4232                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(5)))))
4233                        ),
4234                        vec!(),
4235                        None
4236                    ),
4237                    RynaExpr::For(Location::none(), 
4238                        "i".into(),
4239                        Box::new(RynaExpr::NameReference(Location::none(), "arr".into())),
4240                        vec!(
4241                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::NameReference(Location::none(), "i".into())))
4242                        )
4243                    ),
4244                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(true))))
4245                )
4246            ) 
4247        );
4248
4249        assert_eq!(
4250            test_template_3,
4251            RynaExpr::BinaryOperationDefinition(Location::none(), 
4252                vec!(),
4253                0,
4254                vec!("T".into(), "G".into()),
4255                ("a".into(), T_0),
4256                ("b".into(), T_0),
4257                T_1,
4258                vec!(
4259                    RynaExpr::If(Location::none(), 
4260                        Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
4261                        vec!(
4262                            RynaExpr::If(Location::none(), 
4263                                Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
4264                                vec!(
4265                                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(2)))))
4266                                ),
4267                                vec!(),
4268                                None
4269                            ),
4270                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1)))))
4271                        ),
4272                        vec!(),
4273                        None
4274                    ),
4275                    RynaExpr::If(Location::none(), 
4276                        Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
4277                        vec!(
4278                            RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(1)))))
4279                        ),
4280                        vec!(),
4281                        None
4282                    ),
4283                    RynaExpr::Return(Location::none(), Box::new(RynaExpr::Literal(Location::none(), Object::new(Integer::from(0)))))
4284                )
4285            ) 
4286        );
4287
4288        assert_eq!(
4289            test_template_4,
4290            RynaExpr::NaryOperationDefinition(Location::none(), 
4291                vec!(),
4292                1,
4293                vec!("T".into(), "G".into()),
4294                ("a".into(), T_0),
4295                vec!(
4296                    ("b".into(), T_1),
4297                    ("c".into(), INT)
4298                ),
4299                Type::And(vec!(T_0, ARR_OF!(T_1))),
4300                vec!(
4301                    RynaExpr::Return(Location::none(), Box::new(
4302                        RynaExpr::Tuple(Location::none(), vec!(
4303                            RynaExpr::BinaryOperation(Location::none(), 
4304                                0,
4305                                vec!(),
4306                                Box::new(RynaExpr::NameReference(Location::none(), "a".into())),
4307                                Box::new(RynaExpr::BinaryOperation(Location::none(), 
4308                                    2,
4309                                    vec!(),
4310                                    Box::new(RynaExpr::NameReference(Location::none(), "b".into())),
4311                                    Box::new(RynaExpr::NameReference(Location::none(), "c".into()))
4312                                )
4313                            )),
4314                            RynaExpr::Literal(Location::none(), Object::new(true))
4315                        ))
4316                    ))
4317                )
4318            )
4319        );
4320    }
4321
4322    #[test]
4323    fn class_definition_parsing() {
4324        let ctx = standard_ctx();
4325
4326        let dice_roll_str = "class DiceRoll {
4327            faces: Int;
4328            rolls: Int;
4329        }";
4330
4331        let sync_lists_str = "class SyncLists<K, V> {
4332            syntax from \"test\";
4333            syntax from [[a-h] | d];
4334            syntax from Arg([\"-\"], Sign) Arg(1{d}, Int) [\".\" Arg(1{d}, Dec)];
4335
4336            from: Array<'K>;
4337            to: Array<'V>;
4338        }";
4339
4340        let (_, dice_roll) = ctx.class_definition_parser(Span::new(dice_roll_str)).unwrap();
4341        let (_, sync_lists) = ctx.class_definition_parser(Span::new(sync_lists_str)).unwrap();
4342
4343        assert_eq!(dice_roll, RynaExpr::ClassDefinition(Location::none(), 
4344            vec!(),
4345            "DiceRoll".into(),
4346            vec!(),
4347            vec!(
4348                ("faces".into(), INT),
4349                ("rolls".into(), INT)
4350            ),
4351            None,
4352            vec!()
4353        ));
4354
4355        assert_eq!(sync_lists, RynaExpr::ClassDefinition(Location::none(), 
4356            vec!(),
4357            "SyncLists".into(),
4358            vec!("K".into(), "V".into()),
4359            vec!(
4360                ("from".into(), ARR_OF!(T_0)),
4361                ("to".into(), ARR_OF!(T_1))
4362            ),
4363            None,
4364            vec!(
4365                Pattern::Str("test".into()),
4366                Pattern::Optional(Box::new(Pattern::Or(vec!(
4367                    Pattern::Range('a', 'h'),
4368                    Pattern::Symbol('d')
4369                )))),
4370                Pattern::And(vec!(
4371                    Pattern::Arg(
4372                        Box::new(Pattern::Optional(
4373                            Box::new(Pattern::Str("-".into()))
4374                        )),
4375                        "Sign".into()
4376                    ),
4377                    Pattern::Arg(
4378                        Box::new(
4379                            Pattern::Repeat(
4380                                Box::new(Pattern::Symbol('d')),
4381                                Some(1),
4382                                None
4383                            ),
4384                        ),
4385                        "Int".into()
4386                    ),
4387                    Pattern::Optional(Box::new(
4388                        Pattern::And(vec!(
4389                            Pattern::Str(".".into()),
4390                            Pattern::Arg(
4391                                Box::new(Pattern::Repeat(
4392                                    Box::new(Pattern::Symbol('d')),
4393                                    Some(1),
4394                                    None
4395                                )),
4396                                "Dec".into()
4397                            )
4398                        ))
4399                    ))
4400                ))
4401            )
4402        ));
4403    }
4404
4405    #[test]
4406    fn alias_definition_parsing() {
4407        let ctx = standard_ctx();
4408
4409        let number_str = "type Number = Int | Float;";
4410
4411        let (_, number) = ctx.alias_definition_parser(Span::new(number_str)).unwrap();
4412
4413        assert_eq!(number, RynaExpr::ClassDefinition(Location::none(), 
4414            vec!(),
4415            "Number".into(),
4416            vec!(),
4417            vec!(),
4418            Some(Type::Or(vec!(
4419                INT, FLOAT
4420            ))),
4421            vec!()
4422        ));
4423    }
4424}