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 self.with_depth(error::Expr::Space, Self::expression_inner)
49 }
50
51 fn expression_inner(&mut self) -> Result<(&'a Located<Expr<'a>>, Position), error::Expr<'a>> {
52 let start = self.get_position();
53
54 self.one_of(
55 error::Expr::Start,
56 vec![
57 Box::new(|p: &mut Parser<'a>| p.let_(start)),
59 Box::new(|p: &mut Parser<'a>| p.case_(start)),
61 Box::new(|p: &mut Parser<'a>| p.if_(start)),
63 Box::new(|p: &mut Parser<'a>| p.lambda(start)),
65 Box::new(|p| p.assert_(start)),
66 Box::new(|p| p.fail(start)),
67 Box::new(|p| p.todo(start)),
68 Box::new(|p| p.trace(start)),
69 Box::new(|p| p.comptime(start)),
70 Box::new(|p| p.do_(start)),
71 Box::new(|p| {
73 let expr = p.possibly_negative_term(start)?;
74 let end = p.get_position();
75 p.chomp(error::Expr::Space)?;
76 p.chomp_expr_end(start, expr, vec![], end)
77 }),
78 ],
79 )
80 }
81
82 pub(crate) fn chomp_expr_end(
100 &mut self,
101 start: Position,
102 expr: &'a Located<Expr<'a>>,
103 args: Vec<&'a Located<Expr<'a>>>,
104 end: Position,
105 ) -> Result<(&'a Located<Expr<'a>>, Position), error::Expr<'a>> {
106 let mut ops: BumpVec<'a, &'a BinOpOperand<'a>> = BumpVec::new_in(self.bump);
108 let mut current_expr = expr;
109 let mut current_args = args;
110 let mut current_end = end;
111
112 loop {
113 let result = if self.is_trailing_section_operator() {
114 ExprEndState::Done
115 } else {
116 self.one_of_with_fallback(
117 vec![
118 Box::new(|p: &mut Parser<'a>| {
120 let (row, col) = p.position();
121 p.check_indent(row, col, error::Expr::Start)?;
122 let arg = p.term()?;
123 let new_end = p.get_position();
124 p.chomp(error::Expr::Space)?;
125
126 Ok(ExprEndState::MoreArgs(arg, new_end))
127 }),
128 Box::new(|p: &mut Parser<'a>| {
130 let (row, col) = p.position();
131 p.check_indent(row, col, error::Expr::Start)?;
132
133 let op_start = p.get_position();
135
136 let op = p.add_location_operator(
137 error::Expr::Start,
138 error::Expr::OperatorReserved,
139 )?;
140 let op_name = op.value;
141 let op_end = p.get_position();
142
143 p.chomp_and_check_indent(error::Expr::Space, |row, col| {
144 error::Expr::IndentOperatorRight(op_name, row, col)
145 })?;
146
147 let new_start = p.get_position();
148
149 if op_name == "-"
152 && current_end != op_start && op_end == new_start
154 {
156 let negated_expr = p.term()?;
158 let neg_end = p.get_position();
159 let neg_region = Region::new(op_start, neg_end);
160 let neg =
161 p.alloc(Located::at(neg_region, Expr::Negate(negated_expr)));
162 p.chomp(error::Expr::Space)?;
163
164 Ok(ExprEndState::MoreArgs(neg, neg_end))
165 } else {
166 p.one_of(
168 |row, col| error::Expr::OperatorRight(op_name, row, col),
169 vec![
170 Box::new(|p: &mut Parser<'a>| {
172 let new_expr = p.possibly_negative_term(new_start)?;
173 let new_end = p.get_position();
174 p.chomp(error::Expr::Space)?;
175
176 Ok(ExprEndState::MoreOps(op, new_expr, new_end))
177 }),
178 Box::new(|p: &mut Parser<'a>| {
180 let (final_expr, final_end) = p.one_of(
181 |row, col| {
182 error::Expr::OperatorRight(op_name, row, col)
183 },
184 vec![
185 Box::new(|p: &mut Parser<'a>| {
186 p.let_(new_start)
187 }),
188 Box::new(|p| p.case_(new_start)),
189 Box::new(|p| p.if_(new_start)),
190 Box::new(|p| p.lambda(new_start)),
191 Box::new(|p| p.assert_(new_start)),
192 Box::new(|p| p.fail(new_start)),
193 Box::new(|p| p.todo(new_start)),
194 Box::new(|p| p.trace(new_start)),
195 Box::new(|p| p.comptime(new_start)),
196 Box::new(|p| p.do_(new_start)),
197 ],
198 )?;
199
200 Ok(ExprEndState::Final(op, final_expr, final_end))
201 }),
202 ],
203 )
204 }
205 }),
206 ],
207 ExprEndState::Done,
208 )?
209 };
210
211 match result {
212 ExprEndState::MoreArgs(arg, new_end) => {
213 current_args.push(arg);
214 current_end = new_end;
215 }
216 ExprEndState::MoreOps(op, new_expr, new_end) => {
217 let call_expr =
219 to_call(self, start, current_expr, std::mem::take(&mut current_args));
220 let operand = self.alloc(BinOpOperand {
221 expr: call_expr,
222 op,
223 });
224 ops.push(operand);
225 current_expr = new_expr;
226 current_end = new_end;
227 }
228 ExprEndState::Final(op, final_expr, final_end) => {
229 let call_expr = to_call(self, start, current_expr, current_args);
231 let operand = self.alloc(BinOpOperand {
232 expr: call_expr,
233 op,
234 });
235 ops.push(operand);
236
237 let ops_slice = ops.into_bump_slice();
238 let binops = Expr::BinOps {
239 operands: ops_slice,
240 last: final_expr,
241 };
242 let result = self.alloc(Located::at(Region::new(start, final_end), binops));
243 return Ok((result, final_end));
244 }
245 ExprEndState::Done => {
246 let final_call = to_call(self, start, current_expr, current_args);
248
249 if ops.is_empty() {
250 return Ok((final_call, current_end));
251 } else {
252 let ops_slice = ops.into_bump_slice();
253 let binops = Expr::BinOps {
254 operands: ops_slice,
255 last: final_call,
256 };
257 let result =
258 self.alloc(Located::at(Region::new(start, current_end), binops));
259 return Ok((result, current_end));
260 }
261 }
262 }
263 }
264 }
265
266 fn is_trailing_section_operator(&mut self) -> bool {
268 let saved = self.save_state();
269 let result = self
270 .operator(|_, _| (), |_, _, _| ())
271 .and_then(|_| self.chomp(|_, _, _| ()))
272 .is_ok()
273 && self.peek() == Some(b')');
274 self.restore_state(saved);
275 result
276 }
277
278 fn possibly_negative_term(
291 &mut self,
292 start: Position,
293 ) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
294 self.one_of(
295 error::Expr::Start,
296 vec![
297 Box::new(|p: &mut Parser<'a>| {
298 p.word1(b'-', error::Expr::Start)?;
299 let expr = p.term()?;
300 Ok(p.add_end(start, Expr::Negate(expr)))
301 }),
302 Box::new(|p| p.term()),
303 ],
304 )
305 }
306
307 pub fn term(&mut self) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
321 self.with_depth(error::Expr::Space, Self::term_inner)
322 }
323
324 fn term_inner(&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(&'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);
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)]
418#[cfg(test)]
420macro_rules! assert_expression_snapshot {
421 ($code:expr) => {{
422 let bump = bumpalo::Bump::new();
423 let src = bump.alloc_str(indoc::indoc!($code));
424 let mut parser = $crate::Parser::new(&bump, src);
425 let (result, _end) = parser.expression().expect("expected successful parse");
426 parser.chomp(|_, _, _| ()).expect("expected trailing space");
427 assert!(parser.is_eof(), "expression parser left trailing input");
428
429 insta::with_settings!({
430 description => format!("Code:\n\n{}", indoc::indoc!($code)),
431 omit_expression => true,
432 }, {
433 insta::assert_debug_snapshot!(result);
434 });
435 }};
436}
437
438#[cfg(test)]
440#[cfg(test)]
444macro_rules! assert_indented_expr_snapshot {
445 ($code:expr) => {{
446 let bump = bumpalo::Bump::new();
447 let fragment = indoc::indoc!($code);
448 let indented = $crate::test_support::indent_fragment(fragment);
449 let src = bump.alloc_str(&indented);
450 let mut parser = $crate::Parser::new(&bump, src);
451 parser
452 .chomp(|_, _, _| "space error")
453 .expect("expected leading indent");
454 let result = parser.term().expect("expected successful parse");
455 parser.chomp(|_, _, _| ()).expect("expected trailing space");
456 assert!(parser.is_eof(), "expression parser left trailing input");
457
458 insta::with_settings!({
459 description => format!("Code (indented inside a def):\n\n{}", indented),
460 omit_expression => true,
461 }, {
462 insta::assert_debug_snapshot!(result);
463 });
464 }};
465}
466
467#[cfg(test)]
469macro_rules! assert_indented_expression_snapshot {
470 ($code:expr) => {{
471 let bump = bumpalo::Bump::new();
472 let fragment = indoc::indoc!($code);
473 let indented = $crate::test_support::indent_fragment(fragment);
474 let src = bump.alloc_str(&indented);
475 let mut parser = $crate::Parser::new(&bump, src);
476 parser
477 .chomp(|_, _, _| "space error")
478 .expect("expected leading indent");
479 let (result, _end) = parser.expression().expect("expected successful parse");
480 parser.chomp(|_, _, _| ()).expect("expected trailing space");
481 assert!(parser.is_eof(), "expression parser left trailing input");
482
483 insta::with_settings!({
484 description => format!("Code (indented inside a def):\n\n{}", indented),
485 omit_expression => true,
486 }, {
487 insta::assert_debug_snapshot!(result);
488 });
489 }};
490}
491
492#[cfg(test)]
493#[cfg(test)]
494pub(crate) use assert_expr_snapshot;
495#[cfg(test)]
496#[cfg(test)]
497pub(crate) use assert_expression_snapshot;
498#[cfg(test)]
499pub(crate) use assert_indented_expr_snapshot;
500#[cfg(test)]
501pub(crate) use assert_indented_expression_snapshot;
502
503#[cfg(test)]
504mod tests {
505 #[test]
506 fn operator_chain_arena_growth_is_linear() {
507 let mut previous = None;
508 for count in [1000, 2000, 4000] {
509 let source = vec!["x"; count].join(" + ");
510 let bump = bumpalo::Bump::new();
511 let mut parser = crate::Parser::new(&bump, &source);
512 let (expression, _) = parser.expression().expect("operator chain");
513 assert!(parser.is_eof());
514 let nash_source::Expr::BinOps { operands, .. } = expression.value else {
515 panic!("expected binary operators");
516 };
517 assert_eq!(operands.len(), count - 1);
518 let allocated = bump.allocated_bytes();
519 eprintln!("{count} operands: {allocated} arena bytes");
520 if let Some(previous) = previous {
521 assert!(allocated <= previous * 3, "superlinear arena growth");
523 }
524 previous = Some(allocated);
525 }
526 }
527
528 #[test]
529 fn call_with_bytes_argument() {
530 assert_expression_snapshot!("f #\"01\" x");
531 }
532
533 #[test]
534 fn negate_var() {
535 assert_expression_snapshot!("-x");
536 }
537
538 #[test]
539 fn negate_number() {
540 assert_expression_snapshot!("-42");
541 }
542
543 #[test]
544 fn negate_parens() {
545 assert_expression_snapshot!("-(a)");
546 }
547
548 #[test]
549 fn expr_simple_var() {
550 assert_expression_snapshot!("foo");
551 }
552
553 #[test]
554 fn expr_simple_number() {
555 assert_expression_snapshot!("123");
556 }
557
558 #[test]
559 fn application_single() {
560 assert_expression_snapshot!("f x");
561 }
562
563 #[test]
564 fn application_multiple() {
565 assert_expression_snapshot!("f x y z");
566 }
567
568 #[test]
569 fn application_nested() {
570 assert_expression_snapshot!("f (g x)");
571 }
572
573 #[test]
574 fn application_with_record() {
575 assert_expression_snapshot!("f { x = 1 }");
576 }
577
578 #[test]
580 fn binop_simple_add() {
581 assert_expression_snapshot!("a + b");
582 }
583
584 #[test]
585 fn binop_simple_subtract() {
586 assert_expression_snapshot!("a - b");
587 }
588
589 #[test]
590 fn binop_simple_multiply() {
591 assert_expression_snapshot!("a * b");
592 }
593
594 #[test]
595 fn binop_simple_divide() {
596 assert_expression_snapshot!("a / b");
597 }
598
599 #[test]
600 fn binop_chained() {
601 assert_expression_snapshot!("a + b + c");
602 }
603
604 #[test]
605 fn binop_mixed() {
606 assert_expression_snapshot!("a + b * c");
607 }
608
609 #[test]
610 fn binop_with_parens() {
611 assert_expression_snapshot!("(a + b) * c");
612 }
613
614 #[test]
615 fn binop_pipe_right() {
616 assert_expression_snapshot!("a |> b |> c");
617 }
618
619 #[test]
620 fn binop_functor_map() {
621 assert_expression_snapshot!("f <$> xs");
622 }
623
624 #[test]
625 fn binop_pipe_left() {
626 assert_expression_snapshot!("c <| b <| a");
627 }
628
629 #[test]
630 fn binop_comparison() {
631 assert_expression_snapshot!("a == b");
632 }
633
634 #[test]
635 fn binop_less_than() {
636 assert_expression_snapshot!("a < b");
637 }
638
639 #[test]
640 fn binop_greater_than() {
641 assert_expression_snapshot!("a > b");
642 }
643
644 #[test]
645 fn binop_append() {
646 assert_expression_snapshot!("a ++ b");
647 }
648
649 #[test]
650 fn binop_cons() {
651 assert_expression_snapshot!("a :: b");
652 }
653
654 #[test]
655 fn binop_logical_and() {
656 assert_expression_snapshot!("a && b");
657 }
658
659 #[test]
660 fn binop_logical_or() {
661 assert_expression_snapshot!("a || b");
662 }
663
664 #[test]
665 fn binop_less_than_or_equal() {
666 assert_expression_snapshot!("a <= b");
667 }
668
669 #[test]
670 fn binop_greater_than_or_equal() {
671 assert_expression_snapshot!("a >= b");
672 }
673
674 #[test]
675 fn binop_not_equal() {
676 assert_expression_snapshot!("a /= b");
677 }
678
679 #[test]
680 fn binop_compose_right() {
681 assert_expression_snapshot!("f >> g");
682 }
683
684 #[test]
685 fn binop_compose_left() {
686 assert_expression_snapshot!("f << g");
687 }
688
689 #[test]
690 fn binop_power() {
691 assert_expression_snapshot!("a ^ b");
692 }
693
694 #[test]
695 fn binop_with_function_application() {
696 assert_expression_snapshot!("f x + g y");
697 }
698
699 #[test]
700 fn binop_with_negation() {
701 assert_expression_snapshot!("a + -b");
702 }
703
704 #[test]
705 fn binop_negative_first() {
706 assert_expression_snapshot!("-a + b");
707 }
708
709 #[test]
710 fn binop_with_let() {
711 assert_expression_snapshot!("a + let x = 1 in x");
712 }
713
714 #[test]
715 fn binop_with_if() {
716 assert_expression_snapshot!("a + if b then c else d");
717 }
718
719 #[test]
720 fn binop_with_case() {
721 assert_expression_snapshot!(
722 r#"
723 a + case x of
724 1 -> y
725 _ -> z
726 "#
727 );
728 }
729
730 #[test]
731 fn binop_with_lambda() {
732 assert_expression_snapshot!("a + \\x -> x");
733 }
734
735 #[test]
737 fn op_section_plus() {
738 assert_expression_snapshot!("(+)");
739 }
740
741 #[test]
742 fn op_section_minus() {
743 assert_expression_snapshot!("(-)");
744 }
745
746 #[test]
747 fn op_section_multiply() {
748 assert_expression_snapshot!("(*)");
749 }
750
751 #[test]
752 fn op_section_append() {
753 assert_expression_snapshot!("(++)");
754 }
755
756 #[test]
757 fn op_section_pipe_right() {
758 assert_expression_snapshot!("(|>)");
759 }
760
761 #[test]
762 fn op_section_cons() {
763 assert_expression_snapshot!("(::)");
764 }
765
766 #[test]
768 fn application_with_negative_arg() {
769 assert_expression_snapshot!("f -x");
771 }
772
773 #[test]
774 fn negation_in_parens() {
775 assert_expression_snapshot!("(-42)");
776 }
777
778 #[test]
779 fn negation_in_tuple() {
780 assert_expression_snapshot!("(-a, b)");
781 }
782}