1use crate::ast::*;
44use crate::lexer::{Span, Token, TokenKind};
45
46struct Parser {
48 tokens: Vec<Token>,
49 pos: usize,
50 tile_defaults: TileOptions,
53}
54
55impl Parser {
56 fn new(tokens: Vec<Token>) -> Self {
57 Self {
58 tokens,
59 pos: 0,
60 tile_defaults: TileOptions::default(),
61 }
62 }
63
64 fn peek(&self) -> &TokenKind {
65 &self.tokens[self.pos].kind
66 }
67
68 fn span(&self) -> Span {
69 self.tokens[self.pos].span
70 }
71
72 fn advance(&mut self) -> &Token {
73 let tok = &self.tokens[self.pos];
74 if self.pos < self.tokens.len() - 1 {
75 self.pos += 1;
76 }
77 tok
78 }
79
80 fn expect(&mut self, expected: &TokenKind) -> Result<&Token, String> {
81 if self.peek() == expected {
82 Ok(self.advance())
83 } else {
84 Err(format!(
85 "expected {:?}, got {:?} at line {}, col {}",
86 expected,
87 self.peek(),
88 self.span().line,
89 self.span().col
90 ))
91 }
92 }
93
94 fn expect_ident(&mut self) -> Result<String, String> {
95 match self.peek().clone() {
96 TokenKind::Ident(name) => {
97 self.advance();
98 Ok(name)
99 }
100 TokenKind::Input => {
107 self.advance();
108 Ok("input".to_string())
109 }
110 TokenKind::Cursor => {
116 self.advance();
117 Ok("cursor".to_string())
118 }
119 TokenKind::Over => {
124 self.advance();
125 Ok("over".to_string())
126 }
127 _ => Err(format!(
128 "expected identifier, got {:?} at line {}, col {}",
129 self.peek(),
130 self.span().line,
131 self.span().col
132 )),
133 }
134 }
135
136 fn expect_type_name(&mut self) -> Result<String, String> {
143 let span = self.span();
144 let name = self.expect_ident()?;
145 if crate::PortType::from_keyword(&name).is_some() {
146 return Ok(name);
147 }
148 let message = crate::PortType::retired_keyword_message(&name)
149 .unwrap_or_else(|| format!("`{name}` is not a type keyword"));
150 Err(format!(
151 "{message} (at line {}, col {})",
152 span.line, span.col
153 ))
154 }
155
156 fn at_eof(&self) -> bool {
157 matches!(self.peek(), TokenKind::Eof)
158 }
159}
160
161pub fn parse(tokens: Vec<Token>) -> Result<PolydatFile, String> {
163 parse_with_tile_defaults(tokens, &TileOptions::default())
164}
165
166pub fn parse_with_tile_defaults(
175 tokens: Vec<Token>,
176 tile_defaults: &TileOptions,
177) -> Result<PolydatFile, String> {
178 let mut parser = Parser::new(tokens);
179 parser.tile_defaults = tile_defaults.clone();
180 let mut statements = Vec::new();
181
182 while !parser.at_eof() {
183 parse_statement_into(&mut parser, &mut statements)?;
184 }
185
186 Ok(PolydatFile { statements })
187}
188
189pub fn parse_expression(tokens: Vec<Token>) -> Result<Expr, String> {
207 let mut parser = Parser::new(tokens);
208 let expr = parse_expr(&mut parser)?;
209 if !parser.at_eof() {
210 let span = parser.span();
211 return Err(format!(
212 "expected end of expression at line {}, col {}, got {:?}",
213 span.line,
214 span.col,
215 parser.peek()
216 ));
217 }
218 Ok(expr)
219}
220
221fn parse_statement_into(p: &mut Parser, out: &mut Vec<Statement>) -> Result<(), String> {
227 match p.peek() {
228 TokenKind::Pragma => out.push(parse_pragma(p)?),
229 TokenKind::Input => parse_input_decl(p, out)?,
230 TokenKind::Extern => out.push(parse_extern_port(p)?),
231 TokenKind::Cursor => out.push(parse_cursor_decl(p)?),
232 TokenKind::For(_) => out.push(parse_for_statement(p)?),
233 TokenKind::Tile => out.push(parse_tile(p)?),
234 TokenKind::Const | TokenKind::Shared | TokenKind::Volatile => {
235 out.push(parse_modified_binding(p)?);
236 }
237 TokenKind::LParen => out.push(parse_destructuring_binding(p)?),
238 TokenKind::Ident(_) => {
239 if is_module_def(p) {
243 out.push(parse_module_def(p)?);
244 } else if is_polytile_binding(p) {
245 out.push(parse_polytile_binding(p)?);
246 } else {
247 out.push(parse_cycle_binding(p)?);
248 }
249 }
250 _ => {
251 return Err(format!(
252 "unexpected token {:?} at line {}, col {}",
253 p.peek(),
254 p.span().line,
255 p.span().col
256 ));
257 }
258 }
259 Ok(())
260}
261
262fn parse_for_statement(p: &mut Parser) -> Result<Statement, String> {
268 let span = p.span();
269 let text = match p.peek().clone() {
270 TokenKind::For(text) => text,
271 other => {
272 return Err(format!(
273 "expected `for`, got {other:?} at line {}, col {}",
274 span.line, span.col
275 ));
276 }
277 };
278 p.advance();
279 let source = for_source_from_text(&text, span, true)?;
280 if !matches!(p.peek(), TokenKind::LBrace) {
281 return Err(format!(
282 "`for {text}` at line {}, col {} needs a `{{` block on the same line; \
283 to bind a producer instead, write `name := for {text}`",
284 span.line, span.col
285 ));
286 }
287 p.advance();
288 let mut body = Vec::new();
289 while !matches!(p.peek(), TokenKind::RBrace | TokenKind::Eof) {
290 parse_statement_into(p, &mut body)?;
291 }
292 p.expect(&TokenKind::RBrace)?;
293 Ok(Statement::For(ForStmt { source, body, span }))
294}
295
296fn parse_tile(p: &mut Parser) -> Result<Statement, String> {
301 let span = p.span();
302 p.expect(&TokenKind::Tile)?;
303 let name = p.expect_ident()?;
304 let encoding = if matches!(p.peek(), TokenKind::Colon) {
305 p.advance();
306 Some(p.expect_ident()?)
307 } else {
308 None
309 };
310 let mut options = p.tile_defaults.clone();
311 if matches!(p.peek(), TokenKind::LParen) {
312 p.advance();
313 while !matches!(p.peek(), TokenKind::RParen | TokenKind::Eof) {
314 let key = p.expect_ident()?;
315 match key.as_str() {
316 "delims" => {
317 options.open = expect_string(p, "delims open")?;
318 options.close = expect_string(p, "delims close")?;
319 if options.open.is_empty() || options.close.is_empty() {
320 return Err(format!(
321 "tile '{name}' at line {}, col {}: delimiters must not be empty",
322 span.line, span.col
323 ));
324 }
325 }
326 "sigil" => {
327 options.sigil = expect_string(p, "sigil")?;
328 if options.sigil.is_empty() {
329 return Err(format!(
330 "tile '{name}' at line {}, col {}: sigil must not be empty",
331 span.line, span.col
332 ));
333 }
334 }
335 "strict" => options.strict = true,
336 "instring" => options.in_string = true,
337 other => {
338 return Err(format!(
339 "tile '{name}' at line {}, col {}: unknown option '{other}'; options are delims, sigil, strict, instring",
340 span.line, span.col
341 ));
342 }
343 }
344 if matches!(p.peek(), TokenKind::Comma) {
345 p.advance();
346 }
347 }
348 p.expect(&TokenKind::RParen)?;
349 }
350 if !matches!(p.peek(), TokenKind::ColonEq) {
353 return Err(format!(
354 "tile '{name}' at line {}, col {}: expected `:=` before the body; a tile binds a wire, \
355 as in `tile {name} : json := {{ ... }}` or `tile {name} := \"...\"`, got {:?}",
356 span.line,
357 span.col,
358 p.peek()
359 ));
360 }
361 p.advance();
362 let (body_kind, body) = match p.peek().clone() {
363 TokenKind::TileBody(text, kind) => {
364 p.advance();
365 (kind, text)
366 }
367 TokenKind::StringLit(s) => {
368 p.advance();
369 (TileBodyKind::Literal, s)
370 }
371 other => {
372 return Err(format!(
373 "tile '{name}' at line {}, col {}: expected a body (a `{{ }}` or `[ ]` block, `<<< >>>` heredoc, or string), got {other:?}",
374 span.line, span.col
375 ));
376 }
377 };
378 if let Some(enc) = &encoding
379 && !matches!(enc.as_str(), "json" | "text" | "csv")
380 {
381 return Err(format!(
382 "tile '{name}' at line {}, col {}: unknown encoding '{enc}'; encodings are json, text, csv",
383 span.line, span.col
384 ));
385 }
386 let pieces = super::tile::parse_template(&body, &options, span)
387 .map_err(|e| format!("tile '{name}': {e}"))?;
388 Ok(Statement::Tile(TileDef {
389 name,
390 encoding,
391 options,
392 body_kind,
393 pieces,
394 span,
395 }))
396}
397
398fn is_polytile_binding(p: &Parser) -> bool {
401 p.pos + 3 < p.tokens.len()
402 && matches!(&p.tokens[p.pos].kind, TokenKind::Ident(_))
403 && matches!(&p.tokens[p.pos + 1].kind, TokenKind::ColonEq)
404 && matches!(&p.tokens[p.pos + 2].kind, TokenKind::Ident(f) if f == "polytile" || f == "polytile_json")
405 && matches!(&p.tokens[p.pos + 3].kind, TokenKind::LParen)
406}
407
408fn parse_polytile_binding(p: &mut Parser) -> Result<Statement, String> {
416 let span = p.span();
417 let name = p.expect_ident()?;
418 p.expect(&TokenKind::ColonEq)?;
419 let func = p.expect_ident()?;
420 p.expect(&TokenKind::LParen)?;
421 let at = |what: &str| {
422 format!(
423 "{func} for '{name}' at line {}, col {}: {what}",
424 span.line, span.col
425 )
426 };
427 let encoding = if func == "polytile" {
428 let e = expect_string(p, "the encoding").map_err(|m| at(&m))?;
429 if !matches!(p.peek(), TokenKind::Comma) {
430 return Err(at("expected `,` and then the template"));
431 }
432 p.advance();
433 Some(e)
434 } else {
435 None
436 };
437 let body = expect_string(p, "the template body (a string or a `<<< >>>` heredoc)")
438 .map_err(|m| at(&m))?;
439 let mut options = p.tile_defaults.clone();
440 while matches!(p.peek(), TokenKind::Comma) {
441 p.advance();
442 if matches!(p.peek(), TokenKind::RParen) {
443 break;
444 }
445 let key = p.expect_ident()?;
446 p.expect(&TokenKind::Colon)
447 .map_err(|_| at(&format!("option `{key}` needs `: \"value\"`")))?;
448 match key.as_str() {
449 "open" => options.open = expect_string(p, "open").map_err(|m| at(&m))?,
450 "close" => options.close = expect_string(p, "close").map_err(|m| at(&m))?,
451 "sigil" => options.sigil = expect_string(p, "sigil").map_err(|m| at(&m))?,
452 "strict" => {
453 let v = p.expect_ident().map_err(|m| at(&m))?;
454 options.strict = v == "true";
455 }
456 "instring" => {
457 let v = p.expect_ident().map_err(|m| at(&m))?;
458 options.in_string = v == "true";
459 }
460 other => {
461 return Err(at(&format!(
462 "unknown option '{other}'; options are open, close, sigil, strict, instring"
463 )));
464 }
465 }
466 }
467 p.expect(&TokenKind::RParen).map_err(|m| at(&m))?;
468 if options.open.is_empty() || options.close.is_empty() || options.sigil.is_empty() {
469 return Err(at("delimiters and sigil must not be empty"));
470 }
471 let tile = match encoding {
472 Some(enc) => super::tile_structural::tile_from_text(&name, &enc, &body, &options, span)?,
473 None => super::tile_structural::tile_from_json_text(&name, &body, &options, span)?,
474 };
475 Ok(Statement::Tile(tile))
476}
477
478fn expect_string(p: &mut Parser, what: &str) -> Result<String, String> {
479 match p.peek().clone() {
480 TokenKind::StringLit(s) => {
481 p.advance();
482 Ok(s)
483 }
484 other => Err(format!(
485 "expected a string for {what}, got {other:?} at line {}, col {}",
486 p.span().line,
487 p.span().col
488 )),
489 }
490}
491
492pub fn for_source_from_text(
494 text: &str,
495 span: Span,
496 allow_producer: bool,
497) -> Result<ForSource, String> {
498 if text.is_empty() {
499 return Err(format!(
500 "`for` at line {}, col {} has no comprehension",
501 span.line, span.col
502 ));
503 }
504 let is_ident = text.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
505 && text
506 .chars()
507 .next()
508 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
509 if is_ident {
510 if allow_producer {
511 return Ok(ForSource::producer(text, span));
512 }
513 return Err(format!(
514 "`for {text}` at line {}, col {}: a producer expression needs comprehension text such as `k in 1..10`, \
515 or a derivation such as `{text} where {{k}} > 1` or `{text} order halton/5`",
516 span.line, span.col
517 ));
518 }
519 {
522 use crate::comprehension::parse::{split_at_order, split_at_where};
523 let (head, order) = split_at_order(text);
524 let (base, filter) = split_at_where(&head);
525 let base = base.trim();
526 let base_is_ident = !base.is_empty()
527 && base.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
528 && base
529 .chars()
530 .next()
531 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
532 if base_is_ident && (filter.is_some() || order.is_some()) {
533 return Ok(ForSource::derived(base, filter, order, span));
534 }
535 }
536 let algebra = crate::comprehension::spec::parse_comprehension_algebra(text)
537 .map_err(|e| format!("`for {text}` at line {}, col {}: {e}", span.line, span.col))?;
538 ForSource::comprehension(algebra, span).ok_or_else(|| {
544 format!(
545 "`for {text}` at line {}, col {}: parsed, but the comprehension it denotes has no text \
546 form, so it could not be written back; this is a gap between the comprehension \
547 parser and its renderer, not an error in the program",
548 span.line, span.col
549 )
550 })
551}
552
553fn parse_pragma(p: &mut Parser) -> Result<Statement, String> {
554 let span = p.span();
555 p.expect(&TokenKind::Pragma)?;
556 let name = p.expect_ident()?;
557 Ok(Statement::Pragma { name, span })
558}
559
560fn is_module_def(p: &Parser) -> bool {
562 if p.pos + 4 >= p.tokens.len() {
567 return false;
568 }
569 let third_is_param_name = matches!(
570 &p.tokens[p.pos + 2].kind,
571 TokenKind::Ident(_) | TokenKind::Input,
572 );
573 matches!(&p.tokens[p.pos].kind, TokenKind::Ident(_))
574 && matches!(&p.tokens[p.pos + 1].kind, TokenKind::LParen)
575 && third_is_param_name
576 && matches!(&p.tokens[p.pos + 3].kind, TokenKind::Colon)
577}
578
579fn parse_module_def(p: &mut Parser) -> Result<Statement, String> {
581 let span = p.span();
582 let name = p.expect_ident()?;
583
584 p.expect(&TokenKind::LParen)?;
586 let mut params = Vec::new();
587 while !matches!(p.peek(), TokenKind::RParen) {
588 let pname = p.expect_ident()?;
589 p.expect(&TokenKind::Colon)?;
590 let ptype = p.expect_type_name()?;
591 params.push(TypedParam {
592 name: pname,
593 typ: ptype,
594 });
595 if matches!(p.peek(), TokenKind::Comma) {
596 p.advance();
597 }
598 }
599 p.expect(&TokenKind::RParen)?;
600
601 p.expect(&TokenKind::Arrow)?;
603 p.expect(&TokenKind::LParen)?;
604 let mut outputs = Vec::new();
605 while !matches!(p.peek(), TokenKind::RParen) {
606 let oname = p.expect_ident()?;
607 p.expect(&TokenKind::Colon)?;
608 let otype = p.expect_type_name()?;
609 outputs.push(TypedParam {
610 name: oname,
611 typ: otype,
612 });
613 if matches!(p.peek(), TokenKind::Comma) {
614 p.advance();
615 }
616 }
617 p.expect(&TokenKind::RParen)?;
618
619 p.expect(&TokenKind::ColonEq)?;
621 p.expect(&TokenKind::LBrace)?;
622
623 let mut body = Vec::new();
624 while !matches!(p.peek(), TokenKind::RBrace | TokenKind::Eof) {
625 parse_statement_into(p, &mut body)?;
626 }
627 p.expect(&TokenKind::RBrace)?;
628
629 Ok(Statement::ModuleDef(ModuleDef {
630 name,
631 params,
632 outputs,
633 body,
634 span,
635 }))
636}
637
638fn parse_extern_port(p: &mut Parser) -> Result<Statement, String> {
640 let span = p.span();
641 p.advance(); let name = p.expect_ident()?;
644 p.expect(&TokenKind::Colon)?;
645 let typ = p.expect_type_name()?;
646
647 let default = if matches!(p.peek(), TokenKind::Eq) {
649 p.advance(); Some(parse_expr(p)?)
651 } else {
652 None
653 };
654
655 Ok(Statement::ExternPort(ExternPort {
656 name,
657 typ,
658 default,
659 span,
660 }))
661}
662
663fn parse_input_decl(p: &mut Parser, out: &mut Vec<Statement>) -> Result<(), String> {
674 let keyword_span = p.span();
675 p.advance(); if matches!(p.peek(), TokenKind::LParen) {
678 p.advance(); if matches!(p.peek(), TokenKind::RParen) {
681 return Err(format!(
682 "`input ()` is empty; omit the line entirely to declare zero inputs \
683 (at line {}, col {})",
684 keyword_span.line, keyword_span.col,
685 ));
686 }
687 loop {
688 let span = p.span();
689 let name = p.expect_ident()?;
690 let ty = if matches!(p.peek(), TokenKind::Colon) {
691 p.advance();
692 Some(p.expect_type_name()?)
693 } else {
694 None
695 };
696 out.push(Statement::InputDecl(InputDecl { name, ty, span }));
697 if matches!(p.peek(), TokenKind::Comma) {
698 p.advance();
699 } else {
700 break;
701 }
702 }
703 p.expect(&TokenKind::RParen)?;
704 } else {
705 let span = p.span();
707 let name = p.expect_ident()?;
708 let ty = if matches!(p.peek(), TokenKind::Colon) {
709 p.advance();
710 Some(p.expect_type_name()?)
711 } else {
712 None
713 };
714 out.push(Statement::InputDecl(InputDecl { name, ty, span }));
715 }
716 Ok(())
717}
718
719fn parse_cursor_decl(p: &mut Parser) -> Result<Statement, String> {
724 let span = p.span();
725 p.advance(); let name = p.expect_ident()?;
727 p.expect(&TokenKind::Eq)?;
728 let constructor = parse_expr(p)?;
729 let over = if matches!(p.peek(), TokenKind::Over) {
731 p.advance();
732 Some(parse_expr(p)?)
733 } else {
734 None
735 };
736 Ok(Statement::Cursor(CursorDecl {
737 name,
738 constructor,
739 over,
740 span,
741 }))
742}
743
744fn parse_modified_binding(p: &mut Parser) -> Result<Statement, String> {
750 let start_span = p.span();
751 let mut collected: Vec<WireModifier> = Vec::new();
752
753 loop {
754 let m = match p.peek() {
755 TokenKind::Const => WireModifier::Const,
756 TokenKind::Shared => WireModifier::Shared,
757 TokenKind::Volatile => WireModifier::Volatile,
758 _ => break,
759 };
760 if collected.contains(&m) {
761 return Err(format!(
762 "duplicate `{m:?}` modifier at line {}, col {}",
763 p.span().line,
764 p.span().col,
765 ));
766 }
767 collected.push(m);
768 p.advance();
769 }
770
771 let modifier = BindingModifier::try_from_iter(collected)
772 .map_err(|e| format!("{e} at line {}, col {}", start_span.line, start_span.col,))?;
773
774 match p.peek() {
775 TokenKind::Ident(_) | TokenKind::Input | TokenKind::Cursor | TokenKind::Over => {
781 parse_cycle_binding_with_modifier(p, modifier)
782 }
783 _ => Err(format!(
784 "expected binding name after modifiers at line {}, col {}",
785 p.span().line,
786 p.span().col
787 )),
788 }
789}
790
791fn parse_cycle_binding(p: &mut Parser) -> Result<Statement, String> {
793 parse_cycle_binding_with_modifier(p, BindingModifier::NONE)
794}
795
796fn parse_cycle_binding_with_modifier(
797 p: &mut Parser,
798 modifier: BindingModifier,
799) -> Result<Statement, String> {
800 let span = p.span();
801 let name = p.expect_ident()?;
802 let type_annotation = if matches!(p.peek(), TokenKind::Colon) {
808 p.advance(); let typ = p.expect_type_name()?;
810 if !modifier.is_shared() {
811 return Err(format!(
812 "type annotation `{name}: {typ}` is only supported on `shared` bindings (it pins the shared cell's type). For a plain typed slot use `extern {name}: {typ} = …` at line {}, col {}",
813 span.line, span.col,
814 ));
815 }
816 Some(typ)
817 } else {
818 None
819 };
820 p.expect(&TokenKind::ColonEq)?;
821 let value = parse_expr(p)?;
822
823 Ok(Statement::Binding(Binding {
824 targets: vec![name],
825 value,
826 modifier,
827 type_annotation,
828 span,
829 }))
830}
831
832fn parse_destructuring_binding(p: &mut Parser) -> Result<Statement, String> {
834 let span = p.span();
835 p.advance(); let mut targets = Vec::new();
837 loop {
838 targets.push(p.expect_ident()?);
839 if matches!(p.peek(), TokenKind::Comma) {
840 p.advance();
841 } else {
842 break;
843 }
844 }
845 p.expect(&TokenKind::RParen)?;
846 p.expect(&TokenKind::ColonEq)?;
847 let value = parse_expr(p)?;
848
849 Ok(Statement::Binding(Binding {
850 targets,
851 value,
852 modifier: BindingModifier::NONE,
853 type_annotation: None,
854 span,
855 }))
856}
857
858fn parse_expr(p: &mut Parser) -> Result<Expr, String> {
864 parse_expr_bp(p, 0)
865}
866
867fn parse_expr_bp(p: &mut Parser, min_bp: u8) -> Result<Expr, String> {
891 let mut lhs = parse_atom(p)?;
892 lhs = parse_postfix_as(p, lhs)?;
896
897 while let Some(op_kind) = binary_operator(p.peek()) {
898 let (l_bp, r_bp) = binding_power(op_kind);
899 if l_bp < min_bp {
900 break;
901 }
902
903 p.advance(); let rhs = parse_expr_bp(p, r_bp)?;
905 lhs = Expr::BinOp(Box::new(lhs), op_kind, Box::new(rhs));
906 }
907
908 Ok(lhs)
909}
910
911pub fn binary_operator(kind: &TokenKind) -> Option<BinOpKind> {
913 Some(match kind {
914 TokenKind::PipePipe => BinOpKind::Or,
915 TokenKind::AmpAmp => BinOpKind::And,
916 TokenKind::EqEq => BinOpKind::Eq,
917 TokenKind::BangEq => BinOpKind::Ne,
918 TokenKind::Lt => BinOpKind::Lt,
919 TokenKind::Gt => BinOpKind::Gt,
920 TokenKind::LtEq => BinOpKind::Le,
921 TokenKind::GtEq => BinOpKind::Ge,
922 TokenKind::Pipe => BinOpKind::BitOr,
923 TokenKind::Caret => BinOpKind::BitXor,
924 TokenKind::Ampersand => BinOpKind::BitAnd,
925 TokenKind::ShiftLeft => BinOpKind::Shl,
926 TokenKind::ShiftRight => BinOpKind::Shr,
927 TokenKind::Plus => BinOpKind::Add,
928 TokenKind::Minus => BinOpKind::Sub,
929 TokenKind::Star => BinOpKind::Mul,
930 TokenKind::Slash => BinOpKind::Div,
931 TokenKind::Percent => BinOpKind::Mod,
932 TokenKind::StarStar => BinOpKind::Pow,
933 _ => return None,
934 })
935}
936
937pub fn binding_power(op: BinOpKind) -> (u8, u8) {
946 match op {
947 BinOpKind::Or => (1, 2),
948 BinOpKind::And => (3, 4),
949 BinOpKind::Eq | BinOpKind::Ne => (5, 6),
950 BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Le | BinOpKind::Ge => (7, 8),
951 BinOpKind::BitOr => (9, 10),
952 BinOpKind::BitXor => (11, 12),
953 BinOpKind::BitAnd => (13, 14),
954 BinOpKind::Shl | BinOpKind::Shr => (15, 16),
955 BinOpKind::Add | BinOpKind::Sub => (17, 18),
956 BinOpKind::Mul | BinOpKind::Div | BinOpKind::Mod => (19, 20),
957 BinOpKind::Pow => (22, 21),
958 }
959}
960
961fn parse_postfix_as(p: &mut Parser, mut expr: Expr) -> Result<Expr, String> {
965 while matches!(p.peek(), TokenKind::Ident(s) if s.as_str() == "as") {
966 let span = p.span();
967 p.advance(); let ty_name = match p.peek() {
969 TokenKind::Ident(name) => name.clone(),
970 other => return Err(format!("expected a type name after `as`, found {other:?}")),
971 };
972 p.advance(); let port_type = crate::PortType::from_keyword(&ty_name).ok_or_else(|| {
974 crate::PortType::retired_keyword_message(&ty_name)
975 .unwrap_or_else(|| format!("unknown type `{ty_name}` in `... as {ty_name}` cast"))
976 })?;
977 expr = Expr::Cast(Box::new(expr), port_type, span);
978 }
979 Ok(expr)
980}
981
982fn parse_if_block(p: &mut Parser, span: Span) -> Result<Expr, String> {
1006 let cond = parse_expr(p)?;
1007
1008 if !matches!(p.peek(), TokenKind::LBrace) {
1009 return Err(format!(
1010 "expected `{{` to open the then-branch of an `if` expression, got {:?} at line {}, col {}. \
1011 Block form is `if <cond> {{ <then> }} else {{ <else> }}`; the call form `if(cond, a, b)` \
1012 is also accepted.",
1013 p.peek(),
1014 p.span().line,
1015 p.span().col
1016 ));
1017 }
1018 p.advance();
1019 let then_expr = parse_expr(p)?;
1020 p.expect(&TokenKind::RBrace)?;
1021
1022 match p.peek().clone() {
1023 TokenKind::Ident(word) if word == "else" => {
1024 p.advance();
1025 }
1026 other => {
1027 return Err(format!(
1028 "expected `else` after the then-branch of an `if` expression, got {:?} at line {}, col {}. \
1029 `else` is required: a Polydat expression always produces a value, so there is no \
1030 result for the false path without it.",
1031 other,
1032 p.span().line,
1033 p.span().col
1034 ));
1035 }
1036 }
1037
1038 let else_expr = match p.peek().clone() {
1040 TokenKind::Ident(word) if word == "if" => {
1041 let else_span = p.span();
1042 p.advance();
1043 parse_if_block(p, else_span)?
1044 }
1045 TokenKind::LBrace => {
1046 p.advance();
1047 let e = parse_expr(p)?;
1048 p.expect(&TokenKind::RBrace)?;
1049 e
1050 }
1051 other => {
1052 return Err(format!(
1053 "expected `{{` or `if` after `else`, got {:?} at line {}, col {}",
1054 other,
1055 p.span().line,
1056 p.span().col
1057 ));
1058 }
1059 };
1060
1061 Ok(Expr::Call(CallExpr {
1063 func: "if".into(),
1064 args: vec![
1065 Arg::Positional(cond),
1066 Arg::Positional(then_expr),
1067 Arg::Positional(else_expr),
1068 ],
1069 span,
1070 }))
1071}
1072
1073fn parse_atom(p: &mut Parser) -> Result<Expr, String> {
1074 let span = p.span();
1075
1076 match p.peek().clone() {
1077 TokenKind::Minus => {
1078 p.advance();
1080 let inner = parse_atom(p)?;
1081 Ok(Expr::UnaryNeg(Box::new(inner), span))
1082 }
1083 TokenKind::Bang => {
1084 p.advance();
1086 let inner = parse_atom(p)?;
1087 Ok(Expr::UnaryBitNot(Box::new(inner), span))
1088 }
1089 TokenKind::LParen => {
1090 p.advance(); let inner = parse_expr(p)?;
1094 p.expect(&TokenKind::RParen)?;
1095 Ok(inner)
1096 }
1097 TokenKind::StringLit(s) => {
1098 p.advance();
1099 Ok(parse_interpolated_string(s, span))
1100 }
1101 TokenKind::IntLit(v) => {
1102 p.advance();
1103 Ok(Expr::IntLit(v, span))
1104 }
1105 TokenKind::FloatLit(v) => {
1106 p.advance();
1107 Ok(Expr::FloatLit(v, span))
1108 }
1109 TokenKind::LBracket => parse_array_lit(p),
1110 TokenKind::For(text) => {
1111 p.advance();
1112 let source = for_source_from_text(&text, span, false)?;
1113 Ok(Expr::For(Box::new(source)))
1114 }
1115 TokenKind::Ident(name) => {
1116 p.advance();
1117 if name == "if" && !matches!(p.peek(), TokenKind::LParen) {
1123 parse_if_block(p, span)
1124 } else if matches!(p.peek(), TokenKind::LParen) {
1125 parse_call(p, name, span)
1127 } else if matches!(p.peek(), TokenKind::Dot) {
1128 parse_field_chain(p, name, span)
1129 } else {
1130 Ok(Expr::Ident(name, span))
1131 }
1132 }
1133 TokenKind::Input => {
1137 p.advance();
1138 let name = "input".to_string();
1139 if matches!(p.peek(), TokenKind::Dot) {
1140 parse_field_chain(p, name, span)
1141 } else {
1142 Ok(Expr::Ident(name, span))
1143 }
1144 }
1145 TokenKind::Cursor => {
1151 p.advance();
1152 let name = "cursor".to_string();
1153 if matches!(p.peek(), TokenKind::Dot) {
1154 parse_field_chain(p, name, span)
1155 } else {
1156 Ok(Expr::Ident(name, span))
1157 }
1158 }
1159 TokenKind::Over => {
1163 p.advance();
1164 let name = "over".to_string();
1165 if matches!(p.peek(), TokenKind::Dot) {
1166 parse_field_chain(p, name, span)
1167 } else {
1168 Ok(Expr::Ident(name, span))
1169 }
1170 }
1171 _ => Err(format!(
1172 "expected expression, got {:?} at line {}, col {}",
1173 p.peek(),
1174 span.line,
1175 span.col
1176 )),
1177 }
1178}
1179
1180fn parse_interpolated_string(s: String, span: Span) -> Expr {
1215 let segments = match scan_interpolation_segments(&s) {
1216 Some(segs) => segs,
1217 None => return Expr::StringLit(s, span), };
1219
1220 if !segments
1221 .iter()
1222 .any(|seg| matches!(seg, Segment::Placeholder(_)))
1223 {
1224 return Expr::StringLit(s, span);
1225 }
1226
1227 let mut format_str = String::with_capacity(s.len());
1232 let mut placeholder_exprs: Vec<Expr> = Vec::new();
1233 for seg in segments {
1234 match seg {
1235 Segment::Literal(text) => format_str.push_str(&text),
1236 Segment::Placeholder(body) => {
1237 let expr = match parse_placeholder_body(&body, span) {
1238 Ok(e) => e,
1239 Err(_) => return Expr::StringLit(s, span),
1244 };
1245 placeholder_exprs.push(expr);
1246 format_str.push_str("{}");
1247 }
1248 }
1249 }
1250
1251 let mut args: Vec<Arg> = Vec::with_capacity(placeholder_exprs.len() + 1);
1252 args.push(Arg::Positional(Expr::StringLit(format_str, span)));
1253 for e in placeholder_exprs {
1254 args.push(Arg::Positional(e));
1255 }
1256 Expr::Call(CallExpr {
1257 func: "printf".into(),
1258 args,
1259 span,
1260 })
1261}
1262
1263enum Segment {
1265 Literal(String),
1269 Placeholder(String),
1272}
1273
1274fn scan_interpolation_segments(s: &str) -> Option<Vec<Segment>> {
1283 let chars: Vec<char> = s.chars().collect();
1284 let mut segments: Vec<Segment> = Vec::new();
1285 let mut literal = String::new();
1286 let mut i = 0;
1287 while i < chars.len() {
1288 let c = chars[i];
1289 if c == '{' && i + 1 < chars.len() && chars[i + 1] == '{' {
1292 literal.push_str("{{");
1293 i += 2;
1294 continue;
1295 }
1296 if c == '}' && i + 1 < chars.len() && chars[i + 1] == '}' {
1297 literal.push_str("}}");
1298 i += 2;
1299 continue;
1300 }
1301 if c == '{' {
1302 if !literal.is_empty() {
1303 segments.push(Segment::Literal(std::mem::take(&mut literal)));
1304 }
1305 let body_start = i + 1;
1306 let body_end = find_placeholder_end(&chars, body_start)?;
1307 let body: String = chars[body_start..body_end].iter().collect();
1308 segments.push(Segment::Placeholder(body));
1309 i = body_end + 1; continue;
1311 }
1312 literal.push(c);
1313 i += 1;
1314 }
1315 if !literal.is_empty() {
1316 segments.push(Segment::Literal(literal));
1317 }
1318 Some(segments)
1319}
1320
1321fn find_placeholder_end(chars: &[char], start: usize) -> Option<usize> {
1326 let mut depth: i32 = 0;
1327 let mut in_string = false;
1328 let mut i = start;
1329 while i < chars.len() {
1330 let c = chars[i];
1331 if in_string {
1332 if c == '\\' && i + 1 < chars.len() {
1333 i += 2;
1338 continue;
1339 }
1340 if c == '"' {
1341 in_string = false;
1342 }
1343 i += 1;
1344 continue;
1345 }
1346 match c {
1347 '"' => in_string = true,
1348 '(' | '[' | '{' => depth += 1,
1349 ')' | ']' => depth -= 1,
1350 '}' => {
1351 if depth == 0 {
1352 return Some(i);
1353 }
1354 depth -= 1;
1355 }
1356 _ => {}
1357 }
1358 i += 1;
1359 }
1360 None
1361}
1362
1363fn parse_placeholder_body(body: &str, _span: Span) -> Result<Expr, String> {
1365 let body = body.trim();
1366 if body.is_empty() {
1367 return Err("empty placeholder".into());
1368 }
1369 let tokens = crate::lexer::lex(body)?;
1370 parse_expression(tokens)
1371}
1372
1373fn parse_field_chain(p: &mut Parser, base: String, span: Span) -> Result<Expr, String> {
1381 p.advance(); let mut source = base;
1383 let mut field = p.expect_ident()?;
1384 while matches!(p.peek(), TokenKind::Dot) {
1385 p.advance();
1386 source = format!("{source}__{field}");
1387 field = p.expect_ident()?;
1388 }
1389 Ok(Expr::FieldAccess {
1390 source,
1391 field,
1392 span,
1393 })
1394}
1395
1396fn parse_call(p: &mut Parser, func: String, span: Span) -> Result<Expr, String> {
1398 p.advance(); let mut args = Vec::new();
1400
1401 if !matches!(p.peek(), TokenKind::RParen) {
1402 loop {
1403 args.push(parse_arg(p)?);
1404 if matches!(p.peek(), TokenKind::Comma) {
1405 p.advance();
1406 } else {
1407 break;
1408 }
1409 }
1410 }
1411
1412 p.expect(&TokenKind::RParen)?;
1413 Ok(Expr::Call(CallExpr { func, args, span }))
1414}
1415
1416fn parse_arg(p: &mut Parser) -> Result<Arg, String> {
1422 let arg_name: Option<String> = match p.peek() {
1423 TokenKind::Ident(name) => Some(name.clone()),
1424 TokenKind::Input => Some("input".to_string()),
1425 _ => None,
1426 };
1427 if let Some(name) = arg_name
1428 && p.pos + 1 < p.tokens.len()
1429 && matches!(p.tokens[p.pos + 1].kind, TokenKind::Colon)
1430 {
1431 p.advance(); p.advance(); let value = parse_expr(p)?;
1434 return Ok(Arg::Named(name, value));
1435 }
1436 let expr = parse_expr(p)?;
1437 Ok(Arg::Positional(expr))
1438}
1439
1440fn parse_array_lit(p: &mut Parser) -> Result<Expr, String> {
1442 let span = p.span();
1443 p.advance(); let mut elements = Vec::new();
1445
1446 if !matches!(p.peek(), TokenKind::RBracket) {
1447 loop {
1448 elements.push(parse_expr(p)?);
1449 if matches!(p.peek(), TokenKind::Comma) {
1450 p.advance();
1451 } else {
1452 break;
1453 }
1454 }
1455 }
1456
1457 p.expect(&TokenKind::RBracket)?;
1458 Ok(Expr::ArrayLit(elements, span))
1459}
1460
1461#[cfg(test)]
1462mod tests {
1463 use super::*;
1464 use crate::lexer::lex;
1465
1466 fn parse_str(s: &str) -> PolydatFile {
1467 let tokens = lex(s).unwrap();
1468 parse(tokens).unwrap()
1469 }
1470
1471 fn parse_str_err(s: &str) -> String {
1472 let tokens = lex(s).unwrap();
1473 match parse(tokens) {
1474 Ok(_) => panic!("expected parse error from: {s:?}"),
1475 Err(e) => e,
1476 }
1477 }
1478
1479 fn cycle_modifier_of(f: &PolydatFile) -> BindingModifier {
1480 match &f.statements[0] {
1481 Statement::Binding(b) => b.modifier,
1482 other => panic!("expected cycle binding, got {other:?}"),
1483 }
1484 }
1485
1486 #[test]
1490 fn a_retired_type_spelling_is_refused_with_its_keyword_everywhere_a_type_is_named() {
1491 let positions = [
1492 ("extern x: {T}\n", "extern x: {K}\n"),
1493 ("input x: {T}\n", "input x: {K}\n"),
1494 ("input (a: u64, x: {T})\n", "input (a: u64, x: {K})\n"),
1495 (
1496 "m(a: {T}) -> (b: u64) := {\n b := 1\n}\n",
1497 "m(a: {K}) -> (b: u64) := {\n b := 1\n}\n",
1498 ),
1499 (
1500 "m(a: u64) -> (b: {T}) := {\n b := 1\n}\n",
1501 "m(a: u64) -> (b: {K}) := {\n b := 1\n}\n",
1502 ),
1503 ("shared x: {T} := 1\n", "shared x: {K} := 1\n"),
1504 ("y := x as {T}\n", "y := x as {K}\n"),
1505 ("tile t := \"${x:{T}}\"\n", "tile t := \"${x:{K}}\"\n"),
1506 ];
1507 for (retired, keyword) in [
1508 ("String", "str"),
1509 ("Str", "str"),
1510 ("Json", "json"),
1511 ("Ext", "ext"),
1512 ] {
1513 for (refused, accepted) in positions {
1514 let refused = refused.replace("{T}", retired);
1515 let err = parse_str_err(&refused);
1516 assert!(
1517 err.contains(&format!(
1518 "`{retired}` is no longer a type keyword; write `{keyword}`"
1519 )),
1520 "{refused:?}: {err}"
1521 );
1522 parse_str(&accepted.replace("{K}", keyword));
1523 }
1524 }
1525 }
1526
1527 #[test]
1532 fn a_declaration_naming_no_type_is_refused() {
1533 for src in [
1534 "extern x: strr\n",
1535 "input x: strr\n",
1536 "input (a: u64, x: strr)\n",
1537 "m(a: strr) -> (b: u64) := {\n b := 1\n}\n",
1538 "m(a: u64) -> (b: strr) := {\n b := 1\n}\n",
1539 "shared x: strr := 1\n",
1540 ] {
1541 let err = parse_str_err(src);
1542 assert!(
1543 err.contains("`strr` is not a type keyword"),
1544 "{src:?}: {err}"
1545 );
1546 }
1547 }
1548
1549 #[test]
1550 fn parse_volatile_modifier() {
1551 let f = parse_str("volatile x := 42");
1552 let m = cycle_modifier_of(&f);
1553 assert!(m.is_volatile() && !m.is_const() && !m.is_shared());
1554 }
1555
1556 #[test]
1557 fn parse_modifiers_in_any_order_yields_same_set() {
1558 let m1 = cycle_modifier_of(&parse_str("shared volatile x := 42"));
1559 let m2 = cycle_modifier_of(&parse_str("volatile shared x := 42"));
1560 assert_eq!(
1561 m1, m2,
1562 "ordering shouldn't matter: `shared volatile` and `volatile shared` collapse to the same set"
1563 );
1564 assert!(m1.is_shared() && m1.is_volatile());
1565 }
1566
1567 #[test]
1568 fn parse_rejects_shared_const_in_either_order() {
1569 for src in ["const shared x := 42", "shared const x := 42"] {
1570 let err = parse_str_err(src);
1571 assert!(
1572 err.contains("const") && err.contains("shared"),
1573 "error should name the conflicting keywords: {err}"
1574 );
1575 }
1576 }
1577
1578 #[test]
1579 fn parse_shared_volatile_combination() {
1580 let m = cycle_modifier_of(&parse_str("shared volatile x := 42"));
1581 assert!(m.is_shared() && m.is_volatile() && !m.is_const());
1582 }
1583
1584 #[test]
1585 fn parse_rejects_const_volatile_combo() {
1586 let err = parse_str_err("const volatile x := 42");
1587 assert!(
1588 err.contains("const") && err.contains("volatile"),
1589 "error should name the conflicting keywords: {err}"
1590 );
1591 }
1592
1593 #[test]
1594 fn parse_rejects_volatile_const_combo_same_as_const_volatile() {
1595 let err = parse_str_err("volatile const x := 42");
1597 assert!(err.contains("const") && err.contains("volatile"));
1598 }
1599
1600 #[test]
1601 fn parse_rejects_duplicate_modifier() {
1602 let err = parse_str_err("const const x := 42");
1603 assert!(
1604 err.contains("duplicate"),
1605 "error should call out duplicate: {err}"
1606 );
1607 }
1608
1609 #[test]
1610 fn parse_volatile_const_binding() {
1611 let f = parse_str("volatile x := 42");
1618 match &f.statements[0] {
1619 Statement::Binding(b) => {
1620 assert!(b.modifier.is_volatile());
1621 assert!(!b.modifier.is_const());
1622 }
1623 other => panic!("expected binding, got {other:?}"),
1624 }
1625 }
1626
1627 #[test]
1628 fn parse_input_bare() {
1629 let f = parse_str("input cycle: u64");
1630 assert_eq!(f.statements.len(), 1);
1631 match &f.statements[0] {
1632 Statement::InputDecl(d) => {
1633 assert_eq!(d.name, "cycle");
1634 assert_eq!(d.ty.as_deref(), Some("u64"));
1635 }
1636 other => panic!("expected InputDecl, got {other:?}"),
1637 }
1638 }
1639
1640 #[test]
1641 fn parse_input_bare_untyped() {
1642 let f = parse_str("input cycle");
1643 match &f.statements[0] {
1644 Statement::InputDecl(d) => {
1645 assert_eq!(d.name, "cycle");
1646 assert!(d.ty.is_none(), "no type annotation");
1647 }
1648 other => panic!("expected InputDecl, got {other:?}"),
1649 }
1650 }
1651
1652 #[test]
1653 fn parse_input_tuple_form() {
1654 let f = parse_str("input (cycle: u64, q: f64)");
1657 assert_eq!(f.statements.len(), 2);
1658 match &f.statements[0] {
1659 Statement::InputDecl(d) => {
1660 assert_eq!(d.name, "cycle");
1661 assert_eq!(d.ty.as_deref(), Some("u64"));
1662 }
1663 other => panic!("expected InputDecl, got {other:?}"),
1664 }
1665 match &f.statements[1] {
1666 Statement::InputDecl(d) => {
1667 assert_eq!(d.name, "q");
1668 assert_eq!(d.ty.as_deref(), Some("f64"));
1669 }
1670 other => panic!("expected InputDecl, got {other:?}"),
1671 }
1672 }
1673
1674 #[test]
1675 fn parse_input_tuple_empty_rejected() {
1676 let tokens = crate::lexer::lex("input ()").unwrap();
1678 let err = parse(tokens).unwrap_err();
1679 assert!(
1680 err.contains("empty"),
1681 "error should mention empty tuple: {err}"
1682 );
1683 }
1684
1685 #[test]
1686 fn parse_const_binding() {
1687 let f = parse_str("const lut := dist_normal(72.0, 5.0)");
1688 assert_eq!(f.statements.len(), 1);
1689 match &f.statements[0] {
1690 Statement::Binding(b) => {
1691 assert_eq!(b.targets, vec!["lut"]);
1692 assert!(b.modifier.is_const());
1693 match &b.value {
1694 Expr::Call(c) => {
1695 assert_eq!(c.func, "dist_normal");
1696 assert_eq!(c.args.len(), 2);
1697 }
1698 _ => panic!("expected call"),
1699 }
1700 }
1701 _ => panic!("expected const binding"),
1702 }
1703 }
1704
1705 #[test]
1706 fn parse_cycle_binding() {
1707 let f = parse_str("seed := hash(cycle)");
1708 match &f.statements[0] {
1709 Statement::Binding(b) => {
1710 assert_eq!(b.targets, vec!["seed"]);
1711 match &b.value {
1712 Expr::Call(c) => {
1713 assert_eq!(c.func, "hash");
1714 assert_eq!(c.args.len(), 1);
1715 }
1716 _ => panic!("expected call"),
1717 }
1718 }
1719 _ => panic!("expected cycle binding"),
1720 }
1721 }
1722
1723 #[test]
1724 fn parse_destructuring() {
1725 let f = parse_str("(tenant, device, reading) := mixed_radix(cycle, 100, 1000, 0)");
1726 match &f.statements[0] {
1727 Statement::Binding(b) => {
1728 assert_eq!(b.targets, vec!["tenant", "device", "reading"]);
1729 match &b.value {
1730 Expr::Call(c) => {
1731 assert_eq!(c.func, "mixed_radix");
1732 assert_eq!(c.args.len(), 4);
1733 }
1734 _ => panic!("expected call"),
1735 }
1736 }
1737 _ => panic!("expected cycle binding"),
1738 }
1739 }
1740
1741 #[test]
1742 fn parse_named_args() {
1743 let f = parse_str("const lut := dist_normal(mean: 72.0, stddev: 5.0)");
1744 match &f.statements[0] {
1745 Statement::Binding(b) => match &b.value {
1746 Expr::Call(c) => {
1747 assert!(matches!(&c.args[0], Arg::Named(n, _) if n == "mean"));
1748 assert!(matches!(&c.args[1], Arg::Named(n, _) if n == "stddev"));
1749 }
1750 _ => panic!("expected call"),
1751 },
1752 _ => panic!("expected const binding"),
1753 }
1754 }
1755
1756 #[test]
1757 fn parse_string_lit_plain() {
1758 let f = parse_str(r#"id := "static text""#);
1761 match &f.statements[0] {
1762 Statement::Binding(b) => match &b.value {
1763 Expr::StringLit(s, _) => assert_eq!(s, "static text"),
1764 _ => panic!("expected string lit"),
1765 },
1766 _ => panic!("expected binding"),
1767 }
1768 }
1769
1770 #[test]
1771 fn parse_string_lit_interpolated() {
1772 let f = parse_str(r#"id := "{code}-{seq}""#);
1776 match &f.statements[0] {
1777 Statement::Binding(b) => match &b.value {
1778 Expr::Call(c) => {
1779 assert_eq!(c.func, "printf");
1780 assert_eq!(c.args.len(), 3);
1781 match &c.args[0] {
1782 Arg::Positional(Expr::StringLit(s, _)) => assert_eq!(s, "{}-{}"),
1783 _ => panic!("expected format string as first arg"),
1784 }
1785 match &c.args[1] {
1786 Arg::Positional(Expr::Ident(n, _)) => assert_eq!(n, "code"),
1787 _ => panic!("expected ident `code`"),
1788 }
1789 match &c.args[2] {
1790 Arg::Positional(Expr::Ident(n, _)) => assert_eq!(n, "seq"),
1791 _ => panic!("expected ident `seq`"),
1792 }
1793 }
1794 other => panic!("expected printf call, got {other:?}"),
1795 },
1796 _ => panic!("expected binding"),
1797 }
1798 }
1799
1800 #[test]
1801 fn parse_string_lit_format_spec_left_alone() {
1802 let f = parse_str(r#"id := "x={:05}""#);
1807 match &f.statements[0] {
1808 Statement::Binding(b) => match &b.value {
1809 Expr::StringLit(s, _) => assert_eq!(s, "x={:05}"),
1810 _ => panic!("expected literal"),
1811 },
1812 _ => panic!("expected binding"),
1813 }
1814 }
1815
1816 #[test]
1817 fn parse_string_lit_nested_call() {
1818 let f = parse_str(r#"email := "{format_u64(hash(cycle), 10)}@example.com""#);
1821 let call = match &f.statements[0] {
1822 Statement::Binding(b) => match &b.value {
1823 Expr::Call(c) => c,
1824 other => panic!("expected printf call, got {other:?}"),
1825 },
1826 _ => panic!("expected binding"),
1827 };
1828 assert_eq!(call.func, "printf");
1829 assert_eq!(call.args.len(), 2);
1830 match &call.args[0] {
1831 Arg::Positional(Expr::StringLit(s, _)) => assert_eq!(s, "{}@example.com"),
1832 other => panic!("expected format string, got {other:?}"),
1833 }
1834 match &call.args[1] {
1835 Arg::Positional(Expr::Call(inner)) => {
1836 assert_eq!(inner.func, "format_u64");
1837 assert_eq!(inner.args.len(), 2);
1838 match &inner.args[0] {
1839 Arg::Positional(Expr::Call(h)) => assert_eq!(h.func, "hash"),
1840 other => panic!("expected hash(...) call, got {other:?}"),
1841 }
1842 match &inner.args[1] {
1843 Arg::Positional(Expr::IntLit(10, _)) => {}
1844 other => panic!("expected literal 10, got {other:?}"),
1845 }
1846 }
1847 other => panic!("expected format_u64 call, got {other:?}"),
1848 }
1849 }
1850
1851 #[test]
1852 fn parse_string_lit_arithmetic_in_placeholder() {
1853 let f = parse_str(r#"id := "x={a + b * 2}""#);
1856 let call = match &f.statements[0] {
1857 Statement::Binding(b) => match &b.value {
1858 Expr::Call(c) => c,
1859 other => panic!("expected call, got {other:?}"),
1860 },
1861 _ => panic!("expected binding"),
1862 };
1863 assert_eq!(call.func, "printf");
1864 match &call.args[1] {
1865 Arg::Positional(Expr::BinOp(_, BinOpKind::Add, _)) => {}
1866 other => panic!("expected addition, got {other:?}"),
1867 }
1868 }
1869
1870 #[test]
1871 fn parse_string_lit_field_access() {
1872 let f = parse_str(r#"k := "row {row.id}""#);
1874 let call = match &f.statements[0] {
1875 Statement::Binding(b) => match &b.value {
1876 Expr::Call(c) => c,
1877 other => panic!("expected call, got {other:?}"),
1878 },
1879 _ => panic!("expected binding"),
1880 };
1881 assert_eq!(call.func, "printf");
1882 match &call.args[1] {
1883 Arg::Positional(Expr::FieldAccess { source, field, .. }) => {
1884 assert_eq!(source, "row");
1885 assert_eq!(field, "id");
1886 }
1887 other => panic!("expected field access, got {other:?}"),
1888 }
1889 }
1890
1891 #[test]
1892 fn parse_string_lit_escaped_braces() {
1893 let f = parse_str(r#"k := "{{not a placeholder}} but {real}""#);
1897 let call = match &f.statements[0] {
1898 Statement::Binding(b) => match &b.value {
1899 Expr::Call(c) => c,
1900 other => panic!("expected call, got {other:?}"),
1901 },
1902 _ => panic!("expected binding"),
1903 };
1904 match &call.args[0] {
1905 Arg::Positional(Expr::StringLit(s, _)) => {
1906 assert_eq!(s, "{{not a placeholder}} but {}");
1907 }
1908 other => panic!("expected fmt string, got {other:?}"),
1909 }
1910 match &call.args[1] {
1911 Arg::Positional(Expr::Ident(n, _)) => assert_eq!(n, "real"),
1912 other => panic!("expected ident `real`, got {other:?}"),
1913 }
1914 }
1915
1916 #[test]
1917 fn parse_string_lit_unterminated_falls_back() {
1918 let f = parse_str(r#"k := "missing close {abc""#);
1920 match &f.statements[0] {
1921 Statement::Binding(b) => match &b.value {
1922 Expr::StringLit(s, _) => assert_eq!(s, "missing close {abc"),
1923 other => panic!("expected literal, got {other:?}"),
1924 },
1925 _ => panic!("expected binding"),
1926 }
1927 }
1928
1929 #[test]
1930 fn parse_string_lit_parens_in_placeholder() {
1931 let f = parse_str(r#"k := "{abs(x - y)}""#);
1935 let call = match &f.statements[0] {
1936 Statement::Binding(b) => match &b.value {
1937 Expr::Call(c) => c,
1938 other => panic!("expected call, got {other:?}"),
1939 },
1940 _ => panic!("expected binding"),
1941 };
1942 assert_eq!(call.func, "printf");
1943 match &call.args[1] {
1944 Arg::Positional(Expr::Call(inner)) => assert_eq!(inner.func, "abs"),
1945 other => panic!("expected abs call, got {other:?}"),
1946 }
1947 }
1948
1949 #[test]
1950 fn parse_array_lit() {
1951 let f = parse_str("const weights := [60.0, 20.0, 15.0, 5.0]");
1952 match &f.statements[0] {
1953 Statement::Binding(b) => match &b.value {
1954 Expr::ArrayLit(elems, _) => assert_eq!(elems.len(), 4),
1955 _ => panic!("expected array lit"),
1956 },
1957 _ => panic!("expected const binding"),
1958 }
1959 }
1960
1961 #[test]
1962 fn parse_nested_call() {
1963 let f = parse_str("x := hash(interleave(a, b))");
1964 match &f.statements[0] {
1965 Statement::Binding(b) => match &b.value {
1966 Expr::Call(c) => {
1967 assert_eq!(c.func, "hash");
1968 assert_eq!(c.args.len(), 1);
1969 match &c.args[0] {
1970 Arg::Positional(Expr::Call(inner)) => {
1971 assert_eq!(inner.func, "interleave");
1972 assert_eq!(inner.args.len(), 2);
1973 }
1974 _ => panic!("expected nested call"),
1975 }
1976 }
1977 _ => panic!("expected call"),
1978 },
1979 _ => panic!("expected binding"),
1980 }
1981 }
1982
1983 #[test]
1984 fn parse_full_program() {
1985 let src = r#"
1986 // Const bindings (compile-time fold or scope-init pull)
1987 const temp_lut := dist_normal(mean: 72.0, stddev: 5.0)
1988 const weights := [60.0, 20.0, 15.0]
1989
1990 // Cycle bindings (per-cycle eval)
1991 input cycle: u64
1992 (tenant, device) := mixed_radix(cycle, 100, 0)
1993 tenant_h := hash(tenant)
1994 code := mod(tenant_h, 10000)
1995 device_id := "{code}-{seq}"
1996 "#;
1997 let f = parse_str(src);
1998 assert_eq!(f.statements.len(), 7);
1999 }
2000
2001 #[test]
2002 fn parse_mixed_positional_named() {
2003 let f = parse_str("const lut := dist_normal(72.0, 5.0, resolution: 2000)");
2004 match &f.statements[0] {
2005 Statement::Binding(b) => match &b.value {
2006 Expr::Call(c) => {
2007 assert!(matches!(&c.args[0], Arg::Positional(_)));
2008 assert!(matches!(&c.args[1], Arg::Positional(_)));
2009 assert!(matches!(&c.args[2], Arg::Named(n, _) if n == "resolution"));
2010 }
2011 _ => panic!("expected call"),
2012 },
2013 _ => panic!("expected const binding"),
2014 }
2015 }
2016
2017 #[test]
2018 fn parse_simple_addition() {
2019 let f = parse_str("y := a + b");
2020 match &f.statements[0] {
2021 Statement::Binding(b) => match &b.value {
2022 Expr::BinOp(lhs, BinOpKind::Add, rhs) => {
2023 assert!(matches!(**lhs, Expr::Ident(ref s, _) if s == "a"));
2024 assert!(matches!(**rhs, Expr::Ident(ref s, _) if s == "b"));
2025 }
2026 _ => panic!("expected BinOp Add, got {:?}", b.value),
2027 },
2028 _ => panic!("expected cycle binding"),
2029 }
2030 }
2031
2032 #[test]
2033 fn parse_precedence_mul_over_add() {
2034 let f = parse_str("y := a + b * c");
2036 match &f.statements[0] {
2037 Statement::Binding(b) => match &b.value {
2038 Expr::BinOp(lhs, BinOpKind::Add, rhs) => {
2039 assert!(matches!(**lhs, Expr::Ident(ref s, _) if s == "a"));
2040 match &**rhs {
2041 Expr::BinOp(rl, BinOpKind::Mul, rr) => {
2042 assert!(matches!(**rl, Expr::Ident(ref s, _) if s == "b"));
2043 assert!(matches!(**rr, Expr::Ident(ref s, _) if s == "c"));
2044 }
2045 _ => panic!("expected inner Mul"),
2046 }
2047 }
2048 _ => panic!("expected outer Add"),
2049 },
2050 _ => panic!("expected cycle binding"),
2051 }
2052 }
2053
2054 #[test]
2055 fn parse_parenthesized_grouping() {
2056 let f = parse_str("y := (a + b) * c");
2058 match &f.statements[0] {
2059 Statement::Binding(b) => {
2060 match &b.value {
2061 Expr::BinOp(lhs, BinOpKind::Mul, rhs) => {
2062 match &**lhs {
2063 Expr::BinOp(_, BinOpKind::Add, _) => {} _ => panic!("expected inner Add in lhs"),
2065 }
2066 assert!(matches!(**rhs, Expr::Ident(ref s, _) if s == "c"));
2067 }
2068 _ => panic!("expected outer Mul"),
2069 }
2070 }
2071 _ => panic!("expected cycle binding"),
2072 }
2073 }
2074
2075 fn if_call(src: &str) -> CallExpr {
2077 let f = parse_str(src);
2078 match &f.statements[0] {
2079 Statement::Binding(b) => match &b.value {
2080 Expr::Call(c) => {
2081 assert_eq!(
2082 c.func, "if",
2083 "block form must desugar to the `if` intrinsic"
2084 );
2085 assert_eq!(c.args.len(), 3, "if intrinsic takes (cond, then, else)");
2086 c.clone()
2087 }
2088 other => panic!("expected Call, got {:?}", other),
2089 },
2090 _ => panic!("expected binding"),
2091 }
2092 }
2093
2094 #[test]
2095 fn if_block_desugars_to_the_call_intrinsic() {
2096 let block = if_call("y := if c { a } else { b }");
2100 let call = if_call("y := if(c, a, b)");
2101 for (i, (bl, ca)) in block.args.iter().zip(call.args.iter()).enumerate() {
2102 match (bl, ca) {
2103 (Arg::Positional(Expr::Ident(x, _)), Arg::Positional(Expr::Ident(y, _))) => {
2104 assert_eq!(x, y, "arg {} differs between block and call form", i);
2105 }
2106 _ => panic!("expected plain idents in both forms"),
2107 }
2108 }
2109 }
2110
2111 #[test]
2112 fn if_block_accepts_expressions_in_condition_and_branches() {
2113 let c = if_call("y := if segments > 0 { total / segments } else { 0 }");
2114 assert!(
2115 matches!(
2116 &c.args[0],
2117 Arg::Positional(Expr::BinOp(_, BinOpKind::Gt, _))
2118 ),
2119 "condition should parse as a full expression"
2120 );
2121 assert!(
2122 matches!(
2123 &c.args[1],
2124 Arg::Positional(Expr::BinOp(_, BinOpKind::Div, _))
2125 ),
2126 "then-branch should parse as a full expression"
2127 );
2128 }
2129
2130 #[test]
2131 fn if_block_chains_else_if() {
2132 let c = if_call("y := if a { 1 } else if b { 2 } else { 3 }");
2134 match &c.args[2] {
2135 Arg::Positional(Expr::Call(inner)) => {
2136 assert_eq!(inner.func, "if");
2137 assert!(matches!(
2138 &inner.args[1],
2139 Arg::Positional(Expr::IntLit(2, _))
2140 ));
2141 assert!(matches!(
2142 &inner.args[2],
2143 Arg::Positional(Expr::IntLit(3, _))
2144 ));
2145 }
2146 other => panic!("expected nested if in else position, got {:?}", other),
2147 }
2148 }
2149
2150 #[test]
2151 fn if_block_nests_inside_other_expressions() {
2152 let f = parse_str("y := 1 + if c { 2 } else { 3 }");
2154 match &f.statements[0] {
2155 Statement::Binding(b) => match &b.value {
2156 Expr::BinOp(_, BinOpKind::Add, rhs) => {
2157 assert!(matches!(**rhs, Expr::Call(ref c) if c.func == "if"));
2158 }
2159 other => panic!("expected Add with an if on the rhs, got {:?}", other),
2160 },
2161 _ => panic!("expected binding"),
2162 }
2163 }
2164
2165 #[test]
2166 fn if_call_form_still_parses_as_a_call() {
2167 let c = if_call("y := if(c, a, b)");
2169 assert_eq!(c.args.len(), 3);
2170 }
2171
2172 #[test]
2173 fn if_block_requires_else() {
2174 let err = parse_str_err("y := if c { a }");
2177 assert!(
2178 err.contains("else"),
2179 "error should name the missing else: {}",
2180 err
2181 );
2182 }
2183
2184 #[test]
2185 fn if_block_reports_a_missing_brace_helpfully() {
2186 let err = parse_str_err("y := if c a else b");
2187 assert!(
2188 err.contains("if <cond>"),
2189 "error should show the block form: {}",
2190 err
2191 );
2192 }
2193
2194 #[test]
2195 fn parse_unary_negation() {
2196 let f = parse_str("y := -x");
2197 match &f.statements[0] {
2198 Statement::Binding(b) => match &b.value {
2199 Expr::UnaryNeg(inner, _) => {
2200 assert!(matches!(**inner, Expr::Ident(ref s, _) if s == "x"));
2201 }
2202 _ => panic!("expected UnaryNeg"),
2203 },
2204 _ => panic!("expected cycle binding"),
2205 }
2206 }
2207
2208 #[test]
2209 fn parse_func_call_with_infix_arg() {
2210 let f = parse_str("y := sin(cycle * 0.25)");
2212 match &f.statements[0] {
2213 Statement::Binding(b) => match &b.value {
2214 Expr::Call(c) => {
2215 assert_eq!(c.func, "sin");
2216 assert_eq!(c.args.len(), 1);
2217 match &c.args[0] {
2218 Arg::Positional(Expr::BinOp(_, BinOpKind::Mul, _)) => {}
2219 _ => panic!("expected Mul inside sin() arg"),
2220 }
2221 }
2222 _ => panic!("expected call"),
2223 },
2224 _ => panic!("expected cycle binding"),
2225 }
2226 }
2227
2228 #[test]
2229 fn parse_power_right_associative() {
2230 let f = parse_str("y := a ** b ** c");
2232 match &f.statements[0] {
2233 Statement::Binding(b) => match &b.value {
2234 Expr::BinOp(lhs, BinOpKind::Pow, rhs) => {
2235 assert!(matches!(**lhs, Expr::Ident(ref s, _) if s == "a"));
2236 match &**rhs {
2237 Expr::BinOp(rl, BinOpKind::Pow, rr) => {
2238 assert!(matches!(**rl, Expr::Ident(ref s, _) if s == "b"));
2239 assert!(matches!(**rr, Expr::Ident(ref s, _) if s == "c"));
2240 }
2241 _ => panic!("expected inner Pow"),
2242 }
2243 }
2244 _ => panic!("expected outer Pow"),
2245 },
2246 _ => panic!("expected cycle binding"),
2247 }
2248 }
2249
2250 #[test]
2251 fn parse_negate_function_call() {
2252 let f = parse_str("y := -sin(x)");
2254 match &f.statements[0] {
2255 Statement::Binding(b) => match &b.value {
2256 Expr::UnaryNeg(inner, _) => match &**inner {
2257 Expr::Call(c) => assert_eq!(c.func, "sin"),
2258 _ => panic!("expected Call inside UnaryNeg"),
2259 },
2260 _ => panic!("expected UnaryNeg"),
2261 },
2262 _ => panic!("expected cycle binding"),
2263 }
2264 }
2265
2266 #[test]
2267 fn parse_all_operators() {
2268 let f = parse_str("y := a + b - c * d / e % f ** g");
2270 match &f.statements[0] {
2271 Statement::Binding(_) => {} _ => panic!("expected cycle binding"),
2273 }
2274 }
2275
2276 #[test]
2277 fn parse_star_star_power() {
2278 let f = parse_str("y := x ** 2.0");
2280 match &f.statements[0] {
2281 Statement::Binding(b) => match &b.value {
2282 Expr::BinOp(lhs, BinOpKind::Pow, rhs) => {
2283 assert!(matches!(**lhs, Expr::Ident(ref s, _) if s == "x"));
2284 assert!(matches!(**rhs, Expr::FloatLit(v, _) if v == 2.0));
2285 }
2286 _ => panic!("expected BinOp Pow, got {:?}", b.value),
2287 },
2288 _ => panic!("expected cycle binding"),
2289 }
2290 }
2291
2292 #[test]
2293 fn parse_caret_is_xor() {
2294 let f = parse_str("y := a ^ b");
2296 match &f.statements[0] {
2297 Statement::Binding(b) => match &b.value {
2298 Expr::BinOp(lhs, BinOpKind::BitXor, rhs) => {
2299 assert!(matches!(**lhs, Expr::Ident(ref s, _) if s == "a"));
2300 assert!(matches!(**rhs, Expr::Ident(ref s, _) if s == "b"));
2301 }
2302 _ => panic!("expected BinOp BitXor, got {:?}", b.value),
2303 },
2304 _ => panic!("expected cycle binding"),
2305 }
2306 }
2307
2308 #[test]
2309 fn parse_bitand_binds_tighter_than_bitor() {
2310 let f = parse_str("y := a & b | c");
2312 match &f.statements[0] {
2313 Statement::Binding(b) => {
2314 match &b.value {
2315 Expr::BinOp(lhs, BinOpKind::BitOr, rhs) => {
2316 match &**lhs {
2317 Expr::BinOp(_, BinOpKind::BitAnd, _) => {} _ => panic!("expected inner BitAnd in lhs"),
2319 }
2320 assert!(matches!(**rhs, Expr::Ident(ref s, _) if s == "c"));
2321 }
2322 _ => panic!("expected outer BitOr"),
2323 }
2324 }
2325 _ => panic!("expected cycle binding"),
2326 }
2327 }
2328
2329 #[test]
2330 fn parse_shift_left() {
2331 let f = parse_str("y := a << 4");
2333 match &f.statements[0] {
2334 Statement::Binding(b) => match &b.value {
2335 Expr::BinOp(lhs, BinOpKind::Shl, rhs) => {
2336 assert!(matches!(**lhs, Expr::Ident(ref s, _) if s == "a"));
2337 assert!(matches!(**rhs, Expr::IntLit(4, _)));
2338 }
2339 _ => panic!("expected BinOp Shl, got {:?}", b.value),
2340 },
2341 _ => panic!("expected cycle binding"),
2342 }
2343 }
2344
2345 #[test]
2346 fn parse_cursor_without_over_clause() {
2347 let f = parse_str("cursor q = range(0, 100)");
2348 match &f.statements[0] {
2349 Statement::Cursor(c) => {
2350 assert_eq!(c.name, "q");
2351 assert!(c.over.is_none(), "no `over` → over is None");
2352 }
2353 other => panic!("expected Cursor, got {other:?}"),
2354 }
2355 }
2356
2357 #[test]
2358 fn parse_cursor_with_over_iter_var() {
2359 let f = parse_str("cursor q = range(0, 100) over p");
2360 match &f.statements[0] {
2361 Statement::Cursor(c) => {
2362 assert_eq!(c.name, "q");
2363 match &c.over {
2364 Some(Expr::Ident(name, _)) => assert_eq!(name, "p"),
2365 other => panic!("expected Some(Ident('p')), got {other:?}"),
2366 }
2367 }
2368 other => panic!("expected Cursor, got {other:?}"),
2369 }
2370 }
2371
2372 #[test]
2373 fn parse_cursor_with_over_dotted_param_projection() {
2374 let f = parse_str("cursor q = range(0, 100) over cursor.partitions");
2375 match &f.statements[0] {
2376 Statement::Cursor(c) => {
2377 assert!(c.over.is_some(), "should have over clause");
2378 match &c.over {
2380 Some(Expr::FieldAccess { .. }) => {} Some(other) => panic!("expected FieldAccess, got {other:?}"),
2382 None => panic!("expected Some"),
2383 }
2384 }
2385 other => panic!("expected Cursor, got {other:?}"),
2386 }
2387 }
2388
2389 #[test]
2390 fn parse_cursor_over_does_not_swallow_following_statement() {
2391 let f = parse_str("cursor q = range(0, 100) over p\nother := 42");
2392 assert_eq!(f.statements.len(), 2);
2393 }
2394
2395 #[test]
2396 fn parse_chained_field_access_flattens_intermediate_levels() {
2397 let f = parse_str("i := q.cursor.idx");
2402 match &f.statements[0] {
2403 Statement::Binding(b) => match &b.value {
2404 Expr::FieldAccess { source, field, .. } => {
2405 assert_eq!(source, "q__cursor");
2406 assert_eq!(field, "idx");
2407 }
2408 other => panic!("expected FieldAccess, got {other:?}"),
2409 },
2410 other => panic!("expected binding, got {other:?}"),
2411 }
2412 let f = parse_str("x := a.b.c.d");
2414 match &f.statements[0] {
2415 Statement::Binding(b) => match &b.value {
2416 Expr::FieldAccess { source, field, .. } => {
2417 assert_eq!(source, "a__b__c");
2418 assert_eq!(field, "d");
2419 }
2420 other => panic!("expected FieldAccess, got {other:?}"),
2421 },
2422 other => panic!("expected binding, got {other:?}"),
2423 }
2424 }
2425
2426 #[test]
2427 fn parse_unary_bitnot() {
2428 let f = parse_str("y := !x");
2430 match &f.statements[0] {
2431 Statement::Binding(b) => match &b.value {
2432 Expr::UnaryBitNot(inner, _) => {
2433 assert!(matches!(**inner, Expr::Ident(ref s, _) if s == "x"));
2434 }
2435 _ => panic!("expected UnaryBitNot, got {:?}", b.value),
2436 },
2437 _ => panic!("expected cycle binding"),
2438 }
2439 }
2440}