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