1use winnow::combinator::{
45 alt, cut_err, delimited, fail, not, opt, peek, preceded, separated, seq, terminated,
46};
47use winnow::error::{StrContext, StrContextValue};
48use winnow::Parser;
49
50use winnow::ascii::dec_uint;
51
52use crate::ast::{BinaryOp, CExpr, Expr, ExprKind, Lit, UnaryOp};
53use crate::parser::lexer::{bool_literal, hex, identifier, reserved, ws, Input};
54use crate::parser::types::parse as parse_type;
55use crate::parser::PResult;
56
57pub fn call_expr(input: &mut Input<'_>) -> PResult<CExpr> {
65 let (mut call, span) = seq!(CExpr {
66 alias: terminated(identifier.map(str::to_string), '.'),
67 fn_name: identifier.map(str::to_string),
68 _: ('(', ws),
69 args: separated(0.., parse, (ws, ',', ws)),
70 _: (ws, ')'),
71 span: "".value(0..0usize),
72 })
73 .with_span()
74 .parse_next(input)?;
75 call.span = span;
76 Ok(call)
77}
78
79fn sizeof_expr(input: &mut Input<'_>) -> PResult<ExprKind> {
81 preceded(
82 (reserved("sizeof"), ws, '(', ws),
83 terminated(parse_type.map(ExprKind::Sizeof), (ws, ')')),
84 )
85 .parse_next(input)
86}
87
88fn literal(input: &mut Input<'_>) -> PResult<ExprKind> {
95 alt((
96 hex.map(|v| ExprKind::Lit(Lit::Hex(v))),
97 dec_uint::<_, u64, _>
98 .try_map(i64::try_from)
99 .map(|v| ExprKind::Lit(Lit::Int(v))),
100 bool_literal.map(|b| ExprKind::Lit(Lit::Bool(b))),
101 ))
102 .parse_next(input)
103}
104
105fn primary(input: &mut Input<'_>) -> PResult<Expr> {
112 alt((
113 delimited(('(', ws), pratt(0), (ws, ')')).map(|e| e.kind),
114 sizeof_expr,
115 call_expr.map(ExprKind::Call),
116 unary_expr,
117 literal,
118 identifier.map(|s| ExprKind::Var(s.to_string())),
119 ))
120 .with_span()
121 .map(|(kind, span)| Expr { kind, span })
122 .parse_next(input)
123}
124
125fn unary_expr(input: &mut Input<'_>) -> PResult<ExprKind> {
127 seq!(ExprKind::Unary {
128 op: alt((
129 '-'.value(UnaryOp::Neg),
130 '!'.value(UnaryOp::Not),
131 '~'.value(UnaryOp::BitNot),
132 )),
133 _: ws,
134 operand: primary.map(Box::new),
135 })
136 .parse_next(input)
137}
138
139fn binary_op(input: &mut Input<'_>) -> PResult<BinaryOp> {
144 alt((
145 alt((
146 "<<".value(BinaryOp::Shl),
147 ">>".value(BinaryOp::Shr),
148 "<=".value(BinaryOp::Le),
149 ">=".value(BinaryOp::Ge),
150 "==".value(BinaryOp::Eq),
151 "!=".value(BinaryOp::Ne),
152 "&&".value(BinaryOp::And),
153 "||".value(BinaryOp::Or),
154 )),
155 alt((
156 alt((
157 '+'.value(BinaryOp::Add),
158 terminated('-', not(peek('>'))).value(BinaryOp::Sub),
160 '*'.value(BinaryOp::Mul),
161 '/'.value(BinaryOp::Div),
162 '%'.value(BinaryOp::Mod),
163 )),
164 alt((
165 '<'.value(BinaryOp::Lt),
166 '>'.value(BinaryOp::Gt),
167 '&'.value(BinaryOp::BitAnd),
168 '|'.value(BinaryOp::BitOr),
169 '^'.value(BinaryOp::BitXor),
170 )),
171 )),
172 ))
173 .parse_next(input)
174}
175
176fn is_fieldable(e: &ExprKind) -> bool {
182 matches!(
183 e,
184 ExprKind::Var(_) | ExprKind::Call(_) | ExprKind::Field { .. }
185 )
186}
187
188fn field_base_error_msg(e: &ExprKind) -> &'static str {
193 match e {
194 ExprKind::Lit(_) => "field access requires a variable or call on the left, found a literal",
195 ExprKind::Sizeof(_) => {
196 "field access requires a variable or call on the left, found `sizeof(...)`"
197 }
198 ExprKind::Unary { .. } => {
199 "field access requires a variable or call on the left, found a unary expression"
200 }
201 ExprKind::Binary { .. } => {
202 "field access requires a variable or call on the left, found a binary expression"
203 }
204 ExprKind::Cast { .. } => {
205 "field access requires a variable or call on the left, found a cast"
206 }
207 ExprKind::Var(_) | ExprKind::Call(_) | ExprKind::Field { .. } => {
208 unreachable!("is_fieldable bases never reach field_base_error_msg")
209 }
210 }
211}
212
213fn pratt<'i>(min_prec: u8) -> impl FnMut(&mut Input<'i>) -> PResult<Expr> + 'i {
218 move |input: &mut Input<'i>| {
219 let mut lhs = primary.parse_next(input)?;
220
221 loop {
222 let pre_ws = *input;
223 let _ = ws.parse_next(input);
224
225 if let Some((field, field_span)) =
227 opt(preceded(('.', ws), identifier).with_span()).parse_next(input)?
228 {
229 if !is_fieldable(&lhs.kind) {
230 return cut_err(fail::<_, Expr, _>)
231 .context(StrContext::Label("field access"))
232 .context(StrContext::Expected(StrContextValue::Description(
233 field_base_error_msg(&lhs.kind),
234 )))
235 .parse_next(input);
236 }
237 let start = lhs.span.start;
238 lhs = Expr {
239 kind: ExprKind::Field {
240 expr: Box::new(lhs),
241 field: field.to_string(),
242 },
243 span: start..field_span.end,
244 };
245 continue;
246 }
247
248 if let Some((ty, ty_span)) =
251 opt(preceded((reserved("as"), ws), parse_type).with_span()).parse_next(input)?
252 {
253 let start = lhs.span.start;
254 lhs = Expr {
255 kind: ExprKind::Cast {
256 expr: Box::new(lhs),
257 ty,
258 },
259 span: start..ty_span.end,
260 };
261 continue;
262 }
263
264 let Some(op) =
266 opt(binary_op.verify(|op: &BinaryOp| op.prec() >= min_prec)).parse_next(input)?
267 else {
268 *input = pre_ws;
269 break;
270 };
271
272 let _ = ws.parse_next(input);
273 let rhs = pratt(op.prec() + 1).parse_next(input)?;
274
275 let span = lhs.span.start..rhs.span.end;
276 lhs = Expr {
277 kind: ExprKind::Binary {
278 op,
279 lhs: Box::new(lhs),
280 rhs: Box::new(rhs),
281 },
282 span,
283 };
284 }
285
286 Ok(lhs)
287 }
288}
289
290pub fn parse(input: &mut Input<'_>) -> PResult<Expr> {
295 pratt(0).parse_next(input)
296}
297
298#[cfg(test)]
303mod tests {
304 use super::*;
305 use crate::ast::{PrimitiveType, Type};
306 use winnow::stream::{LocatingSlice, Location};
307
308 #[test]
309 fn test_grouping_parens() {
310 let e = parse_expr("(a + b) * c");
312 let ExprKind::Binary {
313 op: BinaryOp::Mul,
314 lhs,
315 ..
316 } = e.kind
317 else {
318 panic!("expected Mul at top")
319 };
320 assert!(matches!(
321 lhs.kind,
322 ExprKind::Binary {
323 op: BinaryOp::Add,
324 ..
325 }
326 ));
327
328 let e = parse_expr("(eir & (1 << 25)) != 0");
330 assert!(matches!(
331 e.kind,
332 ExprKind::Binary {
333 op: BinaryOp::Ne,
334 ..
335 }
336 ));
337
338 let e = parse_expr("((x))");
340 assert!(matches!(e.kind, ExprKind::Var(ref n) if n == "x"));
341 }
342
343 #[test]
344 fn test_unclosed_paren_rejected() {
345 let mut remaining = LocatingSlice::new("(a + b");
346 assert!(parse(&mut remaining).is_err());
347 }
348
349 fn parse_expr(src: &str) -> Expr {
350 let mut remaining = LocatingSlice::new(src);
351 parse(&mut remaining).expect("parse failed")
352 }
353
354 #[test]
357 fn test_int_literal_decimal() {
358 assert!(matches!(parse_expr("42").kind, ExprKind::Lit(Lit::Int(42))));
359 }
360
361 #[test]
362 fn test_int_literal_zero() {
363 assert!(matches!(parse_expr("0").kind, ExprKind::Lit(Lit::Int(0))));
364 }
365
366 #[test]
367 fn test_hex_literal() {
368 assert!(matches!(
369 parse_expr("0xFF").kind,
370 ExprKind::Lit(Lit::Hex(255))
371 ));
372 }
373
374 #[test]
375 fn test_hex_literal_with_underscores() {
376 assert!(matches!(
377 parse_expr("0x3_000_000").kind,
378 ExprKind::Lit(Lit::Hex(0x3_000_000))
379 ));
380 }
381
382 #[test]
383 fn test_bool_literal_true() {
384 assert!(matches!(
385 parse_expr("true").kind,
386 ExprKind::Lit(Lit::Bool(true))
387 ));
388 }
389
390 #[test]
391 fn test_bool_literal_false() {
392 assert!(matches!(
393 parse_expr("false").kind,
394 ExprKind::Lit(Lit::Bool(false))
395 ));
396 }
397
398 #[test]
401 fn test_var() {
402 assert!(matches!(parse_expr("my_var").kind, ExprKind::Var(ref n) if n == "my_var"));
403 }
404
405 #[test]
408 fn test_sizeof_int() {
409 assert!(matches!(
410 parse_expr("sizeof(int)").kind,
411 ExprKind::Sizeof(Type::Primitive(PrimitiveType::Int))
412 ));
413 }
414
415 #[test]
416 fn test_sizeof_uint32() {
417 assert!(matches!(
418 parse_expr("sizeof(uint32)").kind,
419 ExprKind::Sizeof(Type::Primitive(PrimitiveType::UInt32))
420 ));
421 }
422
423 #[test]
426 fn test_unary_neg() {
427 let e = parse_expr("-x");
428 assert!(matches!(
429 e.kind,
430 ExprKind::Unary {
431 op: UnaryOp::Neg,
432 ..
433 }
434 ));
435 }
436
437 #[test]
438 fn test_unary_not() {
439 let e = parse_expr("!flag");
440 assert!(matches!(
441 e.kind,
442 ExprKind::Unary {
443 op: UnaryOp::Not,
444 ..
445 }
446 ));
447 }
448
449 #[test]
450 fn test_unary_bitnot() {
451 let e = parse_expr("~mask");
452 assert!(matches!(
453 e.kind,
454 ExprKind::Unary {
455 op: UnaryOp::BitNot,
456 ..
457 }
458 ));
459 }
460
461 #[test]
464 fn test_binary_add() {
465 let e = parse_expr("a + 1");
466 match e.kind {
467 ExprKind::Binary {
468 op: BinaryOp::Add,
469 lhs,
470 rhs,
471 } => {
472 assert!(matches!(lhs.kind, ExprKind::Var(ref n) if n == "a"));
473 assert!(matches!(rhs.kind, ExprKind::Lit(Lit::Int(1))));
474 }
475 other => panic!("expected Add, got {other:?}"),
476 }
477 }
478
479 #[test]
480 fn test_binary_sub() {
481 let e = parse_expr("x - 2");
482 assert!(matches!(
483 e.kind,
484 ExprKind::Binary {
485 op: BinaryOp::Sub,
486 ..
487 }
488 ));
489 }
490
491 #[test]
492 fn test_binary_mul() {
493 let e = parse_expr("n * 4");
494 assert!(matches!(
495 e.kind,
496 ExprKind::Binary {
497 op: BinaryOp::Mul,
498 ..
499 }
500 ));
501 }
502
503 #[test]
509 fn test_cast_precedence() {
510 let e = parse_expr("a + x as uint");
511 let ExprKind::Binary {
512 op: BinaryOp::Add,
513 rhs,
514 ..
515 } = e.kind
516 else {
517 panic!("expected Add at root, got {:?}", e.kind);
518 };
519 assert!(matches!(
520 rhs.kind,
521 ExprKind::Cast {
522 ty: Type::Primitive(PrimitiveType::UInt),
523 ..
524 }
525 ));
526 let e = parse_expr("-x as uint");
527 let ExprKind::Cast { expr, .. } = e.kind else {
528 panic!("expected Cast at root, got {:?}", e.kind);
529 };
530 assert!(matches!(expr.kind, ExprKind::Unary { .. }));
531 let e = parse_expr("s.len as int8 as uint");
532 let ExprKind::Cast { expr, ty } = e.kind else {
533 panic!("expected Cast at root, got {:?}", e.kind);
534 };
535 assert_eq!(ty, Type::Primitive(PrimitiveType::UInt));
536 let ExprKind::Cast { expr, .. } = expr.kind else {
537 panic!("expected an inner Cast");
538 };
539 assert!(matches!(expr.kind, ExprKind::Field { .. }));
540 assert_eq!(e.span, 0..21);
541 }
542
543 #[test]
544 fn test_precedence_add_mul() {
545 let e = parse_expr("a + b * c");
547 match e.kind {
548 ExprKind::Binary {
549 op: BinaryOp::Add,
550 lhs,
551 rhs,
552 } => {
553 assert!(matches!(lhs.kind, ExprKind::Var(ref n) if n == "a"));
554 assert!(matches!(
555 rhs.kind,
556 ExprKind::Binary {
557 op: BinaryOp::Mul,
558 ..
559 }
560 ));
561 }
562 other => panic!("expected Add at root, got {other:?}"),
563 }
564 }
565
566 #[test]
567 fn test_precedence_mul_add() {
568 let e = parse_expr("a * b + c");
570 match e.kind {
571 ExprKind::Binary {
572 op: BinaryOp::Add,
573 lhs,
574 rhs,
575 } => {
576 assert!(matches!(
577 lhs.kind,
578 ExprKind::Binary {
579 op: BinaryOp::Mul,
580 ..
581 }
582 ));
583 assert!(matches!(rhs.kind, ExprKind::Var(ref n) if n == "c"));
584 }
585 other => panic!("expected Add at root, got {other:?}"),
586 }
587 }
588
589 #[test]
590 fn test_precedence_comparison_over_logical() {
591 let e = parse_expr("a < b && c > d");
593 assert!(matches!(
594 e.kind,
595 ExprKind::Binary {
596 op: BinaryOp::And,
597 ..
598 }
599 ));
600 }
601
602 #[test]
605 fn test_eq() {
606 assert!(matches!(
607 parse_expr("x == 0").kind,
608 ExprKind::Binary {
609 op: BinaryOp::Eq,
610 ..
611 }
612 ));
613 }
614
615 #[test]
616 fn test_lt() {
617 assert!(matches!(
618 parse_expr("n < 10").kind,
619 ExprKind::Binary {
620 op: BinaryOp::Lt,
621 ..
622 }
623 ));
624 }
625
626 #[test]
627 fn test_le() {
628 assert!(matches!(
629 parse_expr("n <= 10").kind,
630 ExprKind::Binary {
631 op: BinaryOp::Le,
632 ..
633 }
634 ));
635 }
636
637 #[test]
640 fn test_logical_and() {
641 assert!(matches!(
642 parse_expr("a && b").kind,
643 ExprKind::Binary {
644 op: BinaryOp::And,
645 ..
646 }
647 ));
648 }
649
650 #[test]
651 fn test_logical_or() {
652 assert!(matches!(
653 parse_expr("x || y").kind,
654 ExprKind::Binary {
655 op: BinaryOp::Or,
656 ..
657 }
658 ));
659 }
660
661 #[test]
664 fn test_bitwise_and() {
665 assert!(matches!(
666 parse_expr("flags & 0x0F").kind,
667 ExprKind::Binary {
668 op: BinaryOp::BitAnd,
669 ..
670 }
671 ));
672 }
673
674 #[test]
675 fn test_shl() {
676 assert!(matches!(
677 parse_expr("x << 2").kind,
678 ExprKind::Binary {
679 op: BinaryOp::Shl,
680 ..
681 }
682 ));
683 }
684
685 #[test]
688 fn test_call_in_expr() {
689 let e = parse_expr("eth.has_rx()");
690 match e.kind {
691 ExprKind::Call(c) => {
692 assert_eq!(c.alias, "eth");
693 assert_eq!(c.fn_name, "has_rx");
694 assert!(c.args.is_empty());
695 }
696 other => panic!("expected ExprKind::Call, got {other:?}"),
697 }
698 }
699
700 #[test]
701 fn test_call_with_arg() {
702 let e = parse_expr("eth.isforward(pkt)");
703 match e.kind {
704 ExprKind::Call(c) => {
705 assert_eq!(c.fn_name, "isforward");
706 assert!(matches!(c.args[0].kind, ExprKind::Var(ref n) if n == "pkt"));
707 }
708 other => panic!("expected ExprKind::Call, got {other:?}"),
709 }
710 }
711
712 #[test]
715 fn test_span_non_empty() {
716 let src = "a + b";
717 let mut remaining = LocatingSlice::new(src);
718 let start = 0usize;
719 let _ = parse(&mut remaining).unwrap();
720 let end = remaining.current_token_start();
721 assert!(end > start, "span should be non-empty");
722 }
723
724 #[test]
727 fn test_call_expr_basic() {
728 let mut remaining = LocatingSlice::new("eth.send_packet()");
729 let cexpr = call_expr(&mut remaining).unwrap();
730 assert_eq!(cexpr.alias, "eth");
731 assert_eq!(cexpr.fn_name, "send_packet");
732 assert!(cexpr.args.is_empty());
733 assert_eq!(*remaining, "");
734 }
735
736 #[test]
737 fn test_call_expr_single_arg() {
738 let mut remaining = LocatingSlice::new("eth.handle_irq(eth)");
739 let cexpr = call_expr(&mut remaining).unwrap();
740 assert_eq!(cexpr.alias, "eth");
741 assert_eq!(cexpr.fn_name, "handle_irq");
742 assert!(matches!(cexpr.args[0].kind, ExprKind::Var(ref n) if n == "eth"));
743 }
744
745 #[test]
746 fn test_call_expr_multiple_args() {
747 let mut remaining = LocatingSlice::new("ethc.reply(req, len, resp)");
748 let cexpr = call_expr(&mut remaining).unwrap();
749 assert_eq!(cexpr.fn_name, "reply");
750 assert_eq!(cexpr.args.len(), 3);
751 }
752
753 #[test]
754 fn test_call_expr_rejects_ws_around_dot() {
755 let mut remaining = LocatingSlice::new("drv . start()");
756 assert!(call_expr(&mut remaining).is_err());
757 }
758
759 #[test]
760 fn test_call_expr_rejects_ws_before_paren() {
761 let mut remaining = LocatingSlice::new("drv.start ()");
762 assert!(call_expr(&mut remaining).is_err());
763 }
764
765 #[test]
766 fn test_parse_dispatches_var() {
767 let mut remaining = LocatingSlice::new("my_var");
768 let expr = parse(&mut remaining).unwrap();
769 assert!(matches!(expr.kind, ExprKind::Var(ref n) if n == "my_var"));
770 }
771
772 #[test]
773 fn test_address_arithmetic() {
774 let src = "base + n * 4";
776 let e = parse_expr(src);
777 match e.kind {
779 ExprKind::Binary {
780 op: BinaryOp::Add,
781 rhs,
782 ..
783 } => {
784 assert!(matches!(
785 rhs.kind,
786 ExprKind::Binary {
787 op: BinaryOp::Mul,
788 ..
789 }
790 ));
791 }
792 other => panic!("expected Add, got {other:?}"),
793 }
794 }
795
796 #[test]
799 fn test_field_access() {
800 let e = parse_expr("ring_buf.vaddr");
801 match e.kind {
802 ExprKind::Field { expr, field } => {
803 assert_eq!(field, "vaddr");
804 assert!(matches!(expr.kind, ExprKind::Var(ref n) if n == "ring_buf"));
805 }
806 other => panic!("expected Field, got {other:?}"),
807 }
808 }
809
810 #[test]
811 fn test_field_access_in_binary() {
812 let e = parse_expr("ring_buf.vaddr + offset");
814 assert!(matches!(
815 e.kind,
816 ExprKind::Binary {
817 op: BinaryOp::Add,
818 ..
819 }
820 ));
821 }
822
823 #[test]
824 fn test_field_access_rejects_int_literal() {
825 let mut remaining = LocatingSlice::new("42.foo");
826 assert!(parse(&mut remaining).is_err());
827 }
828
829 #[test]
830 fn test_field_access_rejects_sizeof() {
831 let mut remaining = LocatingSlice::new("sizeof(int).foo");
832 assert!(parse(&mut remaining).is_err());
833 }
834
835 #[test]
836 fn test_field_access_rejects_binary() {
837 let mut remaining = LocatingSlice::new("(a + b).foo");
838 assert!(parse(&mut remaining).is_err());
839 }
840
841 #[test]
842 fn test_field_access_rejects_unary() {
843 let mut remaining = LocatingSlice::new("(-x).foo");
844 assert!(parse(&mut remaining).is_err());
845 }
846
847 #[test]
848 fn test_field_access_chain_still_valid() {
849 let e = parse_expr("a.b.c");
851 match e.kind {
852 ExprKind::Field { expr, field } => {
853 assert_eq!(field, "c");
854 match expr.kind {
855 ExprKind::Field { expr, field } => {
856 assert_eq!(field, "b");
857 assert!(matches!(expr.kind, ExprKind::Var(ref n) if n == "a"));
858 }
859 other => panic!("expected inner Field, got {other:?}"),
860 }
861 }
862 other => panic!("expected Field, got {other:?}"),
863 }
864 }
865
866 #[test]
867 fn test_field_access_on_call_still_valid() {
868 let e = parse_expr("eth.get_buf().addr");
869 match e.kind {
870 ExprKind::Field { expr, field } => {
871 assert_eq!(field, "addr");
872 assert!(matches!(expr.kind, ExprKind::Call(_)));
873 }
874 other => panic!("expected Field, got {other:?}"),
875 }
876 }
877}