Skip to main content

polydat_grammar/
parser.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Recursive descent parser for the Polydat DSL.
5//!
6//! Parses a token stream (from the lexer) into an AST.
7//! Infix arithmetic expressions (`+`, `-`, `*`, `/`, `%`, `^`) are
8//! handled by a Pratt (precedence-climbing) parser that produces
9//! `Expr::BinOp` nodes, later desugared by the compiler into
10//! function calls.
11//!
12//! ## String interpolation
13//!
14//! String literals containing `{ … }` placeholders
15//! (polydat_grammar.md §9) are desugared to a `printf` call over
16//! the placeholder bodies. The bodies are parsed as full Polydat
17//! expressions via [`parse_expression`] — same entry the rest of
18//! the language uses — so anything that can appear on a binding
19//! right-hand side can appear inside a placeholder.
20//!
21//! Examples:
22//!
23//! - `"hello"` — no placeholders → `Expr::StringLit("hello")`.
24//! - `"{name}"` — bare identifier → `printf("{}", name)`.
25//! - `"x={a + b}"` — infix expression → `printf("x={}", a + b)`.
26//! - `"{format_u64(hash(cycle), 10)}@example.com"` — nested call
27//!   → `printf("{}@example.com", format_u64(hash(cycle), 10))`.
28//! - `"{row.id}"` — field access → `printf("{}", row.id)`.
29//! - `"{{literal braces}}"` — escaped → stays a `StringLit` (printf
30//!   emits `{` / `}` from `{{` / `}}` at format time).
31//! - `"x={:05}"` — printf format spec, not a Polydat expression → stays
32//!   a `StringLit`; the user is calling printf by hand.
33//! - `"missing close {abc"` — unterminated placeholder → stays a
34//!   `StringLit`.
35//!
36//! The desugaring is pure syntactic sugar. The resulting `printf`
37//! call goes through the standard binding/assembly path: each
38//! placeholder expression compiles to a node, the printf node
39//! ingests their outputs as wires, and at evaluation time
40//! `Value::to_display_string()` renders each input into its slot.
41//! No special runtime support is needed beyond `printf`.
42
43use crate::ast::*;
44use crate::lexer::{Span, Token, TokenKind};
45
46/// Parser state.
47struct Parser {
48    tokens: Vec<Token>,
49    pos: usize,
50    /// The delimiters and sigil a tile is read under when it names
51    /// none of its own: the host's, when one supplied them.
52    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            // `input` is a soft keyword: at statement start it's a
101            // declaration, elsewhere (module-signature param names,
102            // call-site named args, body references like `hash(input)`)
103            // it is a plain identifier. This mirrors the convention
104            // in `nbrs/stdlib/modeling.polydat` where `input:` is the
105            // canonical parameter name for cycle-driven modules.
106            TokenKind::Input => {
107                self.advance();
108                Ok("input".to_string())
109            }
110            // `cursor` is a soft keyword (cursor_partitions.md §7.2).
111            // At statement start
112            // it opens a `cursor q = …` decl; in identifier position
113            // (param names, binding LHS, body references) it's the
114            // workload-level cursor parameter.
115            TokenKind::Cursor => {
116                self.advance();
117                Ok("cursor".to_string())
118            }
119            // `over` is a soft keyword used only by the cursor-decl
120            // syntax (cursor_partitions.md §7.2). In identifier
121            // position it's a plain identifier, so a wire may be
122            // named `over`.
123            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    /// Expect a type name: an identifier that is a type keyword
137    /// ([`crate::PortType::from_keyword`]). Any other name is refused
138    /// where it is written: a spelling polydat retired with the keyword
139    /// to write instead ([`crate::PortType::retired_keyword`]), and any
140    /// other name as not a type keyword, so no declaration compiles
141    /// with a type that does not exist.
142    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
161/// Parse a token stream into a PolydatFile AST.
162pub fn parse(tokens: Vec<Token>) -> Result<PolydatFile, String> {
163    parse_with_tile_defaults(tokens, &TileOptions::default())
164}
165
166/// [`parse`] reading every tile that names no delimiters or sigil of
167/// its own under `tile_defaults`.
168///
169/// A tile body is raw text until it is read, and what it means depends
170/// on the delimiters it is read under, so a host that supplies its own
171/// supplies them here rather than re-reading afterwards: the text is
172/// admitted once, under the reading that was intended. A tile that
173/// names any delimiter of its own keeps all of them.
174pub 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
189/// Parse a token stream as a single Polydat expression.
190///
191/// Used by string-interpolation desugaring to compile placeholder
192/// bodies (`{ … }` inside string literals) the same way any
193/// other binding right-hand side is compiled. Identifiers,
194/// nested function calls, infix arithmetic, and field access
195/// all work uniformly because this is the same `parse_expr`
196/// entry the compiler uses elsewhere.
197///
198/// ```text
199/// // "{format_u64(hash(cycle), 10)}" → printf("{}", format_u64(hash(cycle), 10))
200/// // "{a + b}"                       → printf("{}", a + b)
201/// ```
202///
203/// Returns an error if the tokens don't form a single complete
204/// expression, or if there are trailing tokens after the
205/// expression ends.
206pub 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
221/// Parse one statement and append the resulting AST node(s) to
222/// `out`. Most statement kinds map 1-to-1, but the tuple form of
223/// `input (a: u64, b: f64)` desugars into N `InputDecl` statements
224/// at parse time — hence the `Vec` sink rather than a single
225/// return value.
226fn 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            // Lookahead to distinguish:
240            //   name := expr              → cycle binding
241            //   name(p: type) -> ... := { → module def
242            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
262/// `for <source> { statements }` (for_traversal.md §2).
263///
264/// The lexer already captured the source text. A bare identifier names
265/// a bound producer; anything else is comprehension text handed to the
266/// comprehension parser, so the traversal grammar has one owner.
267fn 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
296/// `tile name [: encoding] [(options)] := body` (polytile.md §2.1).
297///
298/// The lexer captured block and heredoc bodies raw into a `TileBody`
299/// token; a string-literal body arrives as an ordinary string token.
300fn 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    // A tile binds a wire, so `:=` precedes every body form; the lexer
351    // captures a block or heredoc body right after it.
352    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
398/// `name := polytile(...)` or `name := polytile_json(...)`: a tile
399/// whose body arrives as an argument (polytile.md §5.6).
400fn 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
408/// `name := polytile("<encoding>", "<template>" [, open: "..", close: "..", sigil: ".."])`
409/// `name := polytile_json("<structural json>" [, options])`
410///
411/// The body is a string literal or a heredoc, taken raw: it is
412/// compiled as a template, never evaluated, so interpolation inside it
413/// belongs to the tile. This is the form a host that only holds strings
414/// emits as a program transform.
415fn 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
492/// Classify and parse the text after `for`.
493pub 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    // A derivation: `<producer> [where <pred>] [order <spec>]`. The
520    // head is a bare identifier and the text has no `in` clause.
521    {
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    // Built through the constructor, which refuses a tree the text
539    // cannot write back. Text this parser accepts should always be
540    // writable, so a refusal here is a round-trip gap between the two
541    // halves of the comprehension grammar rather than an author error,
542    // and says so.
543    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
560/// Lookahead: is this a module def? Pattern: ident ( ident : ident ...
561fn is_module_def(p: &Parser) -> bool {
562    // Need at least: ident ( <param-name> : type
563    // The param name accepts plain idents AND the soft keyword
564    // `input` (canonical for cycle-driven modules — see
565    // `nbrs/stdlib/modeling.polydat`).
566    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
579/// `name(param: type, ...) -> (output: type, ...) := { body }`
580fn parse_module_def(p: &mut Parser) -> Result<Statement, String> {
581    let span = p.span();
582    let name = p.expect_ident()?;
583
584    // Parse params: (name: type, ...)
585    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    // Parse -> (output: type, ...)
602    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    // Parse := { body }
620    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
638/// `extern name: type = default`
639fn parse_extern_port(p: &mut Parser) -> Result<Statement, String> {
640    let span = p.span();
641    p.advance(); // consume 'extern'
642
643    let name = p.expect_ident()?;
644    p.expect(&TokenKind::Colon)?;
645    let typ = p.expect_type_name()?;
646
647    // Optional default: = expr
648    let default = if matches!(p.peek(), TokenKind::Eq) {
649        p.advance(); // consume '='
650        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
663/// Parse an `input` declaration. Two surface forms, both emit one
664/// [`Statement::InputDecl`] per declared slot:
665///
666/// - `input <name>[: <type>]` — bare single
667/// - `input (<name>[: <type>][, ...])` — tuple form mirroring the
668///   module-signature param-list shape (see
669///   a host-provided cycle module). Desugars to N InputDecls.
670///
671/// Empty tuple `input ()` is rejected — declare zero inputs by
672/// simply omitting the `input` line.
673fn parse_input_decl(p: &mut Parser, out: &mut Vec<Statement>) -> Result<(), String> {
674    let keyword_span = p.span();
675    p.advance(); // consume 'input'
676
677    if matches!(p.peek(), TokenKind::LParen) {
678        // Tuple form: input (a: u64, b: f64, ...)
679        p.advance(); // consume '('
680        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        // Bare form: input name[: type]
706        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
719/// `cursor name = Cursor()` or `cursor name = expr [over partition_source]`
720///
721/// The trailing `over <expr>` clause (cursor_partitions.md §7.2) names a partition
722/// source the cursor narrows by — see [`CursorDecl::over`].
723fn parse_cursor_decl(p: &mut Parser) -> Result<Statement, String> {
724    let span = p.span();
725    p.advance(); // consume 'cursor'
726    let name = p.expect_ident()?;
727    p.expect(&TokenKind::Eq)?;
728    let constructor = parse_expr(p)?;
729    // Optional `over <expr>` clause — partition narrowing source.
730    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
744/// `<modifier>* name := expr` where each modifier ∈ {const,
745/// shared, volatile, ...}. Modifiers may appear in any order;
746/// duplicates and the contradictory `const` + `volatile` and
747/// `const` + `shared` combos are rejected (see
748/// [`BindingModifier::try_from_iter`]).
749fn 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        // Soft keywords (`input`, `cursor`, `over`) and regular
776        // identifiers are all accepted as binding names. The
777        // soft-keyword recognition lives in `expect_ident`; this
778        // guard just dispatches to the binding-with-modifier
779        // path when the upcoming token can serve as an ident.
780        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
791/// `name := expr`
792fn 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    // Optional type annotation — `shared name: f64 := expr`. Pins the
803    // shared CELL's type for life (scope_model.md §"Type stability");
804    // literal inference (`1` vs `1.0`) stops being load-bearing. Only
805    // `shared` bindings carry a cell whose type the annotation can pin,
806    // so it is rejected elsewhere rather than silently ignored.
807    let type_annotation = if matches!(p.peek(), TokenKind::Colon) {
808        p.advance(); // consume ':'
809        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
832/// `(a, b, c) := expr`
833fn parse_destructuring_binding(p: &mut Parser) -> Result<Statement, String> {
834    let span = p.span();
835    p.advance(); // consume '('
836    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
858/// Parse an expression with operator precedence (Pratt parsing).
859///
860/// Handles infix arithmetic operators (`+`, `-`, `*`, `/`, `%`, `^`)
861/// with correct precedence and associativity. Atoms are literals,
862/// identifiers, function calls, parenthesized groups, and unary negation.
863fn parse_expr(p: &mut Parser) -> Result<Expr, String> {
864    parse_expr_bp(p, 0)
865}
866
867/// Pratt parser core: parse expression with minimum binding power.
868///
869/// Precedence levels (lowest to highest):
870///   Level 0a: `||` (logical Or)      — bp (1, 2)
871///   Level 0b: `&&` (logical And)     — bp (3, 4)
872///   Level 1: `==` `!=`               — bp (5, 6)
873///   Level 2: `<` `>` `<=` `>=`       — bp (7, 8)
874///   Level 3: `|`  (BitOr)            — bp (9, 10)
875///   Level 4: `^`  (BitXor)           — bp (11, 12)
876///   Level 5: `&`  (BitAnd)           — bp (13, 14)
877///   Level 6: `<<` `>>` (Shl/Shr)     — bp (15, 16)
878///   Level 7: `+` `-` (Add/Sub)       — bp (17, 18)
879///   Level 8: `*` `/` `%`             — bp (19, 20)
880///   Level 9: `**` (Pow, right)       — bp (22, 21)
881///   Level 10: `-` `!` (unary, in parse_atom)
882///
883/// `||` / `&&` sit *below* comparison (polydat_grammar.md §6.1,
884/// §7; the lowest
885/// bands) so `a > b && c > d` parses as `(a > b) && (c > d)`, and
886/// `||` binds looser than `&&` (C/Rust convention). Comparison ops
887/// sit below arithmetic/bitwise so `a + b < c * d` parses as
888/// `(a + b) < (c * d)`; equality below relational so `a < b == c`
889/// parses as `(a < b) == c`.
890fn parse_expr_bp(p: &mut Parser, min_bp: u8) -> Result<Expr, String> {
891    let mut lhs = parse_atom(p)?;
892    // The `as <type>` postfix cast (polydat_grammar.md §10) binds tightly to the
893    // atom (Rust convention): `a + b as u64` is `a + (b as u64)`;
894    // parenthesise to cast a whole sub-expression.
895    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(); // consume operator token
904        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
911/// The binary operator a token spells, if it spells one.
912pub 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
937/// The binding powers `(left, right)` of a binary operator: the one
938/// precedence table of the language (polydat_grammar.md §6.1), whose
939/// levels `parse_expr_bp` lists. Expressions and comprehension `where` predicates
940/// ([`crate::comprehension::predicate`]) both parse with it. A higher
941/// power binds tighter; `left < right` associates to the left and
942/// `left > right` to the right. The unary operators `-` and `!` bind
943/// tighter than every binary operator: each applies to the atom after
944/// it.
945pub 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
961/// Parse trailing `as <type>` casts on an expression (polydat_grammar.md §10).
962/// `as` is a *soft* keyword (contextual): only the postfix `as <type>`
963/// form is a cast; `as` is otherwise a normal identifier.
964fn 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(); // consume `as`
968        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(); // consume the type name
973        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
982/// Parse an atomic expression: literal, identifier, function call,
983/// parenthesized group, or unary negation.
984/// Parses the block form of conditional selection:
985/// `if <cond> { <then> } else { <else> }`, including `else if` chains.
986///
987/// This is **surface sugar only**. It desugars here, at parse time, into the
988/// existing `if(cond, then, else)` call intrinsic, exactly as `a + b` is sugar
989/// for `u64_add(a, b)`. Everything downstream is therefore inherited rather than
990/// duplicated: branch-type dispatch (Str > F64 > U64), automatic u64→f64
991/// widening of the narrower branch, and the compiled `select_*` node selection
992/// all live in `binding.rs`'s desugar and behave identically for both spellings.
993///
994/// Two semantic points that follow from Polydat being a dataflow kernel language
995/// rather than an imperative one, and which the block syntax deliberately does
996/// not pretend otherwise about:
997///
998/// * **Both branches always evaluate.** There is no short-circuit; `select_*`
999///   picks between two values that have both already been computed. A branch is
1000///   not a guard, so it cannot be used to avoid a division by zero or an
1001///   out-of-range read on the untaken side.
1002/// * **`else` is mandatory.** Every Polydat expression yields a value and there
1003///   is no unit type, so a one-armed `if` would have nothing to produce when the
1004///   condition is false.
1005fn 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    // `else if ...` chains by recursing: the else-branch is itself an if-expression.
1039    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    // Desugar to the call intrinsic; `binding.rs` handles it from here.
1062    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            // Unary negation: `-expr`
1079            p.advance();
1080            let inner = parse_atom(p)?;
1081            Ok(Expr::UnaryNeg(Box::new(inner), span))
1082        }
1083        TokenKind::Bang => {
1084            // Unary bitwise NOT: `!expr`
1085            p.advance();
1086            let inner = parse_atom(p)?;
1087            Ok(Expr::UnaryBitNot(Box::new(inner), span))
1088        }
1089        TokenKind::LParen => {
1090            // Parenthesized grouping (not a function call — that is
1091            // handled inside the Ident branch below).
1092            p.advance(); // consume '('
1093            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` is a SOFT keyword, like `over` and `input`: it stays a plain
1118            // identifier to the lexer, and only the shape that follows decides how
1119            // it parses. `if(` is the long-standing call form and is left entirely
1120            // alone; anything else is the block form below. Keeping it soft is what
1121            // lets both spellings coexist without a lexer change or a migration.
1122            if name == "if" && !matches!(p.peek(), TokenKind::LParen) {
1123                parse_if_block(p, span)
1124            } else if matches!(p.peek(), TokenKind::LParen) {
1125                // Function call: name(args...)
1126                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        // `input` is a soft keyword: usable as a plain identifier in
1134        // expressions (e.g. `hash(input)` inside a module body where
1135        // `input` is the parameter name).
1136        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        // `cursor` is also a soft keyword in expression position:
1146        // the `over cursor.partitions` form (cursor_partitions.md §7.2) names the
1147        // workload's `cursor` parameter. The statement-level
1148        // `cursor q = …` decl is handled by `parse_statement_into`
1149        // before expression parsing kicks in.
1150        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        // `over` is a soft keyword used only by the cursor-decl
1160        // syntax; in expression position it's a plain identifier,
1161        // so a wire may be named `over`.
1162        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
1180/// Desugar a string literal that contains `{ … }` placeholders
1181/// into a `printf` call.
1182///
1183/// String interpolation (polydat_grammar.md §9): `{name}` references resolve
1184/// to other bindings or workload parameters; the compiler
1185/// splits the template into a format string and the placeholder
1186/// expressions, then wires them into a `Printf` node that
1187/// formats at evaluation time. This is pure syntactic sugar —
1188/// no special runtime support beyond the standard node path.
1189///
1190/// Implementation: each placeholder body is lexed and parsed as
1191/// a full Polydat expression via the same `parse_expression` entry
1192/// the rest of the language uses, so nesting, function calls,
1193/// arithmetic, and field access all work uniformly:
1194///
1195/// | Input                                            | Result                                     |
1196/// |--------------------------------------------------|--------------------------------------------|
1197/// | `"hello"`                                        | `Expr::StringLit("hello")`                 |
1198/// | `"hello {name}"`                                 | `printf("hello {}", name)`                 |
1199/// | `"{a}-{b}"`                                      | `printf("{}-{}", a, b)`                    |
1200/// | `"{format_u64(hash(cycle), 10)}@example.com"`    | `printf("{}@example.com", format_u64(hash(cycle), 10))` |
1201/// | `"x={a + b}"`                                    | `printf("x={}", a + b)`                    |
1202/// | `"{x:05}"`                                       | `Expr::StringLit("{x:05}")` (format spec — left to printf) |
1203/// | `"{{literal}}"`                                  | `Expr::StringLit("{{literal}}")` (escaped braces) |
1204///
1205/// The placeholder scan is brace- and string-aware: `}` inside
1206/// a quoted string or inside nested parentheses doesn't
1207/// terminate the placeholder. `{{` and `}}` keep printf's escape
1208/// semantics for emitting literal braces in output. A
1209/// placeholder body that fails to parse as a complete
1210/// expression makes the whole literal stay as `StringLit` — the
1211/// user's intent was likely a printf format spec written by
1212/// hand, or an unbalanced brace, neither of which we should
1213/// interpret further.
1214fn 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), // unbalanced — leave alone
1218    };
1219
1220    if !segments
1221        .iter()
1222        .any(|seg| matches!(seg, Segment::Placeholder(_)))
1223    {
1224        return Expr::StringLit(s, span);
1225    }
1226
1227    // Build the printf format string and gather the placeholder
1228    // expressions, parsing each via the standard expression
1229    // parser so nested calls / arithmetic / field access all
1230    // work uniformly.
1231    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                    // Unparseable body → bail out, keep the
1240                    // string literal untouched. The user may
1241                    // have written a printf format spec or
1242                    // some other content that is not Polydat.
1243                    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
1263/// One piece of an interpolated string after segmentation.
1264enum Segment {
1265    /// Literal text to copy into the format string. Includes
1266    /// printf's own `{{` / `}}` escapes verbatim — printf's
1267    /// `parse_format` pass turns them into single-brace output.
1268    Literal(String),
1269    /// A `{ … }` placeholder body, with the surrounding braces
1270    /// stripped, which is lexed and parsed as a Polydat expression.
1271    Placeholder(String),
1272}
1273
1274/// Walk the input, splitting at each `{` that opens a
1275/// placeholder (i.e. not part of `{{`). Brace and string
1276/// awareness: nested `(`/`[`/`{` increase depth, the matching
1277/// closer decreases it, and `}` only terminates a placeholder
1278/// when at depth zero and not inside a `"…"` string literal.
1279///
1280/// Returns `None` if a placeholder is unterminated — the caller
1281/// treats the whole input as a non-interpolated literal.
1282fn 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        // Escaped braces: keep verbatim in the literal so printf
1290        // emits a single-brace output.
1291        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; // skip the `}`
1310            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
1321/// Find the index of the `}` that closes the placeholder
1322/// starting at `start`. Tracks paren/bracket/brace depth and
1323/// double-quoted string state so unbalanced sub-expressions
1324/// inside a placeholder body don't terminate it prematurely.
1325fn 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                // Skip the escape sequence (eg \" or \\). One
1334                // char of lookahead is enough — we only need to
1335                // avoid mistaking the next char for a string
1336                // terminator.
1337                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
1363/// Lex and parse a placeholder body as a single Polydat expression.
1364fn 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
1373/// Parse a dotted field-access chain (`a.b`, `q.cursor.idx`) —
1374/// the base name has already been consumed and the parser sits
1375/// on the first `.`. Intermediate levels flatten into the
1376/// source using the established `__` wire convention, so
1377/// `q.cursor.idx` yields `FieldAccess { source: "q__cursor",
1378/// field: "idx" }` — the same shape one-level access lowers to,
1379/// reading the wire `q__cursor__idx`.
1380fn parse_field_chain(p: &mut Parser, base: String, span: Span) -> Result<Expr, String> {
1381    p.advance(); // consume the first '.'
1382    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
1396/// Parse `name(args...)` — the name has already been consumed.
1397fn parse_call(p: &mut Parser, func: String, span: Span) -> Result<Expr, String> {
1398    p.advance(); // consume '('
1399    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
1416/// Parse a single argument: either `name: expr` (named) or `expr` (positional).
1417///
1418/// `name` accepts both plain identifiers and the soft keyword
1419/// `input` — the latter is the canonical parameter name in
1420/// host-provided cycle-driven modules.
1421fn 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(); // consume ident/keyword
1432        p.advance(); // consume ':'
1433        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
1440/// Parse `[expr, expr, ...]`
1441fn parse_array_lit(p: &mut Parser) -> Result<Expr, String> {
1442    let span = p.span();
1443    p.advance(); // consume '['
1444    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    /// Every place a type is named refuses the spellings retired in
1487    /// 0.10.0 with the keyword to write instead, and accepts that
1488    /// keyword.
1489    #[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    /// A declaration that names a type which does not exist is refused
1528    /// where it is written, in every declaration form: inputs and
1529    /// module outputs included, which once compiled with the unknown
1530    /// name ignored.
1531    #[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        // Order-independent rejection.
1596        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        // `volatile const x := 42` — const binding with volatile
1612        // modifier. The grammar accepts modifier stacking; the
1613        // `const + volatile` combination is rejected by
1614        // `BindingModifier::from_iter` as semantically
1615        // contradictory, but `volatile` alone (no const) is fine
1616        // and the parser must accept the lexical sequence.
1617        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        // Tuple form desugars to N InputDecl statements, mirroring
1655        // the module-signature param-list shape.
1656        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        // `input ()` is malformed — to declare zero inputs, omit the line.
1677        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        // Bare strings without `{name}` placeholders stay as
1759        // `Expr::StringLit`.
1760        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        // Strings containing `{ident}` placeholders compile to a
1773        // `printf(fmt, idents...)` call so the named idents flow
1774        // as wires from the surrounding scope.
1775        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        // printf format specs (`{:05}`, `{:x}`, `{:.3}`) and
1803        // empty positional placeholders (`{}`) aren't valid GK
1804        // expressions, so the literal is preserved untouched
1805        // for printf's own parser.
1806        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        // Function calls inside placeholders (polydat_grammar.md §9)
1819        // parse as full expressions and become printf args.
1820        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        // Infix arithmetic inside placeholders parses via the
1854        // standard Pratt expression path.
1855        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        // Field access (`base.ordinal`) inside placeholders.
1873        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        // Doubled braces (`{{`, `}}`) keep printf's escape
1894        // semantics — they emit literal `{` / `}` at format time
1895        // and don't open a placeholder.
1896        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        // An unterminated `{` makes the whole string stay literal.
1919        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        // Function-call parens inside a placeholder don't
1932        // confuse the brace scanner; the matching `}` is found
1933        // at depth zero.
1934        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        // `a + b * c` should parse as `a + (b * c)`
2035        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        // `(a + b) * c` — parens override precedence
2057        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, _) => {} // correct
2064                            _ => 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    /// Helper: unwrap a binding's value as the `if` call the block form desugars to.
2076    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        // The whole point: the block form is sugar, not a second construct. It must
2097        // produce exactly what the long-standing call form produces, so branch-type
2098        // dispatch and widening in binding.rs apply to it unchanged.
2099        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        // `else if` nests as the else-branch, so the chain is right-associative.
2133        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        // It is an expression, so it composes like one.
2153        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        // `if` stays a soft keyword: `if(` must not be captured by the block form.
2168        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        // Every Polydat expression yields a value, so a one-armed if has no result
2175        // on the false path. The error must say that rather than failing cryptically.
2176        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        // `sin(cycle * 0.25)` — infix inside function args
2211        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        // `a ** b ** c` should parse as `a ** (b ** c)` (right-associative)
2231        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        // `-sin(x)` — unary negation of a function call
2253        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        // Ensure all operators parse without error.
2269        let f = parse_str("y := a + b - c * d / e % f ** g");
2270        match &f.statements[0] {
2271            Statement::Binding(_) => {} // just checking it parses
2272            _ => panic!("expected cycle binding"),
2273        }
2274    }
2275
2276    #[test]
2277    fn parse_star_star_power() {
2278        // `x ** 2.0` parses as BinOp(x, Pow, 2.0)
2279        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        // `a ^ b` parses as BinOp(a, BitXor, b)
2295        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        // `a & b | c` should parse as `(a & b) | c`
2311        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, _) => {} // correct
2318                            _ => 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        // `a << 4` parses as BinOp(a, Shl, 4)
2332        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                // `cursor.partitions` parses as a field access.
2379                match &c.over {
2380                    Some(Expr::FieldAccess { .. }) => {} // OK
2381                    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        // Cursor scalar projections (cursor_partitions.md §7.2): `q.cursor.idx` reads the
2398        // wire `q__cursor__idx` — intermediate dot levels
2399        // flatten into the FieldAccess source using the same
2400        // `__` convention one-level access lowers to.
2401        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        // Deeper chains keep flattening.
2413        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        // `!x` parses as UnaryBitNot(x)
2429        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}