Skip to main content

polydat_grammar/comprehension/spec/
source_parser.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Source-string grammar parser — turns the user-facing
5//! source expression (e.g. `"1..10"`, `"[a, b, c]"`,
6//! `"fib(8)"`) into a typed [`Source`] value.
7//!
8//! comprehension_forms.md §3.1 specifies the source forms, and
9//! the parsing lives here so every polydat consumer shares one
10//! source-grammar implementation.
11//!
12//! Recognized forms:
13//!
14//! | Source text | Produces |
15//! |---|---|
16//! | `1..10` | `IntRange { lo: 1, hi: 10, step: 1 }` |
17//! | `1..=10` | `IntRange { lo: 1, hi: 11, step: 1 }` (inclusive end) |
18//! | `1..10 step 2` | `IntRange { lo: 1, hi: 10, step: 2 }` |
19//! | `[a, b, c]` | `Literal { values: [Str, Str, Str] }` |
20//! | `[1, 2, 3]` | `Literal { values: [Int, Int, Int] }` |
21//! | `[1.0, 2.5]` | `Literal { values: [Float, Float] }` |
22//! | `[true, false]` | `Literal { values: [Bool, Bool] }` |
23//! | `{name}` | `WorkloadParamList { name: "name", len_hint: None }` |
24//! | `fib(8)` (or any `ident(...)`) | `Generator { expr, cardinality_hint: None }` |
25//! | `0.0..1.0` | `ContinuousInterval { interval, measure: Uniform }` |
26//! | `normal(0, 1)` | `Distribution { Normal, support: the measure's own, params }` |
27//! | `exponential(1) on 0.0..1.0` | `Distribution { Exponential, support: the interval, params }` |
28//!
29//! Any other text is a `Generator` expression the runtime
30//! evaluates; `SourceParseError::Unrecognized` is not produced by
31//! this path.
32
33use crate::comprehension::cardinality::{Interval, MeasureName, ProductMeasure};
34use crate::comprehension::source::{LiteralValue, Source};
35
36/// Parse a source-expression string into a typed [`Source`].
37pub fn parse_source(text: &str) -> Result<Source, SourceParseError> {
38    let trimmed = text.trim();
39
40    // Workload-param reference: `{name}` — accepts both the
41    // simple form (`{foo}`) and the dynamic form
42    // (`{a_{b}_c}`). Dynamic placeholders surface as the
43    // outer name with `_` separators; the runtime interpolator
44    // resolves the nesting before lookup.
45    if let Some(name) = strip_curly(trimmed) {
46        return Ok(Source::WorkloadParamList {
47            name,
48            len_hint: None,
49        });
50    }
51    if let Some(dyn_text) = strip_dynamic_curly(trimmed) {
52        return Ok(Source::WorkloadParamList {
53            name: dyn_text,
54            len_hint: None,
55        });
56    }
57
58    // String comprehension (comprehension_forms.md §3.1.3): a wholly-quoted string in
59    // source position. Quote-kind selects the iteration interior:
60    //   - double `"…"` → iterable: token-strip (comma/semicolon/
61    //     whitespace; colons etc. retained) into a literal list.
62    //   - single `'…'` → atomic: one whole-string element.
63    // (Outside the source slot a quoted token is a plain string
64    // literal; this branch only runs because we're parsing a
65    // comprehension source.)
66    // A quoted string that holds a placeholder is read at run time,
67    // where the placeholder substitutes text inside the quotes before
68    // the quote kind is applied (§3.1.3): `'table_{region}'`. So is
69    // one that holds an escaped brace, which is written there as the
70    // brace: `'a_\{b\}'` is the string `a_{b}`.
71    if quoted_with_placeholder(trimmed) {
72        return Ok(Source::Generator {
73            expr: trimmed.to_string(),
74            cardinality_hint: None,
75        });
76    }
77    if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
78        let inner = &trimmed[1..trimmed.len() - 1];
79        let values = super::super::source::split_string_comprehension(inner)
80            .into_iter()
81            .map(parse_literal_value)
82            .collect();
83        return Ok(Source::Literal { values });
84    }
85    if trimmed.len() >= 2 && trimmed.starts_with('\'') && trimmed.ends_with('\'') {
86        let inner = &trimmed[1..trimmed.len() - 1];
87        return Ok(Source::Literal {
88            values: vec![LiteralValue::String(inner.to_string())],
89        });
90    }
91
92    // List comprehension sugar `[…]` (comprehension_forms.md §3.1.3, §3.1.4).
93    //   - Pure-literal list (numbers / bools / quoted strings,
94    //     no spread, no bare references) → `Source::Literal`,
95    //     baked at parse time with a static cardinality (the
96    //     historical fast path, unchanged).
97    //   - Otherwise — any bare-identifier *reference* element or
98    //     a `…`/`...` spread — defers to `Source::Generator`
99    //     carrying the bracket text verbatim, so the runtime
100    //     evaluator (`eval::try_eval_bracket_list`) resolves each
101    //     element against the kernel and applies spread peeling.
102    if trimmed.starts_with('[') && trimmed.ends_with(']') {
103        let inner = &trimmed[1..trimmed.len() - 1];
104        if bracket_is_pure_literal(inner) {
105            return parse_literal_list(inner);
106        }
107        return Ok(Source::Generator {
108            expr: trimmed.to_string(),
109            cardinality_hint: None,
110        });
111    }
112
113    // A named continuous measure (comprehension_forms.md §3.1,
114    // §10.7.5): `normal(0, 1)`, and
115    // `normal(0, 1) on 0.0..1.0` for the measure restricted to an
116    // interval. Before the range and call branches, which would read
117    // the interval alone or take the call for a generator.
118    if let Some(result) = parse_distribution(trimmed) {
119        return result;
120    }
121
122    // Range: contains `..` and starts with a number-ish.
123    if let Some(idx) = find_top_level(trimmed, "..") {
124        return parse_range(trimmed, idx);
125    }
126
127    // Function-call shape: `ident(...)` → Generator
128    if looks_like_function_call(trimmed) {
129        return Ok(Source::Generator {
130            expr: trimmed.to_string(),
131            cardinality_hint: None,
132        });
133    }
134
135    // Bare scalar literal: `10`, `"hello"`, `true`, `3.14` →
136    // single-element Literal: `k in 10` dispenses exactly one
137    // tuple.
138    if let Some(value) = try_parse_bare_scalar(trimmed) {
139        return Ok(Source::Literal {
140            values: vec![value],
141        });
142    }
143
144    // Bare comma-separated list: `k in 1,2,3` and `y in a,b,c`
145    // without brackets are a Literal list (the bare label list of
146    // comprehension_forms.md §3.1.4). The check is conservative:
147    // require a top-level comma and that no element contains
148    // syntax that would suggest a more complex expression
149    // (parens, brackets, braces, operators).
150    if trimmed.contains(',') && looks_like_bare_value_list(trimmed) {
151        return parse_literal_list(trimmed);
152    }
153
154    // Fallback: a Generator expression. Any other expression text
155    // (e.g. `pre_{outer}`, `mod_in(cycle, p)`, `range(0, {n})`) is
156    // resolved by the runtime evaluator via the Polydat Kernel
157    // chain; its cardinality is unknown here
158    // (cardinality_hint=None), and it renders back verbatim.
159    Ok(Source::Generator {
160        expr: trimmed.to_string(),
161        cardinality_hint: None,
162    })
163}
164
165/// Whether `text` is one wholly quoted string, of either quote kind,
166/// that holds an unescaped `{`, a placeholder to substitute, or an
167/// escaped brace (`\{`, `\}`), which the run time writes as the brace.
168fn quoted_with_placeholder(text: &str) -> bool {
169    let Some(quote) = text.chars().next().filter(|c| matches!(c, '"' | '\'')) else {
170        return false;
171    };
172    if text.len() < 2 || !text.ends_with(quote) {
173        return false;
174    }
175    let inner = &text[1..text.len() - 1];
176    if inner.contains(quote) {
177        return false;
178    }
179    let bytes = inner.as_bytes();
180    (0..bytes.len()).any(|i| {
181        let escaped = i > 0 && bytes[i - 1] == b'\\';
182        (bytes[i] == b'{' && !escaped) || (matches!(bytes[i], b'{' | b'}') && escaped)
183    })
184}
185
186/// A named continuous measure written as a source: `normal(0, 1)`
187/// draws from the measure's own support, and `normal(0, 1) on
188/// 0.0..1.0` restricts it to the interval. `None` when the text
189/// names no measure, so the caller reads it as something else.
190///
191/// The arguments are the measure's parameters in the order
192/// [`MeasureName::parameter_names`] gives; none means the standard
193/// ones. A name from the closed set with arguments that are not its
194/// own is an error, not a fall-through: `normal(1)` is a mistake to
195/// report, never a generator call.
196fn parse_distribution(text: &str) -> Option<Result<Source, SourceParseError>> {
197    let (call, support_text) = match split_on_keyword(text, " on ") {
198        Some((call, rest)) => (call, Some(rest)),
199        None => (text, None),
200    };
201    let (name, args) = split_call(call)?;
202    let measure = MeasureName::from_text(name)?;
203    Some(build_distribution(text, measure, args, support_text))
204}
205
206/// The measure source `text` denotes, or the error its arguments or
207/// its interval earn.
208fn build_distribution(
209    text: &str,
210    measure: MeasureName,
211    args: &str,
212    support_text: Option<&str>,
213) -> Result<Source, SourceParseError> {
214    let invalid = || SourceParseError::InvalidRange(text.to_string());
215    let mut params = Vec::new();
216    for arg in args.split(',') {
217        let arg = arg.trim();
218        if arg.is_empty() {
219            if params.is_empty() && args.trim().is_empty() {
220                break;
221            }
222            return Err(invalid());
223        }
224        params.push(arg.parse::<f64>().map_err(|_| invalid())?);
225    }
226    let params = measure.resolve_params(&params).map_err(|_| invalid())?;
227    let support = match support_text {
228        None => measure.support(&params),
229        Some(interval_text) => match parse_range_text(interval_text)? {
230            Source::ContinuousInterval { interval, .. } => interval,
231            _ => return Err(invalid()),
232        },
233    };
234    Ok(Source::Distribution {
235        distribution: measure,
236        support,
237        params,
238    })
239}
240
241/// `name(args)` split into its head and its argument text, or `None`
242/// when the text is not one call and nothing else.
243fn split_call(text: &str) -> Option<(&str, &str)> {
244    let text = text.trim();
245    let open = text.find('(')?;
246    let inner = text.strip_suffix(')')?;
247    let name = text[..open].trim();
248    if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
249        return None;
250    }
251    Some((name, &inner[open + 1..]))
252}
253
254/// Split `text` at `keyword` outside any bracket or quote, the way a
255/// measure's interval is written after its call.
256fn split_on_keyword<'a>(text: &'a str, keyword: &str) -> Option<(&'a str, &'a str)> {
257    let bytes = text.as_bytes();
258    let mut depth = 0i32;
259    let mut quote: Option<u8> = None;
260    for i in 0..bytes.len() {
261        let c = bytes[i];
262        match quote {
263            Some(q) => {
264                if c == q {
265                    quote = None;
266                }
267            }
268            None => match c {
269                b'"' | b'\'' => quote = Some(c),
270                b'(' | b'[' | b'{' => depth += 1,
271                b')' | b']' | b'}' => depth -= 1,
272                _ => {
273                    if depth == 0 && text[i..].starts_with(keyword) {
274                        return Some((&text[..i], &text[i + keyword.len()..]));
275                    }
276                }
277            },
278        }
279    }
280    None
281}
282
283/// Conservative bare-comma-list detector. The form
284/// `k in 1,2,3` (no brackets) is a literal list; this matches
285/// it without misclassifying expression-like text. Same shape
286/// as `looks_like_literal_list` in
287/// `polydat::iteration::comprehension::eval`.
288fn looks_like_bare_value_list(text: &str) -> bool {
289    !text.chars().any(|c| {
290        matches!(
291            c,
292            '(' | ')'
293                | '['
294                | ']'
295                | '{'
296                | '}'
297                | '\''
298                | '"'
299                | '+'
300                | '*'
301                | '/'
302                | '%'
303                | '='
304                | '<'
305                | '>'
306                | '!'
307                | '&'
308                | '|'
309                | '~'
310                | '^'
311                | '?'
312        )
313    })
314}
315
316/// Detect dynamic-placeholder text like `{a_{b}_c}` (nested
317/// braces). Returns the contained text as the name; the runtime
318/// interpolator handles the nesting at lookup time.
319fn strip_dynamic_curly(s: &str) -> Option<String> {
320    let s = s.trim();
321    if !s.starts_with('{') || !s.ends_with('}') {
322        return None;
323    }
324    let inner = &s[1..s.len() - 1];
325    // Must contain at least one nested `{` — distinguishes
326    // dynamic from the simple `{name}` form `strip_curly`
327    // already handled.
328    if !inner.contains('{') {
329        return None;
330    }
331    Some(inner.to_string())
332}
333
334/// Parse a comma-separated literal list. Determines element
335/// type from the first element; mixed-type lists currently
336/// fall back to string.
337fn parse_literal_list(inner: &str) -> Result<Source, SourceParseError> {
338    let parts: Vec<&str> = inner
339        .split(',')
340        .map(|s| s.trim())
341        .filter(|s| !s.is_empty())
342        .collect();
343
344    if parts.is_empty() {
345        return Ok(Source::Literal { values: Vec::new() });
346    }
347
348    let values: Vec<LiteralValue> = parts.iter().map(|s| parse_literal_value(s)).collect();
349
350    Ok(Source::Literal { values })
351}
352
353/// True when every element of a bracket list is a pure literal
354/// (integer, float, bool, or quoted string) and there is no
355/// spread (`…`/`...`). Such lists bake to `Source::Literal` at
356/// parse time. A bare-identifier element (a reference) or a
357/// spread makes the list eval-time (`Source::Generator`)
358/// (comprehension_forms.md §3.1.4).
359fn bracket_is_pure_literal(inner: &str) -> bool {
360    let elems: Vec<&str> = inner
361        .split(',')
362        .map(str::trim)
363        .filter(|s| !s.is_empty())
364        .collect();
365    if elems.is_empty() {
366        return true; // `[]` is a (degenerate) literal list
367    }
368    elems.iter().all(|e| {
369        if e.ends_with('…') || e.ends_with("...") {
370            return false; // spread → eval-time
371        }
372        e.eq_ignore_ascii_case("true")
373            || e.eq_ignore_ascii_case("false")
374            || ((e.starts_with('"') && e.ends_with('"'))
375                || (e.starts_with('\'') && e.ends_with('\'')))
376            || e.parse::<i64>().is_ok()
377            || e.parse::<f64>().is_ok()
378    })
379}
380
381fn parse_literal_value(s: &str) -> LiteralValue {
382    let s = s.trim();
383    if s.eq_ignore_ascii_case("true") {
384        return LiteralValue::Bool(true);
385    }
386    if s.eq_ignore_ascii_case("false") {
387        return LiteralValue::Bool(false);
388    }
389    // Quoted string
390    if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
391        let inner = &s[1..s.len() - 1];
392        return LiteralValue::String(inner.to_string());
393    }
394    // Integer
395    if let Ok(n) = s.parse::<i64>() {
396        return LiteralValue::Int(n);
397    }
398    if let Ok(n) = s.parse::<u64>() {
399        return LiteralValue::UInt(n);
400    }
401    // Float
402    if let Ok(f) = s.parse::<f64>() {
403        return LiteralValue::Float(f);
404    }
405    // Bare identifier → string literal
406    LiteralValue::String(s.to_string())
407}
408
409/// Parse a range expression starting at `dotdot_idx` (the
410/// position of `..`).
411fn parse_range_text(text: &str) -> Result<Source, SourceParseError> {
412    let text = text.trim();
413    match find_top_level(text, "..") {
414        Some(idx) => parse_range(text, idx),
415        None => Err(SourceParseError::InvalidRange(text.to_string())),
416    }
417}
418
419fn parse_range(text: &str, dotdot_idx: usize) -> Result<Source, SourceParseError> {
420    let lo_str = text[..dotdot_idx].trim();
421    let after = &text[dotdot_idx + 2..];
422
423    // `..=` inclusive form
424    let (inclusive_end, after) = if let Some(rest) = after.strip_prefix('=') {
425        (true, rest)
426    } else {
427        (false, after)
428    };
429
430    // Optional ` step N` suffix or the three-segment form
431    // `..N` (e.g. `1..10..2`, `1..=10..2`). Both are step
432    // suffixes. Check ` step ` first since it's the documented
433    // form.
434    let (rhs, step) = if let Some(step_pos) = after.find(" step ") {
435        let rhs = after[..step_pos].trim();
436        let step_str = after[step_pos + 6..].trim();
437        let step: i64 = step_str
438            .parse()
439            .map_err(|_| SourceParseError::InvalidRange(text.to_string()))?;
440        (rhs, step)
441    } else if let Some(step_pos) = after.find("..") {
442        // The `lo..hi..step` shape: the second `..` is
443        // the step separator.
444        let rhs = after[..step_pos].trim();
445        let step_str = after[step_pos + 2..].trim();
446        let step: i64 = step_str
447            .parse()
448            .map_err(|_| SourceParseError::InvalidRange(text.to_string()))?;
449        (rhs, step)
450    } else {
451        (after.trim(), 1)
452    };
453
454    // Try parsing both endpoints as integers first.
455    if let (Ok(lo_i), Ok(hi_i)) = (lo_str.parse::<i64>(), rhs.parse::<i64>()) {
456        let hi = if inclusive_end { hi_i + 1 } else { hi_i };
457        return Ok(Source::IntRange { lo: lo_i, hi, step });
458    }
459    // Otherwise try as floats → continuous interval.
460    if let (Ok(lo_f), Ok(hi_f)) = (lo_str.parse::<f64>(), rhs.parse::<f64>()) {
461        let interval = Interval {
462            lo: lo_f,
463            hi: hi_f,
464            lo_open: false,
465            hi_open: !inclusive_end,
466        };
467        return Ok(Source::ContinuousInterval {
468            interval,
469            measure: ProductMeasure::Uniform,
470        });
471    }
472
473    Err(SourceParseError::InvalidRange(text.to_string()))
474}
475
476fn strip_curly(s: &str) -> Option<String> {
477    let s = s.trim();
478    if s.starts_with('{') && s.ends_with('}') {
479        let inner = &s[1..s.len() - 1];
480        let trimmed = inner.trim();
481        if !trimmed.is_empty() && trimmed.chars().all(|c| c.is_alphanumeric() || c == '_') {
482            return Some(trimmed.to_string());
483        }
484    }
485    None
486}
487
488/// Try to parse `s` as a bare scalar literal — int, float,
489/// bool, or quoted string. Returns `None` if `s` is not a
490/// well-formed scalar (e.g., a bare identifier without
491/// quotes); bare identifiers ambiguously could be names rather
492/// than string literals, so we don't accept them here.
493fn try_parse_bare_scalar(s: &str) -> Option<LiteralValue> {
494    if s.eq_ignore_ascii_case("true") {
495        return Some(LiteralValue::Bool(true));
496    }
497    if s.eq_ignore_ascii_case("false") {
498        return Some(LiteralValue::Bool(false));
499    }
500    if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
501        let inner = &s[1..s.len() - 1];
502        return Some(LiteralValue::String(inner.to_string()));
503    }
504    if let Ok(n) = s.parse::<i64>() {
505        return Some(LiteralValue::Int(n));
506    }
507    if let Ok(n) = s.parse::<u64>() {
508        return Some(LiteralValue::UInt(n));
509    }
510    if let Ok(f) = s.parse::<f64>() {
511        return Some(LiteralValue::Float(f));
512    }
513    None
514}
515
516fn looks_like_function_call(s: &str) -> bool {
517    let Some(open) = s.find('(') else {
518        return false;
519    };
520    if !s.ends_with(')') {
521        return false;
522    }
523    let name = &s[..open];
524    !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_')
525}
526
527/// Find the first top-level occurrence of `needle`,
528/// respecting `(`, `[`, `{` nesting.
529fn find_top_level(s: &str, needle: &str) -> Option<usize> {
530    let bytes = s.as_bytes();
531    let needle_bytes = needle.as_bytes();
532    let mut depth = 0i64;
533    let mut i = 0;
534    while i + needle_bytes.len() <= bytes.len() {
535        match bytes[i] {
536            b'(' | b'[' | b'{' => depth += 1,
537            b')' | b']' | b'}' => depth -= 1,
538            _ => {}
539        }
540        if depth == 0 && &bytes[i..i + needle_bytes.len()] == needle_bytes {
541            return Some(i);
542        }
543        i += 1;
544    }
545    None
546}
547
548/// Errors that can arise during source-string parsing.
549#[derive(Debug, Clone, PartialEq)]
550pub enum SourceParseError {
551    /// The source text doesn't match any recognized shape.
552    Unrecognized(String),
553    /// A range expression couldn't be parsed (bad endpoint
554    /// types, malformed step suffix, etc.).
555    InvalidRange(String),
556}
557
558impl std::fmt::Display for SourceParseError {
559    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
560        match self {
561            SourceParseError::Unrecognized(s) => {
562                write!(f, "unrecognized source expression: {s:?}")
563            }
564            SourceParseError::InvalidRange(s) => {
565                write!(f, "invalid range expression: {s:?}")
566            }
567        }
568    }
569}
570
571impl std::error::Error for SourceParseError {}
572
573#[cfg(test)]
574mod tests {
575    use super::*;
576
577    #[test]
578    fn int_range_exclusive() {
579        let s = parse_source("1..10").unwrap();
580        assert!(matches!(
581            s,
582            Source::IntRange {
583                lo: 1,
584                hi: 10,
585                step: 1
586            }
587        ));
588    }
589
590    #[test]
591    fn double_quoted_source_is_string_comprehension_striped() {
592        // comprehension_forms.md §3.1.3: double-quoted source → token-strip.
593        let s = parse_source(r#""rerank_def, rerank_1x, rerank_2x""#).unwrap();
594        match s {
595            Source::Literal { values } => {
596                assert_eq!(
597                    values,
598                    vec![
599                        LiteralValue::String("rerank_def".into()),
600                        LiteralValue::String("rerank_1x".into()),
601                        LiteralValue::String("rerank_2x".into()),
602                    ]
603                );
604            }
605            other => panic!("expected striped Literal, got {other:?}"),
606        }
607    }
608
609    #[test]
610    fn single_quoted_source_is_atomic() {
611        // comprehension_forms.md §3.1.3: single-quoted source → one whole element.
612        let s = parse_source("'rerank_def, rerank_1x'").unwrap();
613        match s {
614            Source::Literal { values } => {
615                assert_eq!(
616                    values,
617                    vec![LiteralValue::String("rerank_def, rerank_1x".into())]
618                );
619            }
620            other => panic!("expected atomic Literal, got {other:?}"),
621        }
622    }
623
624    #[test]
625    fn int_range_inclusive() {
626        let s = parse_source("1..=10").unwrap();
627        assert!(matches!(
628            s,
629            Source::IntRange {
630                lo: 1,
631                hi: 11,
632                step: 1
633            }
634        ));
635    }
636
637    #[test]
638    fn int_range_with_step() {
639        let s = parse_source("0..100 step 10").unwrap();
640        assert!(matches!(
641            s,
642            Source::IntRange {
643                lo: 0,
644                hi: 100,
645                step: 10
646            }
647        ));
648    }
649
650    #[test]
651    fn literal_int_list() {
652        let s = parse_source("[1, 2, 3]").unwrap();
653        match s {
654            Source::Literal { values } => {
655                assert_eq!(values.len(), 3);
656                assert_eq!(values[0], LiteralValue::Int(1));
657                assert_eq!(values[2], LiteralValue::Int(3));
658            }
659            other => panic!("expected Literal, got {other:?}"),
660        }
661    }
662
663    #[test]
664    fn bracket_bare_words_are_references_not_strings() {
665        // comprehension_forms.md §3.1.4: bare-word bracket elements are wire
666        // *references*, not string literals — so the list defers
667        // to a Generator (resolved at eval time) rather than
668        // baking `["a","b","c"]`. To get string literals, quote
669        // them (see `literal_quoted_strings`).
670        let s = parse_source("[a, b, c]").unwrap();
671        match s {
672            Source::Generator { expr, .. } => assert_eq!(expr, "[a, b, c]"),
673            other => panic!("expected deferred Generator, got {other:?}"),
674        }
675    }
676
677    #[test]
678    fn bracket_with_spread_defers_to_generator() {
679        let s = parse_source("[xs…]").unwrap();
680        assert!(
681            matches!(s, Source::Generator { .. }),
682            "spread list must defer: {s:?}"
683        );
684    }
685
686    #[test]
687    fn literal_quoted_strings() {
688        let s = parse_source(r#"["hello", "world"]"#).unwrap();
689        match s {
690            Source::Literal { values } => {
691                assert_eq!(values[0], LiteralValue::String("hello".into()));
692                assert_eq!(values[1], LiteralValue::String("world".into()));
693            }
694            other => panic!("expected Literal, got {other:?}"),
695        }
696    }
697
698    #[test]
699    fn literal_float_list() {
700        let s = parse_source("[1.5, 2.5, 3.5]").unwrap();
701        match s {
702            Source::Literal { values } => {
703                assert_eq!(values[0], LiteralValue::Float(1.5));
704            }
705            other => panic!("expected Literal, got {other:?}"),
706        }
707    }
708
709    #[test]
710    fn workload_param_ref() {
711        let s = parse_source("{profiles}").unwrap();
712        match s {
713            Source::WorkloadParamList { name, .. } => assert_eq!(name, "profiles"),
714            other => panic!("expected WorkloadParamList, got {other:?}"),
715        }
716    }
717
718    #[test]
719    fn generator_function_call() {
720        let s = parse_source("fib(8)").unwrap();
721        match s {
722            Source::Generator { expr, .. } => assert_eq!(expr, "fib(8)"),
723            other => panic!("expected Generator, got {other:?}"),
724        }
725    }
726
727    #[test]
728    fn continuous_interval_via_floats() {
729        let s = parse_source("0.0..1.0").unwrap();
730        match s {
731            Source::ContinuousInterval { interval, measure } => {
732                assert_eq!(interval.lo, 0.0);
733                assert_eq!(interval.hi, 1.0);
734                assert!(matches!(measure, ProductMeasure::Uniform));
735            }
736            other => panic!("expected ContinuousInterval, got {other:?}"),
737        }
738    }
739
740    #[test]
741    fn continuous_interval_inclusive() {
742        let s = parse_source("0.0..=1.0").unwrap();
743        match s {
744            Source::ContinuousInterval { interval, .. } => {
745                assert!(!interval.hi_open);
746            }
747            other => panic!("expected ContinuousInterval, got {other:?}"),
748        }
749    }
750
751    #[test]
752    fn unrecognized_source_falls_back_to_generator() {
753        // The source grammar accepts arbitrary expression text and
754        // the runtime evaluator resolves it via the Polydat Kernel
755        // chain, so an unrecognized shape passes through as a
756        // Generator expression rather than failing the parse.
757        let s = parse_source("totally nonsense").unwrap();
758        match s {
759            Source::Generator { expr, .. } => assert_eq!(expr, "totally nonsense"),
760            other => panic!("expected Generator, got {other:?}"),
761        }
762    }
763
764    #[test]
765    fn empty_literal_list() {
766        let s = parse_source("[]").unwrap();
767        match s {
768            Source::Literal { values } => assert!(values.is_empty()),
769            other => panic!("expected empty Literal, got {other:?}"),
770        }
771    }
772
773    /// A named measure is a source of its own: the call alone draws
774    /// from the measure's support, and `on <interval>` restricts it.
775    #[test]
776    fn a_named_measure_parses_as_a_distribution() {
777        match parse_source("normal(0, 1)").unwrap() {
778            Source::Distribution {
779                distribution: MeasureName::Normal,
780                support,
781                params,
782            } => {
783                assert_eq!(params, vec![0.0, 1.0]);
784                assert!(support.lo.is_infinite() && support.hi.is_infinite());
785            }
786            other => panic!("expected a normal distribution, got {other:?}"),
787        }
788        match parse_source("exponential(2) on 0.0..1.0").unwrap() {
789            Source::Distribution {
790                distribution: MeasureName::Exponential,
791                support,
792                params,
793            } => {
794                assert_eq!(params, vec![2.0]);
795                assert_eq!(support, Interval::half_open(0.0, 1.0));
796            }
797            other => panic!("expected a restricted exponential, got {other:?}"),
798        }
799        // No arguments takes the measure's standard parameters, and a
800        // Pareto's support starts at its scale.
801        match parse_source("pareto(3, 2)").unwrap() {
802            Source::Distribution {
803                support, params, ..
804            } => {
805                assert_eq!(params, vec![3.0, 2.0]);
806                assert_eq!(support.lo, 3.0);
807            }
808            other => panic!("{other:?}"),
809        }
810        assert!(matches!(
811            parse_source("uniform01()").unwrap(),
812            Source::Distribution {
813                distribution: MeasureName::Uniform01,
814                ..
815            }
816        ));
817    }
818
819    /// Only the closed set of measures is a distribution; any other
820    /// call is the generator it always was.
821    #[test]
822    fn a_call_that_names_no_measure_is_still_a_generator() {
823        for text in ["fib(8)", "partitions(\"*/4\", 100)", "range(0, 10)"] {
824            assert!(
825                matches!(parse_source(text).unwrap(), Source::Generator { .. }),
826                "{text}"
827            );
828        }
829        // An interval alone keeps its uniform measure.
830        assert!(matches!(
831            parse_source("0.0..1.0").unwrap(),
832            Source::ContinuousInterval { .. }
833        ));
834    }
835
836    /// A measure's arguments are its own: a wrong count is the error
837    /// the measure's parameter table names, not a generator call.
838    #[test]
839    fn a_measure_with_the_wrong_arguments_is_an_error() {
840        for text in ["normal(1)", "normal(0, 1, 2)", "beta(a, b)", "gamma(1,)"] {
841            assert!(parse_source(text).is_err(), "{text}");
842        }
843    }
844}