1use bumpalo::collections::Vec as BumpVec;
6use nash_region::{Located, Position, Region};
7use nash_source::{BinOpOperand, Expr};
8
9use crate::Parser;
10use crate::error;
11
12mod accessor;
13mod bytes;
14mod case;
15mod do_;
16mod if_;
17mod keyword;
18mod lambda;
19mod let_;
20mod list;
21mod macro_;
22mod number;
23mod record;
24mod string;
25mod tuple;
26mod variable;
27
28impl<'a> Parser<'a> {
29 pub fn expression(&mut self) -> Result<(&'a Located<Expr<'a>>, Position), error::Expr<'a>> {
48 let start = self.get_position();
49
50 self.one_of(
51 error::Expr::Start,
52 vec![
53 Box::new(|p: &mut Parser<'a>| p.let_(start)),
55 Box::new(|p: &mut Parser<'a>| p.case_(start)),
57 Box::new(|p: &mut Parser<'a>| p.if_(start)),
59 Box::new(|p: &mut Parser<'a>| p.lambda(start)),
61 Box::new(|p| p.assert_(start)),
62 Box::new(|p| p.fail(start)),
63 Box::new(|p| p.todo(start)),
64 Box::new(|p| p.trace(start)),
65 Box::new(|p| p.comptime(start)),
66 Box::new(|p| p.do_(start)),
67 Box::new(|p| {
69 let expr = p.possibly_negative_term(start)?;
70 let end = p.get_position();
71 p.chomp(error::Expr::Space)?;
72 p.chomp_expr_end(start, expr, vec![], end)
73 }),
74 ],
75 )
76 }
77
78 pub(crate) fn chomp_expr_end(
96 &mut self,
97 start: Position,
98 expr: &'a Located<Expr<'a>>,
99 args: Vec<&'a Located<Expr<'a>>>,
100 end: Position,
101 ) -> Result<(&'a Located<Expr<'a>>, Position), error::Expr<'a>> {
102 let mut ops: BumpVec<'a, &'a BinOpOperand<'a>> = BumpVec::new_in(self.bump);
104 let mut current_expr = expr;
105 let mut current_args = args;
106 let mut current_end = end;
107
108 loop {
109 let state_for_fallback = (ops.clone(), current_expr, current_args.clone(), current_end);
110
111 let result = if self.is_trailing_section_operator() {
112 ExprEndState::Done
113 } else {
114 self.one_of_with_fallback(
115 vec![
116 Box::new(|p: &mut Parser<'a>| {
118 let (row, col) = p.position();
119 p.check_indent(row, col, error::Expr::Start)?;
120 let arg = p.term()?;
121 let new_end = p.get_position();
122 p.chomp(error::Expr::Space)?;
123
124 let mut new_args = current_args.clone();
125 new_args.push(arg);
126
127 Ok(ExprEndState::MoreArgs(new_args, new_end))
128 }),
129 Box::new(|p: &mut Parser<'a>| {
131 let (row, col) = p.position();
132 p.check_indent(row, col, error::Expr::Start)?;
133
134 let op_start = p.get_position();
136
137 let op = p.add_location_operator(
138 error::Expr::Start,
139 error::Expr::OperatorReserved,
140 )?;
141 let op_name = op.value;
142 let op_end = p.get_position();
143
144 p.chomp_and_check_indent(error::Expr::Space, |row, col| {
145 error::Expr::IndentOperatorRight(op_name, row, col)
146 })?;
147
148 let new_start = p.get_position();
149
150 if op_name == "-"
153 && current_end != op_start && op_end == new_start
155 {
157 let negated_expr = p.term()?;
159 let neg_end = p.get_position();
160 let neg_region = Region::new(op_start, neg_end);
161 let neg =
162 p.alloc(Located::at(neg_region, Expr::Negate(negated_expr)));
163 p.chomp(error::Expr::Space)?;
164
165 let mut new_args = current_args.clone();
166 new_args.push(neg);
167
168 Ok(ExprEndState::MoreArgs(new_args, neg_end))
169 } else {
170 p.one_of(
172 |row, col| error::Expr::OperatorRight(op_name, row, col),
173 vec![
174 Box::new(|p: &mut Parser<'a>| {
176 let new_expr = p.possibly_negative_term(new_start)?;
177 let new_end = p.get_position();
178 p.chomp(error::Expr::Space)?;
179
180 Ok(ExprEndState::MoreOps(op, new_expr, new_end))
181 }),
182 Box::new(|p: &mut Parser<'a>| {
184 let (final_expr, final_end) = p.one_of(
185 |row, col| {
186 error::Expr::OperatorRight(op_name, row, col)
187 },
188 vec![
189 Box::new(|p: &mut Parser<'a>| {
190 p.let_(new_start)
191 }),
192 Box::new(|p| p.case_(new_start)),
193 Box::new(|p| p.if_(new_start)),
194 Box::new(|p| p.lambda(new_start)),
195 Box::new(|p| p.assert_(new_start)),
196 Box::new(|p| p.fail(new_start)),
197 Box::new(|p| p.todo(new_start)),
198 Box::new(|p| p.trace(new_start)),
199 Box::new(|p| p.comptime(new_start)),
200 Box::new(|p| p.do_(new_start)),
201 ],
202 )?;
203
204 Ok(ExprEndState::Final(op, final_expr, final_end))
205 }),
206 ],
207 )
208 }
209 }),
210 ],
211 ExprEndState::Done,
212 )?
213 };
214
215 match result {
216 ExprEndState::MoreArgs(new_args, new_end) => {
217 current_args = new_args;
218 current_end = new_end;
219 }
220 ExprEndState::MoreOps(op, new_expr, new_end) => {
221 let call_expr = to_call(self, start, current_expr, current_args.clone());
223 let operand = self.alloc(BinOpOperand {
224 expr: call_expr,
225 op,
226 });
227 ops.push(operand);
228 current_expr = new_expr;
229 current_args = Vec::new();
230 current_end = new_end;
231 }
232 ExprEndState::Final(op, final_expr, final_end) => {
233 let call_expr = to_call(self, start, current_expr, current_args);
235 let operand = self.alloc(BinOpOperand {
236 expr: call_expr,
237 op,
238 });
239 ops.push(operand);
240
241 let ops_slice = ops.into_bump_slice();
242 let binops = Expr::BinOps {
243 operands: ops_slice,
244 last: final_expr,
245 };
246 let result = self.alloc(Located::at(Region::new(start, final_end), binops));
247 return Ok((result, final_end));
248 }
249 ExprEndState::Done => {
250 let (saved_ops, saved_expr, saved_args, saved_end) = state_for_fallback;
252 let final_call = to_call(self, start, saved_expr, saved_args);
253
254 if saved_ops.is_empty() {
255 return Ok((final_call, saved_end));
256 } else {
257 let ops_slice = saved_ops.into_bump_slice();
258 let binops = Expr::BinOps {
259 operands: ops_slice,
260 last: final_call,
261 };
262 let result = self.alloc(Located::at(Region::new(start, saved_end), binops));
263 return Ok((result, saved_end));
264 }
265 }
266 }
267 }
268 }
269
270 fn is_trailing_section_operator(&mut self) -> bool {
272 let saved = self.save_state();
273 let result = self
274 .operator(|_, _| (), |_, _, _| ())
275 .and_then(|_| self.chomp(|_, _, _| ()))
276 .is_ok()
277 && self.peek() == Some(b')');
278 self.restore_state(saved);
279 result
280 }
281
282 fn possibly_negative_term(
295 &mut self,
296 start: Position,
297 ) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
298 self.one_of(
299 error::Expr::Start,
300 vec![
301 Box::new(|p: &mut Parser<'a>| {
302 p.word1(b'-', error::Expr::Start)?;
303 let expr = p.term()?;
304 Ok(p.add_end(start, Expr::Negate(expr)))
305 }),
306 Box::new(|p| p.term()),
307 ],
308 )
309 }
310
311 pub fn term(&mut self) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
325 let start = self.get_position();
326
327 self.one_of(
328 error::Expr::Start,
329 vec![
330 Box::new(|p: &mut Parser<'a>| {
331 let variable = p.variable(start)?;
332 let expr = p.macro_call_or_term(start, variable)?;
333 p.accessible(start, expr)
334 }),
335 Box::new(|p| p.bytes(start)),
336 Box::new(|p| p.string(start)),
337 Box::new(|p| p.number(start)),
338 Box::new(|p| p.list(start)),
339 Box::new(|p| {
340 let expr = p.record(start)?;
341 p.accessible(start, expr)
342 }),
343 Box::new(|p| {
344 let expr = p.tuple(start)?;
345 p.accessible(start, expr)
346 }),
347 Box::new(|p| p.accessor(start)),
348 ],
349 )
350 }
351}
352
353fn to_call<'a>(
363 parser: &Parser<'a>,
364 _start: Position,
365 func: &'a Located<Expr<'a>>,
366 args: Vec<&'a Located<Expr<'a>>>,
367) -> &'a Located<Expr<'a>> {
368 if args.is_empty() {
369 func
370 } else {
371 let last_arg = args.last().unwrap();
372 let region = Region::span_across(&func.region, &last_arg.region);
373 let args_slice = parser.alloc_slice_copy(&args);
374 parser.alloc(Located::at(
375 region,
376 Expr::Call {
377 function: func,
378 arguments: args_slice,
379 },
380 ))
381 }
382}
383
384enum ExprEndState<'a> {
386 MoreArgs(Vec<&'a Located<Expr<'a>>>, Position),
388 MoreOps(&'a Located<&'a str>, &'a Located<Expr<'a>>, Position),
390 Final(&'a Located<&'a str>, &'a Located<Expr<'a>>, Position),
392 Done,
394}
395
396#[cfg(test)]
398macro_rules! assert_expr_snapshot {
399 ($code:expr) => {{
400 let bump = bumpalo::Bump::new();
401 let src = bump.alloc_str(indoc::indoc!($code));
402 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
403 let result = parser.term().expect("expected successful parse");
404 parser.chomp(|_, _, _| ()).expect("expected trailing space");
405 assert!(parser.is_eof(), "expression parser left trailing input");
406
407 insta::with_settings!({
408 description => format!("Code:\n\n{}", indoc::indoc!($code)),
409 omit_expression => true,
410 }, {
411 insta::assert_debug_snapshot!(result);
412 });
413 }};
414}
415
416#[cfg(test)]
418macro_rules! assert_expr_error_snapshot {
419 ($code:expr) => {{
420 let bump = bumpalo::Bump::new();
421 let src = bump.alloc_str(indoc::indoc!($code));
422 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
423 let result = parser.term().expect_err("expected parse error");
424
425 insta::with_settings!({
426 description => format!("Code:\n\n{}", indoc::indoc!($code)),
427 omit_expression => true,
428 }, {
429 insta::assert_debug_snapshot!(result);
430 });
431 }};
432}
433
434#[cfg(test)]
436macro_rules! assert_expression_snapshot {
437 ($code:expr) => {{
438 let bump = bumpalo::Bump::new();
439 let src = bump.alloc_str(indoc::indoc!($code));
440 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
441 let (result, _end) = parser.expression().expect("expected successful parse");
442 parser.chomp(|_, _, _| ()).expect("expected trailing space");
443 assert!(parser.is_eof(), "expression parser left trailing input");
444
445 insta::with_settings!({
446 description => format!("Code:\n\n{}", indoc::indoc!($code)),
447 omit_expression => true,
448 }, {
449 insta::assert_debug_snapshot!(result);
450 });
451 }};
452}
453
454#[cfg(test)]
456macro_rules! assert_expression_error_snapshot {
457 ($code:expr) => {{
458 let bump = bumpalo::Bump::new();
459 let src = bump.alloc_str(indoc::indoc!($code));
460 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
461 let result = parser.expression().expect_err("expected parse error");
462
463 insta::with_settings!({
464 description => format!("Code:\n\n{}", indoc::indoc!($code)),
465 omit_expression => true,
466 }, {
467 insta::assert_debug_snapshot!(result);
468 });
469 }};
470}
471
472#[cfg(test)]
476macro_rules! assert_indented_expr_snapshot {
477 ($code:expr) => {{
478 let bump = bumpalo::Bump::new();
479 let fragment = indoc::indoc!($code);
480 let indented = $crate::test_support::indent_fragment(fragment);
481 let src = bump.alloc_str(&indented);
482 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
483 parser
484 .chomp(|_, _, _| "space error")
485 .expect("expected leading indent");
486 let result = parser.term().expect("expected successful parse");
487 parser.chomp(|_, _, _| ()).expect("expected trailing space");
488 assert!(parser.is_eof(), "expression parser left trailing input");
489
490 insta::with_settings!({
491 description => format!("Code (indented inside a def):\n\n{}", indented),
492 omit_expression => true,
493 }, {
494 insta::assert_debug_snapshot!(result);
495 });
496 }};
497}
498
499#[cfg(test)]
501macro_rules! assert_indented_expression_snapshot {
502 ($code:expr) => {{
503 let bump = bumpalo::Bump::new();
504 let fragment = indoc::indoc!($code);
505 let indented = $crate::test_support::indent_fragment(fragment);
506 let src = bump.alloc_str(&indented);
507 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
508 parser
509 .chomp(|_, _, _| "space error")
510 .expect("expected leading indent");
511 let (result, _end) = parser.expression().expect("expected successful parse");
512 parser.chomp(|_, _, _| ()).expect("expected trailing space");
513 assert!(parser.is_eof(), "expression parser left trailing input");
514
515 insta::with_settings!({
516 description => format!("Code (indented inside a def):\n\n{}", indented),
517 omit_expression => true,
518 }, {
519 insta::assert_debug_snapshot!(result);
520 });
521 }};
522}
523
524#[cfg(test)]
525pub(crate) use assert_expr_error_snapshot;
526#[cfg(test)]
527pub(crate) use assert_expr_snapshot;
528#[cfg(test)]
529pub(crate) use assert_expression_error_snapshot;
530#[cfg(test)]
531pub(crate) use assert_expression_snapshot;
532#[cfg(test)]
533pub(crate) use assert_indented_expr_snapshot;
534#[cfg(test)]
535pub(crate) use assert_indented_expression_snapshot;
536
537#[cfg(test)]
538mod tests {
539 #[test]
540 fn call_with_bytes_argument() {
541 assert_expression_snapshot!("f #\"01\" x");
542 }
543
544 #[test]
545 fn error_fat_arrow() {
546 assert_expression_error_snapshot!("a => b");
547 }
548
549 #[test]
550 fn error_left_arrow() {
551 assert_expression_error_snapshot!("a <- b");
552 }
553
554 #[test]
555 fn negate_var() {
556 assert_expression_snapshot!("-x");
557 }
558
559 #[test]
560 fn negate_number() {
561 assert_expression_snapshot!("-42");
562 }
563
564 #[test]
565 fn negate_parens() {
566 assert_expression_snapshot!("-(a)");
567 }
568
569 #[test]
570 fn expr_simple_var() {
571 assert_expression_snapshot!("foo");
572 }
573
574 #[test]
575 fn expr_simple_number() {
576 assert_expression_snapshot!("123");
577 }
578
579 #[test]
580 fn application_single() {
581 assert_expression_snapshot!("f x");
582 }
583
584 #[test]
585 fn application_multiple() {
586 assert_expression_snapshot!("f x y z");
587 }
588
589 #[test]
590 fn application_nested() {
591 assert_expression_snapshot!("f (g x)");
592 }
593
594 #[test]
595 fn application_with_record() {
596 assert_expression_snapshot!("f { x = 1 }");
597 }
598
599 #[test]
601 fn binop_simple_add() {
602 assert_expression_snapshot!("a + b");
603 }
604
605 #[test]
606 fn binop_simple_subtract() {
607 assert_expression_snapshot!("a - b");
608 }
609
610 #[test]
611 fn binop_simple_multiply() {
612 assert_expression_snapshot!("a * b");
613 }
614
615 #[test]
616 fn binop_simple_divide() {
617 assert_expression_snapshot!("a / b");
618 }
619
620 #[test]
621 fn binop_chained() {
622 assert_expression_snapshot!("a + b + c");
623 }
624
625 #[test]
626 fn binop_mixed() {
627 assert_expression_snapshot!("a + b * c");
628 }
629
630 #[test]
631 fn binop_with_parens() {
632 assert_expression_snapshot!("(a + b) * c");
633 }
634
635 #[test]
636 fn binop_pipe_right() {
637 assert_expression_snapshot!("a |> b |> c");
638 }
639
640 #[test]
641 fn binop_pipe_left() {
642 assert_expression_snapshot!("c <| b <| a");
643 }
644
645 #[test]
646 fn binop_comparison() {
647 assert_expression_snapshot!("a == b");
648 }
649
650 #[test]
651 fn binop_less_than() {
652 assert_expression_snapshot!("a < b");
653 }
654
655 #[test]
656 fn binop_greater_than() {
657 assert_expression_snapshot!("a > b");
658 }
659
660 #[test]
661 fn binop_append() {
662 assert_expression_snapshot!("a ++ b");
663 }
664
665 #[test]
666 fn binop_cons() {
667 assert_expression_snapshot!("a :: b");
668 }
669
670 #[test]
671 fn binop_logical_and() {
672 assert_expression_snapshot!("a && b");
673 }
674
675 #[test]
676 fn binop_logical_or() {
677 assert_expression_snapshot!("a || b");
678 }
679
680 #[test]
681 fn binop_less_than_or_equal() {
682 assert_expression_snapshot!("a <= b");
683 }
684
685 #[test]
686 fn binop_greater_than_or_equal() {
687 assert_expression_snapshot!("a >= b");
688 }
689
690 #[test]
691 fn binop_not_equal() {
692 assert_expression_snapshot!("a /= b");
693 }
694
695 #[test]
696 fn binop_compose_right() {
697 assert_expression_snapshot!("f >> g");
698 }
699
700 #[test]
701 fn binop_compose_left() {
702 assert_expression_snapshot!("f << g");
703 }
704
705 #[test]
706 fn binop_power() {
707 assert_expression_snapshot!("a ^ b");
708 }
709
710 #[test]
711 fn binop_with_function_application() {
712 assert_expression_snapshot!("f x + g y");
713 }
714
715 #[test]
716 fn binop_with_negation() {
717 assert_expression_snapshot!("a + -b");
718 }
719
720 #[test]
721 fn binop_negative_first() {
722 assert_expression_snapshot!("-a + b");
723 }
724
725 #[test]
726 fn binop_with_let() {
727 assert_expression_snapshot!("a + let x = 1 in x");
728 }
729
730 #[test]
731 fn binop_with_if() {
732 assert_expression_snapshot!("a + if b then c else d");
733 }
734
735 #[test]
736 fn binop_with_case() {
737 assert_expression_snapshot!(
738 r#"
739 a + case x of
740 1 -> y
741 _ -> z
742 "#
743 );
744 }
745
746 #[test]
747 fn binop_with_lambda() {
748 assert_expression_snapshot!("a + \\x -> x");
749 }
750
751 #[test]
753 fn op_section_plus() {
754 assert_expression_snapshot!("(+)");
755 }
756
757 #[test]
758 fn op_section_minus() {
759 assert_expression_snapshot!("(-)");
760 }
761
762 #[test]
763 fn op_section_multiply() {
764 assert_expression_snapshot!("(*)");
765 }
766
767 #[test]
768 fn op_section_append() {
769 assert_expression_snapshot!("(++)");
770 }
771
772 #[test]
773 fn op_section_pipe_right() {
774 assert_expression_snapshot!("(|>)");
775 }
776
777 #[test]
778 fn op_section_cons() {
779 assert_expression_snapshot!("(::)");
780 }
781
782 #[test]
784 fn application_with_negative_arg() {
785 assert_expression_snapshot!("f -x");
787 }
788
789 #[test]
790 fn negation_in_parens() {
791 assert_expression_snapshot!("(-42)");
792 }
793
794 #[test]
795 fn negation_in_tuple() {
796 assert_expression_snapshot!("(-a, b)");
797 }
798}