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 case;
14mod if_;
15mod lambda;
16mod let_;
17mod list;
18mod number;
19mod record;
20mod string;
21mod tuple;
22mod variable;
23
24impl<'a> Parser<'a> {
25 pub fn expression(&mut self) -> Result<(&'a Located<Expr<'a>>, Position), error::Expr<'a>> {
44 let start = self.get_position();
45
46 self.one_of(
47 error::Expr::Start,
48 vec![
49 Box::new(|p: &mut Parser<'a>| p.let_(start)),
51 Box::new(|p: &mut Parser<'a>| p.case_(start)),
53 Box::new(|p: &mut Parser<'a>| p.if_(start)),
55 Box::new(|p: &mut Parser<'a>| p.lambda(start)),
57 Box::new(|p| {
59 let expr = p.possibly_negative_term(start)?;
60 let end = p.get_position();
61 p.chomp(error::Expr::Space)?;
62 p.chomp_expr_end(start, expr, vec![], end)
63 }),
64 ],
65 )
66 }
67
68 pub(crate) fn chomp_expr_end(
86 &mut self,
87 start: Position,
88 expr: &'a Located<Expr<'a>>,
89 args: Vec<&'a Located<Expr<'a>>>,
90 end: Position,
91 ) -> Result<(&'a Located<Expr<'a>>, Position), error::Expr<'a>> {
92 let mut ops: BumpVec<'a, &'a BinOpOperand<'a>> = BumpVec::new_in(self.bump);
94 let mut current_expr = expr;
95 let mut current_args = args;
96 let mut current_end = end;
97
98 loop {
99 let state_for_fallback = (ops.clone(), current_expr, current_args.clone(), current_end);
100
101 let result = self.one_of_with_fallback(
102 vec![
103 Box::new(|p: &mut Parser<'a>| {
105 let (row, col) = p.position();
106 p.check_indent(row, col, error::Expr::Start)?;
107 let arg = p.term()?;
108 let new_end = p.get_position();
109 p.chomp(error::Expr::Space)?;
110
111 let mut new_args = current_args.clone();
112 new_args.push(arg);
113
114 Ok(ExprEndState::MoreArgs(new_args, new_end))
115 }),
116 Box::new(|p: &mut Parser<'a>| {
118 let (row, col) = p.position();
119 p.check_indent(row, col, error::Expr::Start)?;
120
121 let op_start = p.get_position();
123
124 let op = p.add_location_operator(
125 error::Expr::Start,
126 error::Expr::OperatorReserved,
127 )?;
128 let op_name = op.value;
129 let op_end = p.get_position();
130
131 p.chomp_and_check_indent(error::Expr::Space, |row, col| {
132 error::Expr::IndentOperatorRight(op_name, row, col)
133 })?;
134
135 let new_start = p.get_position();
136
137 if op_name == "-"
140 && current_end != op_start && op_end == new_start
142 {
144 let negated_expr = p.term()?;
146 let neg_end = p.get_position();
147 let neg_region = Region::new(op_start, neg_end);
148 let neg = p.alloc(Located::at(neg_region, Expr::Negate(negated_expr)));
149 p.chomp(error::Expr::Space)?;
150
151 let mut new_args = current_args.clone();
152 new_args.push(neg);
153
154 Ok(ExprEndState::MoreArgs(new_args, neg_end))
155 } else {
156 p.one_of(
158 |row, col| error::Expr::OperatorRight(op_name, row, col),
159 vec![
160 Box::new(|p: &mut Parser<'a>| {
162 let new_expr = p.possibly_negative_term(new_start)?;
163 let new_end = p.get_position();
164 p.chomp(error::Expr::Space)?;
165
166 Ok(ExprEndState::MoreOps(op, new_expr, new_end))
167 }),
168 Box::new(|p: &mut Parser<'a>| {
170 let (final_expr, final_end) = p.one_of(
171 |row, col| {
172 error::Expr::OperatorRight(op_name, row, col)
173 },
174 vec![
175 Box::new(|p: &mut Parser<'a>| p.let_(new_start)),
176 Box::new(|p| p.case_(new_start)),
177 Box::new(|p| p.if_(new_start)),
178 Box::new(|p| p.lambda(new_start)),
179 ],
180 )?;
181
182 Ok(ExprEndState::Final(op, final_expr, final_end))
183 }),
184 ],
185 )
186 }
187 }),
188 ],
189 ExprEndState::Done,
190 )?;
191
192 match result {
193 ExprEndState::MoreArgs(new_args, new_end) => {
194 current_args = new_args;
195 current_end = new_end;
196 }
197 ExprEndState::MoreOps(op, new_expr, new_end) => {
198 let call_expr = to_call(self, start, current_expr, current_args.clone());
200 let operand = self.alloc(BinOpOperand {
201 expr: call_expr,
202 op,
203 });
204 ops.push(operand);
205 current_expr = new_expr;
206 current_args = Vec::new();
207 current_end = new_end;
208 }
209 ExprEndState::Final(op, final_expr, final_end) => {
210 let call_expr = to_call(self, start, current_expr, current_args);
212 let operand = self.alloc(BinOpOperand {
213 expr: call_expr,
214 op,
215 });
216 ops.push(operand);
217
218 let ops_slice = ops.into_bump_slice();
219 let binops = Expr::BinOps {
220 operands: ops_slice,
221 last: final_expr,
222 };
223 let result = self.alloc(Located::at(Region::new(start, final_end), binops));
224 return Ok((result, final_end));
225 }
226 ExprEndState::Done => {
227 let (saved_ops, saved_expr, saved_args, saved_end) = state_for_fallback;
229 let final_call = to_call(self, start, saved_expr, saved_args);
230
231 if saved_ops.is_empty() {
232 return Ok((final_call, saved_end));
233 } else {
234 let ops_slice = saved_ops.into_bump_slice();
235 let binops = Expr::BinOps {
236 operands: ops_slice,
237 last: final_call,
238 };
239 let result = self.alloc(Located::at(Region::new(start, saved_end), binops));
240 return Ok((result, saved_end));
241 }
242 }
243 }
244 }
245 }
246
247 fn possibly_negative_term(
260 &mut self,
261 start: Position,
262 ) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
263 self.one_of(
264 error::Expr::Start,
265 vec![
266 Box::new(|p: &mut Parser<'a>| {
267 p.word1(b'-', error::Expr::Start)?;
268 let expr = p.term()?;
269 Ok(p.add_end(start, Expr::Negate(expr)))
270 }),
271 Box::new(|p| p.term()),
272 ],
273 )
274 }
275
276 pub fn term(&mut self) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
290 let start = self.get_position();
291
292 self.one_of(
293 error::Expr::Start,
294 vec![
295 Box::new(|p: &mut Parser<'a>| {
296 let expr = p.variable(start)?;
297 p.accessible(start, expr)
298 }),
299 Box::new(|p| p.string(start)),
300 Box::new(|p| p.number(start)),
301 Box::new(|p| p.list(start)),
302 Box::new(|p| {
303 let expr = p.record(start)?;
304 p.accessible(start, expr)
305 }),
306 Box::new(|p| {
307 let expr = p.tuple(start)?;
308 p.accessible(start, expr)
309 }),
310 Box::new(|p| p.accessor(start)),
311 ],
312 )
313 }
314}
315
316fn to_call<'a>(
326 parser: &Parser<'a>,
327 _start: Position,
328 func: &'a Located<Expr<'a>>,
329 args: Vec<&'a Located<Expr<'a>>>,
330) -> &'a Located<Expr<'a>> {
331 if args.is_empty() {
332 func
333 } else {
334 let last_arg = args.last().unwrap();
335 let region = Region::span_across(&func.region, &last_arg.region);
336 let args_slice = parser.alloc_slice_copy(&args);
337 parser.alloc(Located::at(
338 region,
339 Expr::Call {
340 function: func,
341 arguments: args_slice,
342 },
343 ))
344 }
345}
346
347enum ExprEndState<'a> {
349 MoreArgs(Vec<&'a Located<Expr<'a>>>, Position),
351 MoreOps(&'a Located<&'a str>, &'a Located<Expr<'a>>, Position),
353 Final(&'a Located<&'a str>, &'a Located<Expr<'a>>, Position),
355 Done,
357}
358
359#[cfg(test)]
361macro_rules! assert_expr_snapshot {
362 ($code:expr) => {{
363 let bump = bumpalo::Bump::new();
364 let src = bump.alloc_str(indoc::indoc!($code));
365 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
366 let result = parser.term().expect("expected successful parse");
367
368 insta::with_settings!({
369 description => format!("Code:\n\n{}", indoc::indoc!($code)),
370 omit_expression => true,
371 }, {
372 insta::assert_debug_snapshot!(result);
373 });
374 }};
375}
376
377#[cfg(test)]
379macro_rules! assert_expr_error_snapshot {
380 ($code:expr) => {{
381 let bump = bumpalo::Bump::new();
382 let src = bump.alloc_str(indoc::indoc!($code));
383 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
384 let result = parser.term().expect_err("expected parse error");
385
386 insta::with_settings!({
387 description => format!("Code:\n\n{}", indoc::indoc!($code)),
388 omit_expression => true,
389 }, {
390 insta::assert_debug_snapshot!(result);
391 });
392 }};
393}
394
395#[cfg(test)]
397macro_rules! assert_expression_snapshot {
398 ($code:expr) => {{
399 let bump = bumpalo::Bump::new();
400 let src = bump.alloc_str(indoc::indoc!($code));
401 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
402 let (result, _end) = parser.expression().expect("expected successful parse");
403
404 insta::with_settings!({
405 description => format!("Code:\n\n{}", indoc::indoc!($code)),
406 omit_expression => true,
407 }, {
408 insta::assert_debug_snapshot!(result);
409 });
410 }};
411}
412
413#[cfg(test)]
417macro_rules! assert_indented_expr_snapshot {
418 ($code:expr) => {{
419 let bump = bumpalo::Bump::new();
420 let fragment = indoc::indoc!($code);
421 let indented = $crate::test_support::indent_fragment(fragment);
422 let src = bump.alloc_str(&indented);
423 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
424 parser
425 .chomp(|_, _, _| "space error")
426 .expect("expected leading indent");
427 let result = parser.term().expect("expected successful parse");
428
429 insta::with_settings!({
430 description => format!("Code (indented inside a def):\n\n{}", indented),
431 omit_expression => true,
432 }, {
433 insta::assert_debug_snapshot!(result);
434 });
435 }};
436}
437
438#[cfg(test)]
440macro_rules! assert_indented_expression_snapshot {
441 ($code:expr) => {{
442 let bump = bumpalo::Bump::new();
443 let fragment = indoc::indoc!($code);
444 let indented = $crate::test_support::indent_fragment(fragment);
445 let src = bump.alloc_str(&indented);
446 let mut parser = $crate::Parser::new(&bump, src.as_bytes());
447 parser
448 .chomp(|_, _, _| "space error")
449 .expect("expected leading indent");
450 let (result, _end) = parser.expression().expect("expected successful parse");
451
452 insta::with_settings!({
453 description => format!("Code (indented inside a def):\n\n{}", indented),
454 omit_expression => true,
455 }, {
456 insta::assert_debug_snapshot!(result);
457 });
458 }};
459}
460
461#[cfg(test)]
462pub(crate) use assert_expr_error_snapshot;
463#[cfg(test)]
464pub(crate) use assert_expr_snapshot;
465#[cfg(test)]
466pub(crate) use assert_expression_snapshot;
467#[cfg(test)]
468pub(crate) use assert_indented_expr_snapshot;
469#[cfg(test)]
470pub(crate) use assert_indented_expression_snapshot;
471
472#[cfg(test)]
473mod tests {
474 #[test]
475 fn negate_var() {
476 assert_expression_snapshot!("-x");
477 }
478
479 #[test]
480 fn negate_number() {
481 assert_expression_snapshot!("-42");
482 }
483
484 #[test]
485 fn negate_parens() {
486 assert_expression_snapshot!("-(a)");
487 }
488
489 #[test]
490 fn expr_simple_var() {
491 assert_expression_snapshot!("foo");
492 }
493
494 #[test]
495 fn expr_simple_number() {
496 assert_expression_snapshot!("123");
497 }
498
499 #[test]
500 fn application_single() {
501 assert_expression_snapshot!("f x");
502 }
503
504 #[test]
505 fn application_multiple() {
506 assert_expression_snapshot!("f x y z");
507 }
508
509 #[test]
510 fn application_nested() {
511 assert_expression_snapshot!("f (g x)");
512 }
513
514 #[test]
515 fn application_with_record() {
516 assert_expression_snapshot!("f { x = 1 }");
517 }
518
519 #[test]
521 fn binop_simple_add() {
522 assert_expression_snapshot!("a + b");
523 }
524
525 #[test]
526 fn binop_simple_subtract() {
527 assert_expression_snapshot!("a - b");
528 }
529
530 #[test]
531 fn binop_simple_multiply() {
532 assert_expression_snapshot!("a * b");
533 }
534
535 #[test]
536 fn binop_simple_divide() {
537 assert_expression_snapshot!("a / b");
538 }
539
540 #[test]
541 fn binop_chained() {
542 assert_expression_snapshot!("a + b + c");
543 }
544
545 #[test]
546 fn binop_mixed() {
547 assert_expression_snapshot!("a + b * c");
548 }
549
550 #[test]
551 fn binop_with_parens() {
552 assert_expression_snapshot!("(a + b) * c");
553 }
554
555 #[test]
556 fn binop_pipe_right() {
557 assert_expression_snapshot!("a |> b |> c");
558 }
559
560 #[test]
561 fn binop_pipe_left() {
562 assert_expression_snapshot!("c <| b <| a");
563 }
564
565 #[test]
566 fn binop_comparison() {
567 assert_expression_snapshot!("a == b");
568 }
569
570 #[test]
571 fn binop_less_than() {
572 assert_expression_snapshot!("a < b");
573 }
574
575 #[test]
576 fn binop_greater_than() {
577 assert_expression_snapshot!("a > b");
578 }
579
580 #[test]
581 fn binop_append() {
582 assert_expression_snapshot!("a ++ b");
583 }
584
585 #[test]
586 fn binop_cons() {
587 assert_expression_snapshot!("a :: b");
588 }
589
590 #[test]
591 fn binop_logical_and() {
592 assert_expression_snapshot!("a && b");
593 }
594
595 #[test]
596 fn binop_logical_or() {
597 assert_expression_snapshot!("a || b");
598 }
599
600 #[test]
601 fn binop_less_than_or_equal() {
602 assert_expression_snapshot!("a <= b");
603 }
604
605 #[test]
606 fn binop_greater_than_or_equal() {
607 assert_expression_snapshot!("a >= b");
608 }
609
610 #[test]
611 fn binop_not_equal() {
612 assert_expression_snapshot!("a /= b");
613 }
614
615 #[test]
616 fn binop_compose_right() {
617 assert_expression_snapshot!("f >> g");
618 }
619
620 #[test]
621 fn binop_compose_left() {
622 assert_expression_snapshot!("f << g");
623 }
624
625 #[test]
626 fn binop_power() {
627 assert_expression_snapshot!("a ^ b");
628 }
629
630 #[test]
631 fn binop_with_function_application() {
632 assert_expression_snapshot!("f x + g y");
633 }
634
635 #[test]
636 fn binop_with_negation() {
637 assert_expression_snapshot!("a + -b");
638 }
639
640 #[test]
641 fn binop_negative_first() {
642 assert_expression_snapshot!("-a + b");
643 }
644
645 #[test]
646 fn binop_with_let() {
647 assert_expression_snapshot!("a + let x = 1 in x");
648 }
649
650 #[test]
651 fn binop_with_if() {
652 assert_expression_snapshot!("a + if b then c else d");
653 }
654
655 #[test]
656 fn binop_with_case() {
657 assert_expression_snapshot!(
658 r#"
659 a + case x of
660 1 -> y
661 _ -> z
662 "#
663 );
664 }
665
666 #[test]
667 fn binop_with_lambda() {
668 assert_expression_snapshot!("a + \\x -> x");
669 }
670
671 #[test]
673 fn op_section_plus() {
674 assert_expression_snapshot!("(+)");
675 }
676
677 #[test]
678 fn op_section_minus() {
679 assert_expression_snapshot!("(-)");
680 }
681
682 #[test]
683 fn op_section_multiply() {
684 assert_expression_snapshot!("(*)");
685 }
686
687 #[test]
688 fn op_section_append() {
689 assert_expression_snapshot!("(++)");
690 }
691
692 #[test]
693 fn op_section_pipe_right() {
694 assert_expression_snapshot!("(|>)");
695 }
696
697 #[test]
698 fn op_section_cons() {
699 assert_expression_snapshot!("(::)");
700 }
701
702 #[test]
704 fn application_with_negative_arg() {
705 assert_expression_snapshot!("f -x");
707 }
708
709 #[test]
710 fn negation_in_parens() {
711 assert_expression_snapshot!("(-42)");
712 }
713
714 #[test]
715 fn negation_in_tuple() {
716 assert_expression_snapshot!("(-a, b)");
717 }
718}