Skip to main content

polydat_core/iteration/comprehension/
eval.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Comprehension spec evaluation — text → typed value list.
5//!
6//! ## What this module does
7//!
8//! A comprehension clause `var in expr` ships its `expr` as
9//! free-form workload-author text. At runtime, the executor
10//! needs to turn that text into a list of typed values to
11//! enumerate over. That's what [`evaluate_spec`] does, given a
12//! Polydat Kernel that holds the in-scope name space (own outputs +
13//! inherited externs from `materialize_wiring_from_outer`).
14//!
15//! ## Pipeline
16//!
17//! A source that is one reference, written bare (`name`) or as a
18//! placeholder that is the whole source (`{name}`, `{a_{b}}`), reads
19//! the value the name is bound to, with its type, and that value is
20//! peeled or wrapped. So does each element of a bracketed list that is
21//! such a reference (comprehension_forms.md §3.1.5). Any other text
22//! goes through the pipeline below, in which a placeholder substitutes
23//! text:
24//!
25//! ```text
26//!   spec_text
27//!       │
28//!       ▼
29//!   interpolate_via_kernel  ← {name} → kernel.lookup(name)
30//!       │
31//!       ▼
32//!   eval_const_expr_for     ← optional: Polydat expression eval,
33//!                              charged to scope.ledger()
34//!       │
35//!       ▼
36//!   parse_list_with_types   ← comma-split, per-element type
37//!       │
38//!       ▼
39//!   Vec<Value>              ← what the executor enumerates
40//! ```
41//!
42//! ## Ownership
43//!
44//! Polydat owns what a comprehension *means*, including how its
45//! source strings resolve (comprehension_forms.md §3.1). A host
46//! consumes this API rather than implementing it.
47
48use std::collections::HashMap;
49
50use crate::ast::Value;
51use crate::iteration::comprehension::eval_source::NoneRead;
52use crate::kernel::interp::Lookup;
53use crate::kernel::interp::interpolate_with_lookup;
54use crate::kernel::interp::{is_name_path, whole_placeholder};
55
56/// Evaluate a comprehension clause's spec text against a `Lookup` scope.
57///
58/// A source that is a reference, bare or a whole placeholder, and a
59/// bracketed list's elements that are, read their values first
60/// (comprehension_forms.md §3.1.5). For any other text:
61///  1. [`interpolate_via_kernel`](crate::kernel::interp::interpolate_via_kernel) resolves `{name}` placeholders
62///     against the kernel's in-scope name space (own outputs +
63///     inherited extern values).
64///  2. Try `dsl::compile::eval_const_expr_for(…, kernel.ledger())`
65///     on the result. On
66///     success with a `Str` value, re-parse as a comma-separated
67///     list with per-element type detection. Other typed
68///     variants become a single-element typed list.
69///  3. On eval failure (most common case for literal lists like
70///     `"1, 10"` which aren't valid Polydat const expressions), fall
71///     back to [`parse_list_with_types`] on the interpolated
72///     text — `1` → `U64`, `1.5` → `F64`, `true` → `Bool`,
73///     anything else → `Str`.
74///
75/// Errors propagate from interpolation (unresolved placeholder,
76/// runaway round count, etc.) — those are the user-facing
77/// actionable diagnostics. A name the source reads that nothing binds
78/// is such an error here; a name bound to None reads None, and the
79/// source yields nothing (none_semantics.md Rule 1). A clause source
80/// evaluated as part of a comprehension reads an unbound name as None
81/// too (comprehension_forms.md §5 V3).
82pub fn evaluate_spec(
83    spec_text: &str,
84    kernel: &dyn Lookup,
85) -> Result<Vec<Value>, crate::dsl::compile::EmbeddingError> {
86    match evaluate_spec_internal(spec_text, kernel) {
87        Ok(values) => Ok(values),
88        Err(SpecError::ReadsNone { reads, .. })
89            if reads.iter().all(|r| matches!(r, NoneRead::BoundNone(_))) =>
90        {
91            Ok(Vec::new())
92        }
93        Err(e) => Err(spec_error(spec_text, String::from(e))),
94    }
95}
96
97/// The error [`evaluate_spec`] reports for `spec_text` failing with
98/// `message`.
99pub(crate) fn spec_error(spec_text: &str, message: String) -> crate::dsl::compile::EmbeddingError {
100    if let Some(rest) = message.strip_prefix("interpolation: unresolved placeholder '{")
101        && let Some(end) = rest.find('}')
102    {
103        return crate::dsl::compile::EmbeddingError::UnresolvedPlaceholder {
104            name: rest[..end].to_string(),
105            source: spec_text.to_string(),
106        };
107    }
108    crate::dsl::compile::EmbeddingError::Parse {
109        source: spec_text.to_string(),
110        message,
111        position: None,
112    }
113}
114
115/// Why a source's spec text yields no values.
116#[derive(Debug, Clone)]
117pub(crate) enum SpecError {
118    /// The source read names that nothing binds or that are bound to
119    /// None, after composition, so it reads None and yields nothing
120    /// (none_semantics.md Rule 1, comprehension_forms.md §5 V3).
121    /// `message` is the diagnostic an API that refuses such a read
122    /// reports ([`evaluate_spec`]).
123    ReadsNone {
124        /// Each such name, once, with how it read None.
125        reads: Vec<NoneRead>,
126        /// The diagnostic for the first read.
127        message: String,
128    },
129    /// Evaluating the text failed.
130    Failed(String),
131}
132
133impl From<String> for SpecError {
134    fn from(message: String) -> Self {
135        SpecError::Failed(message)
136    }
137}
138
139impl From<SpecError> for String {
140    fn from(e: SpecError) -> Self {
141        match e {
142            SpecError::ReadsNone { message, .. } | SpecError::Failed(message) => message,
143        }
144    }
145}
146
147/// What `kernel` binds `name` to, for a source that reads it: a name
148/// nothing binds, or one bound to None, is [`SpecError::ReadsNone`],
149/// with `unbound` the diagnostic for the first.
150fn read_name(
151    kernel: &dyn Lookup,
152    name: &str,
153    unbound: impl FnOnce() -> String,
154) -> Result<Value, SpecError> {
155    match kernel.lookup(name) {
156        Some(Value::None) => Err(SpecError::ReadsNone {
157            reads: vec![NoneRead::BoundNone(name.to_string())],
158            message: format!("`{name}` is None"),
159        }),
160        Some(value) => Ok(value),
161        None => Err(SpecError::ReadsNone {
162            reads: vec![NoneRead::Unbound(name.to_string())],
163            message: unbound(),
164        }),
165    }
166}
167
168/// Interpolate `text`'s `{name}` placeholders against `kernel`, inside
169/// out, so a composed name (`{k_{k}_limits}`) reads the name its leaves
170/// compose to. A placeholder that names what nothing binds, or what is
171/// bound to None, is a read of None ([`SpecError::ReadsNone`]); any
172/// other failure is [`SpecError::Failed`].
173fn interpolate_reading(text: &str, kernel: &dyn Lookup) -> Result<String, SpecError> {
174    let reads = std::cell::RefCell::new(Vec::new());
175    let interpolated = interpolate_with_lookup(text, |name| match kernel.lookup(name) {
176        Some(Value::None) => {
177            reads
178                .borrow_mut()
179                .push(NoneRead::BoundNone(name.to_string()));
180            None
181        }
182        Some(value) => Some(value.to_display_string()),
183        None => {
184            if is_name_path(name) {
185                reads.borrow_mut().push(NoneRead::Unbound(name.to_string()));
186            }
187            None
188        }
189    });
190    interpolated.map_err(|message| {
191        let mut reads = reads.into_inner();
192        if reads.is_empty() {
193            return SpecError::Failed(message);
194        }
195        reads.sort();
196        reads.dedup();
197        SpecError::ReadsNone { reads, message }
198    })
199}
200
201/// The value a placeholder that is a whole operand reads
202/// (comprehension_forms.md §3.1.5): `text` is one placeholder and
203/// nothing else, its body composes, from its leaves, to a name, and the
204/// value is what `kernel` binds that name to, with its type, as the bare
205/// name reads it. `None` when `text` is not such a placeholder, so the
206/// caller substitutes text. A name nothing binds, or one bound to None,
207/// reads None ([`SpecError::ReadsNone`]).
208fn read_whole_placeholder(text: &str, kernel: &dyn Lookup) -> Result<Option<Value>, SpecError> {
209    let Some(body) = whole_placeholder(text) else {
210        return Ok(None);
211    };
212    let composed = interpolate_reading(body, kernel)?;
213    let name = composed.trim();
214    if !is_name_path(name) {
215        return Ok(None);
216    }
217    read_name(kernel, name, || {
218        format!(
219            "interpolation: unresolved placeholder '{{{name}}}' in '{text}' — \
220             not bound by any outer for_each var or workload param. \
221             Use \\{{ \\}} to write literal braces."
222        )
223    })
224    .map(Some)
225}
226
227/// A resolved source value as the values it iterates: its iteration
228/// interior when it has one, itself alone otherwise
229/// (comprehension_forms.md §3.1.2).
230fn peel_or_wrap(v: Value) -> Vec<Value> {
231    match crate::iteration::comprehension::source_values::iteration_interior(&v) {
232        Some(interior) => interior,
233        None => vec![v],
234    }
235}
236
237/// The values of a wholly quoted source (comprehension_forms.md
238/// §3.1.3), `None` when `text` is not one. Placeholders inside the
239/// quotes substitute text; then a double-quoted string strips into its
240/// tokens and a single-quoted one is one whole-string element.
241fn try_eval_quoted(text: &str, kernel: &dyn Lookup) -> Result<Option<Vec<Value>>, SpecError> {
242    let t = text.trim();
243    let quote = match t.chars().next() {
244        Some(q @ ('"' | '\'')) if t.len() >= 2 && t.ends_with(q) => q,
245        _ => return Ok(None),
246    };
247    let inner = &t[1..t.len() - 1];
248    // One string, not two quoted strings with something between them.
249    if inner.contains(quote) {
250        return Ok(None);
251    }
252    let inner = interpolate_reading(inner, kernel)?;
253    Ok(Some(if quote == '"' {
254        crate::iteration::comprehension::source_values::strip_string_tokens(&inner)
255    } else {
256        vec![Value::Str(inner.into())]
257    }))
258}
259
260/// The names `text` reads as free identifiers of the language that
261/// `kernel` does not bind or binds to None, as [`SpecError::ReadsNone`]
262/// with `message`; [`SpecError::Failed`] with `message` when there are
263/// none. An evaluation of `text` that failed reading such a name failed
264/// because the name reads None.
265fn failure_reading(text: &str, kernel: &dyn Lookup, message: String) -> SpecError {
266    let reads: Vec<NoneRead> = polydat_grammar::refs::referenced_names(text)
267        .into_iter()
268        .filter_map(|name| match kernel.lookup(&name) {
269            None => Some(NoneRead::Unbound(name)),
270            Some(Value::None) => Some(NoneRead::BoundNone(name)),
271            Some(_) => None,
272        })
273        .collect();
274    if reads.is_empty() {
275        SpecError::Failed(message)
276    } else {
277        SpecError::ReadsNone { reads, message }
278    }
279}
280
281pub(crate) fn evaluate_spec_internal(
282    spec_text: &str,
283    kernel: &dyn Lookup,
284) -> Result<Vec<Value>, SpecError> {
285    if let Some(values) = try_eval_all_cursor(spec_text, kernel)? {
286        return Ok(values);
287    }
288    // A *bare identifier* source is a direct wire/param/const
289    // reference (comprehension_forms.md §3.1.4). It resolves
290    // against the kernel chain — the same `kernel.lookup` the
291    // `{name}` interpolation path uses — and its value is peeled or
292    // wrapped by `iteration_interior`, so `mnc in mnc_values` works
293    // identically to `mnc in {mnc_values}`. A bare name that does
294    // not resolve reads None, and the diagnostic an API that refuses
295    // it reports carries a quoting hint; it is never bound as its own
296    // name-string.
297    if is_single_bare_ident(spec_text) {
298        let src = spec_text.trim();
299        let v = read_name(kernel, src, || {
300            format!(
301                "comprehension source `{src}` did not resolve to a value — no \
302                 wire, const, param, or outer iter-var by that name is in scope \
303                 here. If you meant the literal string \"{src}\", quote it: \
304                 `\"{src}\"`."
305            )
306        })?;
307        return Ok(peel_or_wrap(v));
308    }
309    // A placeholder that is the whole source reads the value its name
310    // is bound to, with its type, exactly as the bare name above does
311    // (comprehension_forms.md §3.1.5). A composed name (`{a_{b}}`) has
312    // no bare form, and this is how it is read.
313    if let Some(v) = read_whole_placeholder(spec_text, kernel)? {
314        return Ok(peel_or_wrap(v));
315    }
316    // A wholly quoted source interpolates inside its quotes and then
317    // strips or stays whole by its quote kind.
318    if let Some(values) = try_eval_quoted(spec_text, kernel)? {
319        return Ok(values);
320    }
321    // A bracketed list is read element by element before any text is
322    // substituted, so an element that is a whole placeholder reads its
323    // value and an element holding one substitutes text.
324    if let Some(values) = try_eval_bracket_list(spec_text, kernel, true)? {
325        return Ok(values);
326    }
327    let interpolated = interpolate_reading(spec_text, kernel)?;
328    // What the interpolated text evaluates to. A failure that reads a
329    // free name the scope does not bind, or binds to None, is that read
330    // of None.
331    evaluate_interpolated(&interpolated, kernel).map_err(|e| match e {
332        SpecError::Failed(message) => failure_reading(&interpolated, kernel, message),
333        reads_none => reads_none,
334    })
335}
336
337/// [`evaluate_spec_internal`] past interpolation: the source forms over
338/// the interpolated text.
339fn evaluate_interpolated(interpolated: &str, kernel: &dyn Lookup) -> Result<Vec<Value>, SpecError> {
340    // List comprehension sugar `[e1, e2…, e3]`
341    // (comprehension_forms.md §3.1.3). Resolved after interpolation so `{name}` placeholders inside
342    // elements expand first; before the const-eval fallthrough so
343    // bracket structure isn't misparsed as an array-literal expr.
344    if let Some(values) = try_eval_bracket_list(interpolated, kernel, false)? {
345        return Ok(values);
346    }
347    // Range operator (`a..b`, `a..=b`, `a..b..s`, `a..=b..s`;
348    // comprehension_forms.md §3.1, polydat_grammar.md §16.2). Bounds
349    // and step are Polydat const expressions evaluated at this
350    // (post-interpolation) point.
351    if let Some(values) = try_eval_range(interpolated, kernel.ledger())? {
352        return Ok(values);
353    }
354    // Named generators (comprehension_forms.md §3.1).
355    if let Some(values) = try_eval_generator(interpolated)? {
356        return Ok(values);
357    }
358    // Set operators on lists (comprehension_forms.md §3.1).
359    if let Some(values) = try_eval_setop(interpolated, kernel)? {
360        return Ok(values);
361    }
362    // Sequencer expansions (bucket / concat_seq / interval_seq;
363    // comprehension_forms.md §3.1).
364    if let Some(values) = try_eval_sequencer(interpolated, kernel)? {
365        return Ok(values);
366    }
367    // Kernel-aware partition sources — `subdivide(outer, n)` where
368    // `outer` is a partition iter-var bound by an enclosing clause
369    // (cursor_partitions.md §7.1).
370    if let Some(values) = try_eval_partition_call(interpolated, kernel, false)? {
371        return Ok(values);
372    }
373    // `<param>.partitions` in comprehension position resolves the
374    // param's spec string and expands it into its PartitionList
375    // (cursor_partitions.md §7.1).
376    if let Some(values) = try_eval_param_partitions(interpolated, kernel, false)? {
377        return Ok(values);
378    }
379    match crate::dsl::compile::eval_const_expr_for(interpolated, kernel.ledger()) {
380        // Relaxed source resolution (comprehension_forms.md §3.1.2):
381        // a resolved value is peeled one level if it has an iteration
382        // interior (native vector, JSON array, PartitionList, or a
383        // string → its comprehension tokens), else wrapped as a
384        // singleton. `iteration_interior` is the single place that
385        // decision is made.
386        Ok(v) => Ok(
387            match crate::iteration::comprehension::source_values::iteration_interior(&v) {
388                Some(interior) => interior,
389                None => vec![v],
390            },
391        ),
392        // Fall back to the literal-list parse only when the text
393        // is unambiguously a comma-separated list of literals
394        // (e.g. `1, 10, 100` — `eval_const_expr` doesn't accept
395        // that shape because it isn't a single Polydat expression).
396        // Anything that looks like an expression (parens, GK
397        // operators, identifiers other than `true`/`false`) was
398        // *meant* to evaluate; if it failed, we MUST surface the
399        // failure rather than silently splitting and
400        // handing the workload an iter-var like
401        // `matching_profiles('x'` (truncated), which would produce
402        // malformed downstream output far removed from the fault.
403        Err(eval_err) => {
404            // A single bare identifier never reaches here: it is a
405            // reference, resolved or refused above. An unbracketed
406            // bare label list (`a, b, c`) keeps string-token striping
407            // (comprehension_forms.md §3.1.4).
408            if looks_like_literal_list(interpolated) {
409                // A bare unquoted token list strips on the same
410                // separator rule as a string comprehension.
411                Ok(
412                    crate::iteration::comprehension::source_values::strip_string_tokens(
413                        interpolated,
414                    ),
415                )
416            } else {
417                Err(format!(
418                    "for_each clause expression failed to evaluate: {eval_err}\n\
419                     spec: {interpolated}\n\
420                     If this was meant as a literal list (e.g. `1, 10, 100`), \
421                     it should contain only literal values separated by commas. \
422                     If it was meant as an expression, fix the underlying \
423                     evaluation error."
424                )
425                .into())
426            }
427        }
428    }
429}
430
431/// List comprehension sugar (comprehension_forms.md §3.1.3). Evaluate a
432/// bracketed source `[e1, e2…, e3]` to its bound sequence,
433/// peeling exactly one level:
434///   - a plain element contributes its value, whole (no peel);
435///   - a spread element `S…` / `S...` contributes `S`'s
436///     iteration interior (peel one level); a non-iterable `S`
437///     under spread is a hard error.
438///
439/// Elements are parsed by the core expression grammar: a bare
440/// identifier is a wire/param reference (resolved against the
441/// kernel), a quoted token is a string, numbers/bools are
442/// literals. Returns `Ok(None)` when `text` is not a bracketed
443/// list (so the caller falls through to the other source forms).
444///
445/// With `placeholders`, `text` is the source as written: an element
446/// that is a whole placeholder reads the value its name is bound to
447/// (comprehension_forms.md §3.1.5), and any other element substitutes
448/// its placeholders as text before it is read. Without it, `text` has
449/// been interpolated already.
450fn try_eval_bracket_list(
451    text: &str,
452    kernel: &dyn Lookup,
453    placeholders: bool,
454) -> Result<Option<Vec<Value>>, SpecError> {
455    let t = text.trim();
456    if !(t.starts_with('[') && t.ends_with(']') && t.len() >= 2) {
457        return Ok(None);
458    }
459    let inner = &t[1..t.len() - 1];
460    if inner.trim().is_empty() {
461        return Ok(Some(Vec::new()));
462    }
463    let mut out = Vec::new();
464    for elem in split_args_top_level(inner) {
465        let elem = elem.trim();
466        // Spread suffix: `…` (U+2026) or `...`.
467        let (expr, spread) = if let Some(stripped) = elem.strip_suffix('…') {
468            (stripped.trim(), true)
469        } else if let Some(stripped) = elem.strip_suffix("...") {
470            (stripped.trim(), true)
471        } else {
472            (elem, false)
473        };
474        if expr.is_empty() {
475            return Err("empty element in list comprehension `[...]`"
476                .to_string()
477                .into());
478        }
479        let value = if !placeholders {
480            eval_element_value(expr, kernel)?
481        } else if let Some(value) = read_whole_placeholder(expr, kernel)? {
482            value
483        } else {
484            eval_element_value(&interpolate_reading(expr, kernel)?, kernel)?
485        };
486        if spread {
487            match crate::iteration::comprehension::source_values::iteration_interior(&value) {
488                Some(interior) => out.extend(interior),
489                None => {
490                    return Err(format!(
491                        "list comprehension spread `{expr}…` requires an iterable \
492                     source, but `{expr}` resolved to a scalar \
493                     {ty:?}. Use `[{expr}]` to pass it as a single element, \
494                     or supply a list.",
495                        ty = value.port_type(),
496                    )
497                    .into());
498                }
499            }
500        } else {
501            out.push(value);
502        }
503    }
504    Ok(Some(out))
505}
506
507/// Resolve one list-comprehension element to a single value (no
508/// peeling). A bare identifier is a wire/param/const reference
509/// resolved against the kernel; anything else (quoted string,
510/// number, bool, expression) goes through the const evaluator.
511/// An unresolved bare reference reads None, never a silent literal-name
512/// binding, and the diagnostic an API that refuses it reports carries a
513/// quoting hint (comprehension_forms.md §3.1.4).
514fn eval_element_value(expr: &str, kernel: &dyn Lookup) -> Result<Value, SpecError> {
515    let e = expr.trim();
516    if is_single_bare_ident(e) {
517        return read_name(kernel, e, || {
518            format!(
519                "list element `{e}` did not resolve to a value — no wire, const, \
520             param, or outer iter-var by that name is in scope here. \
521             If you meant the literal string \"{e}\", quote it: `\"{e}\"`."
522            )
523        });
524    }
525    crate::dsl::compile::eval_const_expr_for(e, kernel.ledger()).map_err(|err| {
526        failure_reading(
527            e,
528            kernel,
529            format!("list element `{e}` failed to evaluate: {err}"),
530        )
531    })
532}
533
534/// True when `text` is exactly one bare identifier
535/// (`[A-Za-z_][A-Za-z0-9_]*`), excluding `true`/`false`. A bare
536/// identifier source is a direct reference resolved against the
537/// kernel (comprehension_forms.md §3.1.4); the keyword literals are
538/// values.
539fn is_single_bare_ident(text: &str) -> bool {
540    let t = text.trim();
541    if t == "true" || t == "false" {
542        return false;
543    }
544    let mut chars = t.chars();
545    match chars.next() {
546        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
547        _ => return false,
548    }
549    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
550}
551
552/// Heuristic: does this interpolated spec text look like a
553/// "literal list" (comma-separated literals like `1, 10, 100` or
554/// `foo, bar, baz`) rather than an expression?
555///
556/// True only when no character suggests an expression: no
557/// parentheses, no operators, no string-quote characters that
558/// would imply a function-call shape. Whitespace, digits,
559/// alphanumerics, dots (for floats), minus (for negatives), and
560/// commas (the separator) are all OK.
561///
562/// The gate keeps list sources (`k in 1, 10, 100`) working through
563/// the literal-list fallback while still surfacing real evaluation
564/// failures for expression sources like `matching_profiles('x',
565/// 'y')`. A wrong call on a borderline case is cheap: it produces a
566/// clearer error from the eval layer instead of swallowed garbage.
567fn looks_like_literal_list(text: &str) -> bool {
568    let trimmed = text.trim();
569    if trimmed.is_empty() {
570        return false;
571    }
572    !trimmed.chars().any(|c| {
573        matches!(
574            c,
575            '(' | ')'
576                | '['
577                | ']'
578                | '{'
579                | '}'
580                | '\''
581                | '"'
582                | '+'
583                | '*'
584                | '/'
585                | '%'
586                | '='
587                | '<'
588                | '>'
589                | '!'
590                | '&'
591                | '|'
592                | '~'
593                | '^'
594                | '?'
595        )
596    })
597}
598
599/// Pre-evaluate a clause's spec text at synthesis time, using
600/// `probes` for prior clauses' first values and `workload_params`
601/// as a fallback source for names not yet promoted to workload-
602/// kernel `const` bindings.
603///
604/// The runtime dispatcher uses [`evaluate_spec`] directly because
605/// (a) the runtime kernel has prior-clause values as real input
606/// slots, not text probes, and (b) by then workload params are
607/// already injected as final bindings on the for_each scope's
608/// kernel via the synthesis path.
609pub fn pre_evaluate_clause(
610    spec_text: &str,
611    parent_kernel: &dyn Lookup,
612    workload_params: &HashMap<String, String>,
613    probes: &HashMap<String, String>,
614) -> Result<Vec<Value>, String> {
615    // The `all(<cursor>)` form resolves cursor extents from the
616    // parent kernel's auxiliary outputs; it doesn't fit the
617    // const-eval pipeline (which returns a single Value), so it's
618    // intercepted here too — same as `evaluate_spec`.
619    if let Some(values) = try_eval_all_cursor(spec_text, parent_kernel)? {
620        return Ok(values);
621    }
622    // A bare identifier source is a direct reference
623    // (comprehension_forms.md §3.1.4). At synthesis it resolves
624    // against a prior iter-var probe, then the parent kernel, then
625    // the workload params, so a dependent clause (e.g. `limit in
626    // {k_{k}_limits}`) sees the *typed* prior value and infers the
627    // right extern type, rather than the literal name typed as a
628    // string.
629    // What a reference to `name` reads at synthesis.
630    let reference = |name: &str| -> Option<Vec<Value>> {
631        if let Some(pv) = probes.get(name) {
632            return Some(crate::iteration::comprehension::source_values::strip_string_tokens(pv));
633        }
634        if let Some(v) = parent_kernel.lookup(name) {
635            return Some(peel_or_wrap(v));
636        }
637        workload_params
638            .get(name)
639            .map(|s| crate::iteration::comprehension::source_values::strip_string_tokens(s))
640    };
641    // A placeholder that is the whole source is the same reference
642    // (§3.1.5), once a composed name's leaves are substituted, so the
643    // type inferred here is the type the runtime path binds. One that
644    // does not resolve falls through and is reported as unresolved.
645    if let Some(body) = whole_placeholder(spec_text)
646        && let Ok(composed) = interpolate_with_lookup(body, |name| {
647            probes
648                .get(name)
649                .cloned()
650                .or_else(|| parent_kernel.lookup(name).map(|v| v.to_display_string()))
651                .or_else(|| workload_params.get(name).cloned())
652        })
653        && is_name_path(composed.trim())
654        && let Some(values) = reference(composed.trim())
655    {
656        return Ok(values);
657    }
658    if is_single_bare_ident(spec_text) {
659        let name = spec_text.trim();
660        if let Some(values) = reference(name) {
661            return Ok(values);
662        }
663        return Err(format!(
664            "comprehension source `{name}` did not resolve to a value — no wire, \
665             const, param, or outer iter-var by that name is in scope here. \
666             If you meant the literal string \"{name}\", quote it: `\"{name}\"`."
667        ));
668    }
669    let mut text = spec_text.to_string();
670    for (var, probe_value) in probes {
671        text = text.replace(&format!("{{{var}}}"), probe_value);
672    }
673
674    let interpolated = interpolate_with_lookup(&text, |name| {
675        parent_kernel
676            .lookup(name)
677            .map(|v| v.to_display_string())
678            .or_else(|| workload_params.get(name).cloned())
679    })?;
680
681    // The range operator, on the pre-evaluation path too.
682    if let Some(values) = try_eval_range(&interpolated, parent_kernel.ledger())? {
683        return Ok(values);
684    }
685    // The same generator, set-operator, and sequencer forms the
686    // runtime path recognizes.
687    if let Some(values) = try_eval_generator(&interpolated)? {
688        return Ok(values);
689    }
690    if let Some(values) = try_eval_setop(&interpolated, parent_kernel)? {
691        return Ok(values);
692    }
693    if let Some(values) = try_eval_sequencer(&interpolated, parent_kernel)? {
694        return Ok(values);
695    }
696    // Kernel-aware partition sources, as on the runtime path
697    // (cursor_partitions.md §7.1). At pre-evaluation the outer
698    // iter-var may not be installed yet; `try_eval_partition_call`
699    // then returns a single placeholder partition so iter-var type
700    // detection yields `ext`.
701    if let Some(values) = try_eval_partition_call(&interpolated, parent_kernel, true)? {
702        return Ok(values);
703    }
704    // `<param>.partitions` in comprehension position, by the same rule
705    // as the runtime path; the param may already be installed here.
706    if let Some(values) = try_eval_param_partitions(&interpolated, parent_kernel, true)? {
707        return Ok(values);
708    }
709    let value_str =
710        match crate::dsl::compile::eval_const_expr_for(&interpolated, parent_kernel.ledger()) {
711            Ok(Value::Str(s)) => s.to_string(),
712            // `<param>.partitions` and `partitions(spec, ...)`
713            // (cursor_partitions.md §7.1) both evaluate to a `PartitionList` Ext value. Unpack
714            // its entries into a vec of individual `Partition`
715            // values so the for-clause iterates partition-by-
716            // partition.
717            Ok(ref v) if v.as_partition_list().is_some() => {
718                let list = v.as_partition_list().unwrap();
719                return Ok(list
720                    .as_slice()
721                    .iter()
722                    .map(|p| Value::from_partition(*p))
723                    .collect());
724            }
725            Ok(other) => return Ok(vec![other]),
726            // Mirrors `evaluate_spec`'s gating: only fall back to
727            // parse_list_with_types when the text is unambiguously a
728            // literal list. See `looks_like_literal_list` for the
729            // rationale.
730            Err(eval_err) => {
731                if looks_like_literal_list(&interpolated) {
732                    interpolated
733                } else {
734                    return Err(format!(
735                        "for_each clause expression failed to evaluate: {eval_err}\n\
736                     spec: {interpolated}\n\
737                     If this was meant as a literal list (e.g. `1, 10, 100`), \
738                     it should contain only literal values separated by commas. \
739                     If it was meant as an expression, fix the underlying \
740                     evaluation error."
741                    ));
742                }
743            }
744        };
745    Ok(parse_list_with_types(&value_str))
746}
747
748/// Parse a comma-separated text list, detecting each element's
749/// native type, as element types are inferred
750/// (polydat_grammar.md §16.3): `"1, 10"` → `[U64(1), U64(10)]`, `"1.5, 2.5"` → `[F64(...)]`,
751/// mixed → each element gets its own native type.
752pub fn parse_list_with_types(text: &str) -> Vec<Value> {
753    text.split(',')
754        .map(str::trim)
755        .filter(|s| !s.is_empty())
756        .map(|s| {
757            if let Ok(n) = s.parse::<u64>() {
758                Value::U64(n)
759            } else if let Ok(n) = s.parse::<f64>() {
760                Value::F64(n)
761            } else if s == "true" {
762                Value::Bool(true)
763            } else if s == "false" {
764                Value::Bool(false)
765            } else {
766                Value::Str(s.to_string().into())
767            }
768        })
769        .collect()
770}
771
772/// Recognize the comprehension-level `all(<cursor>)` clause form
773/// and resolve it against the parent kernel's cursor extent
774/// auxiliary outputs.
775///
776/// Cursors declared via the Polydat `cursor name = Cursor(start, end)`
777/// shape compile to two well-known auxiliary outputs on the
778/// kernel: `__cursor_extent_<name>_start` and
779/// `__cursor_extent_<name>_end`. Reading those gives the cursor's
780/// resolved extent at scope-init time. `all(<cursor>)` lowers to
781/// the half-open ordinal range `[start, end)` as a `Vec<Value::U64>`.
782///
783/// The source reads the cursor's extent, not a value named after the
784/// cursor ([`polydat_grammar::comprehension::source::Source::names_read`]).
785///
786/// Returns:
787/// - `Ok(Some(values))` if `spec_text` matches the `all(<ident>)`
788///   shape and the cursor's extent resolved successfully.
789/// - `Ok(None)` if `spec_text` doesn't match — caller continues
790///   with the normal interpolation + const-eval pipeline.
791/// - [`SpecError::ReadsNone`] if an extent output is not bound in
792///   scope (no cursor of that name is declared at or above it) or is
793///   bound to None.
794/// - [`SpecError::Failed`] if the extent is not an ordinal range.
795fn try_eval_all_cursor(
796    spec_text: &str,
797    kernel: &dyn Lookup,
798) -> Result<Option<Vec<Value>>, SpecError> {
799    use polydat_grammar::comprehension::source::{all_cursor_argument, cursor_extent_names};
800    let Some(cursor_name) = all_cursor_argument(spec_text) else {
801        return Ok(None);
802    };
803    let [start_key, end_key] = cursor_extent_names(cursor_name);
804    let extent = |key: &str| -> Result<u64, SpecError> {
805        match read_name(kernel, key, || {
806            format!(
807                "all({cursor_name}): cursor '{cursor_name}' has no resolvable extent — \
808                 check that the cursor is declared at or above this scope and that \
809                 its range arguments are init-resolvable. Looked for output '{key}'."
810            )
811        })? {
812            Value::U64(n) => Ok(n),
813            other => Err(format!(
814                "all({cursor_name}): extent output '{key}' is {}, not an ordinal",
815                other.to_display_string()
816            )
817            .into()),
818        }
819    };
820    let start = extent(&start_key)?;
821    let end = extent(&end_key)?;
822
823    if end < start {
824        return Err(format!(
825            "all({cursor_name}): cursor extent end={end} is less than start={start} — \
826             cannot enumerate a negative-extent range."
827        )
828        .into());
829    }
830    Ok(Some((start..end).map(Value::U64).collect()))
831}
832
833fn is_valid_ident(s: &str) -> bool {
834    let mut chars = s.chars();
835    match chars.next() {
836        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
837        _ => return false,
838    }
839    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
840}
841
842/// Recognise the range operator (comprehension_forms.md §3.1,
843/// polydat_grammar.md §16.2) and expand it into a `Vec<Value>`.
844///
845/// Four shapes:
846/// - `a..b`         half-open with step 1
847/// - `a..=b`        closed with step 1
848/// - `a..b..s`      half-open with step `s`
849/// - `a..=b..s`     closed with step `s`
850///
851/// Bounds and step are Polydat const expressions; this function
852/// evaluates each segment via `eval_const_expr_for(segment, ledger)`. Numeric
853/// type follows the bounds: if both are integers, the
854/// emitted list is `Value::U64`; otherwise `Value::F64`.
855///
856/// Returns:
857/// - `Ok(Some(values))` on a successful range expansion.
858/// - `Ok(None)` when `text` doesn't have a top-paren-depth
859///   `..` at all — caller falls through to the standard
860///   const-eval / list-parse path.
861/// - `Err(...)` when the form matches but evaluation fails
862///   (bound non-numeric, step is zero, bounds diverge from
863///   step direction, etc.).
864fn try_eval_range(
865    text: &str,
866    ledger: &std::sync::Arc<crate::kernel::CompileLedger>,
867) -> Result<Option<Vec<Value>>, String> {
868    let trimmed = text.trim();
869    let chars: Vec<char> = trimmed.chars().collect();
870
871    // Find every top-paren-depth `..` (with optional `=`).
872    // Returns positions of the `..` start and whether the
873    // following `=` was present.
874    let mut splits: Vec<(usize, bool)> = Vec::new();
875    let mut depth: i32 = 0;
876    let mut i = 0;
877    while i < chars.len() {
878        let c = chars[i];
879        match c {
880            '(' | '[' | '{' => depth += 1,
881            ')' | ']' | '}' => depth -= 1,
882            '"' | '\'' => {
883                // Skip the rest of the quoted run.
884                let q = c;
885                i += 1;
886                while i < chars.len() && chars[i] != q {
887                    i += 1;
888                }
889            }
890            '.' if depth == 0 && i + 1 < chars.len() && chars[i + 1] == '.' => {
891                let inclusive = i + 2 < chars.len() && chars[i + 2] == '=';
892                splits.push((i, inclusive));
893                i += if inclusive { 3 } else { 2 };
894                continue;
895            }
896            _ => {}
897        }
898        i += 1;
899    }
900
901    if splits.is_empty() {
902        return Ok(None);
903    }
904    if splits.len() > 2 {
905        return Err(format!(
906            "range expression '{trimmed}': more than two `..` operators \
907             at top level — expected one of `a..b`, `a..=b`, `a..b..s`, \
908             or `a..=b..s`"
909        ));
910    }
911    if splits.len() == 2 && splits[1].1 {
912        return Err(format!(
913            "range expression '{trimmed}': step delimiter cannot be \
914             `..=` — only the bound separator may be inclusive"
915        ));
916    }
917
918    // Slice out the segments.
919    let inclusive = splits[0].1;
920    let first_end = splits[0].0;
921    let after_first = first_end + if inclusive { 3 } else { 2 };
922    let (start_text, mid_text, step_text) = match splits.len() {
923        1 => {
924            let start_s: String = chars[..first_end].iter().collect();
925            let end_s: String = chars[after_first..].iter().collect();
926            (start_s, end_s, None)
927        }
928        2 => {
929            let mid_end = splits[1].0;
930            let after_mid = mid_end + 2; // `..` only, not `..=`
931            let start_s: String = chars[..first_end].iter().collect();
932            let mid_s: String = chars[after_first..mid_end].iter().collect();
933            let step_s: String = chars[after_mid..].iter().collect();
934            (start_s, mid_s, Some(step_s))
935        }
936        _ => unreachable!(),
937    };
938
939    let start_val = eval_range_segment(&start_text, "range start", ledger)?;
940    let end_val = eval_range_segment(&mid_text, "range end", ledger)?;
941    let step_val = match step_text {
942        Some(s) => Some(eval_range_segment(&s, "range step", ledger)?),
943        None => None,
944    };
945
946    Ok(Some(expand_range(
947        start_val, end_val, step_val, inclusive, trimmed,
948    )?))
949}
950
951fn eval_range_segment(
952    text: &str,
953    what: &str,
954    ledger: &std::sync::Arc<crate::kernel::CompileLedger>,
955) -> Result<Value, String> {
956    let trimmed = text.trim();
957    if trimmed.is_empty() {
958        return Err(format!("range expression: {what} is empty"));
959    }
960    crate::dsl::compile::eval_const_expr_for(trimmed, ledger)
961        .map_err(|e| format!("range expression: {what} '{trimmed}' did not const-fold — {e}"))
962}
963
964/// Materialise the value list once start/end/step have been
965/// const-folded. If any of the three is `F64`, the whole list
966/// is `F64`; otherwise everything is `U64`.
967fn expand_range(
968    start: Value,
969    end: Value,
970    step: Option<Value>,
971    inclusive: bool,
972    src: &str,
973) -> Result<Vec<Value>, String> {
974    let any_float = matches!(start, Value::F64(_))
975        || matches!(end, Value::F64(_))
976        || matches!(step, Some(Value::F64(_)));
977
978    let to_f64 = |v: &Value| -> Result<f64, String> {
979        match v {
980            Value::U64(n) => Ok(*n as f64),
981            Value::F64(f) => Ok(*f),
982            other => Err(format!(
983                "range expression '{src}': bound has non-numeric value {other:?}"
984            )),
985        }
986    };
987    let to_i64 = |v: &Value| -> Result<i64, String> {
988        match v {
989            Value::U64(n) => i64::try_from(*n).map_err(|_| {
990                format!("range expression '{src}': bound {n} exceeds signed 64-bit range")
991            }),
992            Value::F64(f) => {
993                if f.fract() == 0.0 && *f >= i64::MIN as f64 && *f <= i64::MAX as f64 {
994                    Ok(*f as i64)
995                } else {
996                    Err(format!(
997                        "range expression '{src}': float bound {f} is not integral; \
998                         mix with an explicit float step (e.g. `1.0..10..0.5`) for a float range"
999                    ))
1000                }
1001            }
1002            other => Err(format!(
1003                "range expression '{src}': bound has non-numeric value {other:?}"
1004            )),
1005        }
1006    };
1007
1008    if any_float {
1009        let s = to_f64(&start)?;
1010        let e = to_f64(&end)?;
1011        let st = match step.as_ref() {
1012            Some(v) => to_f64(v)?,
1013            None => 1.0,
1014        };
1015        if st == 0.0 {
1016            return Err(format!("range expression '{src}': step is zero"));
1017        }
1018        // Direction must match (start < end ⇒ step > 0; start > end ⇒ step < 0).
1019        if (e - s).is_sign_positive() && st < 0.0 {
1020            return Ok(Vec::new());
1021        }
1022        if (e - s).is_sign_negative() && st > 0.0 {
1023            return Ok(Vec::new());
1024        }
1025        let mut out = Vec::new();
1026        let mut cur = s;
1027        let cmp = |x: f64| -> bool {
1028            if st > 0.0 {
1029                if inclusive {
1030                    x <= e + 1e-12
1031                } else {
1032                    x < e - 1e-12
1033                }
1034            } else if inclusive {
1035                x >= e - 1e-12
1036            } else {
1037                x > e + 1e-12
1038            }
1039        };
1040        while cmp(cur) {
1041            out.push(Value::F64(cur));
1042            cur += st;
1043        }
1044        return Ok(out);
1045    }
1046
1047    // Integer range.
1048    let s = to_i64(&start)?;
1049    let e = to_i64(&end)?;
1050    let st = match step.as_ref() {
1051        Some(v) => to_i64(v)?,
1052        None => 1,
1053    };
1054    if st == 0 {
1055        return Err(format!("range expression '{src}': step is zero"));
1056    }
1057    if st > 0 && s > e {
1058        return Ok(Vec::new());
1059    }
1060    if st < 0 && s < e {
1061        return Ok(Vec::new());
1062    }
1063    let mut out = Vec::new();
1064    let mut cur = s;
1065    let cmp = |x: i64| -> bool {
1066        if st > 0 {
1067            if inclusive { x <= e } else { x < e }
1068        } else if inclusive {
1069            x >= e
1070        } else {
1071            x > e
1072        }
1073    };
1074    while cmp(cur) {
1075        if cur < 0 {
1076            return Err(format!(
1077                "range expression '{src}': negative value {cur} can't be \
1078                 represented as Value::U64; use a float range \
1079                 (mix any bound or step with `.0`) for signed walks"
1080            ));
1081        }
1082        out.push(Value::U64(cur as u64));
1083        cur = cur.saturating_add(st);
1084        if (st > 0 && cur < s) || (st < 0 && cur > s) {
1085            // saturated; would loop forever on overflow.
1086            break;
1087        }
1088    }
1089    Ok(out)
1090}
1091
1092// ============================================================
1093// Function-call dispatch (Pushes 7, 8, 9)
1094// ============================================================
1095
1096/// Recognise `name(args)` at the top paren depth. Returns
1097/// `Some((name, args))` when the entire `text` is exactly
1098/// one function call (with balanced parens, possibly empty
1099/// args). Quoted strings within args are walked as opaque
1100/// runs so internal commas / parens don't trip the split.
1101fn parse_func_call(text: &str) -> Option<(&str, &str)> {
1102    let trimmed = text.trim();
1103    if !trimmed.ends_with(')') {
1104        return None;
1105    }
1106    let open = trimmed.find('(')?;
1107    let name = trimmed[..open].trim();
1108    if name.is_empty() || !is_valid_ident(name) {
1109        return None;
1110    }
1111    // Make sure the closing `)` matches the opening — i.e.
1112    // the entire text is a single call, not `f(a) + g(b)`.
1113    let chars: Vec<char> = trimmed.chars().collect();
1114    let mut depth = 0i32;
1115    let mut in_quote: Option<char> = None;
1116    for (i, &c) in chars.iter().enumerate().skip(open) {
1117        match (c, in_quote) {
1118            ('"' | '\'', None) => in_quote = Some(c),
1119            (q, Some(open_q)) if q == open_q => in_quote = None,
1120            ('(', None) => depth += 1,
1121            (')', None) => {
1122                depth -= 1;
1123                if depth == 0 {
1124                    if i != chars.len() - 1 {
1125                        return None; // close mid-text
1126                    }
1127                    let args: String = chars[open + 1..i].iter().collect();
1128                    // SAFETY: trimmed lives for fn duration; we
1129                    // index into the original string via slices
1130                    // with care. Instead of returning a borrowed
1131                    // slice from the local `args` String, return
1132                    // the slices directly from `trimmed`.
1133                    let _ = args;
1134                    let name_slice = &trimmed[..open];
1135                    let args_slice = &trimmed[open + 1..trimmed.len() - 1];
1136                    return Some((name_slice.trim(), args_slice));
1137                }
1138            }
1139            _ => {}
1140        }
1141    }
1142    None
1143}
1144
1145/// Split a function-argument list on top-level commas. Skips
1146/// commas inside parens, brackets, braces, or quoted strings.
1147fn split_args_top_level(args: &str) -> Vec<&str> {
1148    let mut out: Vec<&str> = Vec::new();
1149    let chars: Vec<char> = args.chars().collect();
1150    let bytes_per_char: Vec<usize> = chars.iter().map(|c| c.len_utf8()).collect();
1151    let mut start_byte = 0usize;
1152    let mut byte = 0usize;
1153    let mut depth = 0i32;
1154    let mut in_quote: Option<char> = None;
1155    for (i, &c) in chars.iter().enumerate() {
1156        match (c, in_quote) {
1157            ('"' | '\'', None) => in_quote = Some(c),
1158            (q, Some(open_q)) if q == open_q => in_quote = None,
1159            ('(' | '[' | '{', None) => depth += 1,
1160            (')' | ']' | '}', None) => depth -= 1,
1161            (',', None) if depth == 0 => {
1162                let seg = &args[start_byte..byte];
1163                out.push(seg.trim());
1164                start_byte = byte + bytes_per_char[i];
1165            }
1166            _ => {}
1167        }
1168        byte += bytes_per_char[i];
1169    }
1170    let last = &args[start_byte..];
1171    if !last.trim().is_empty() || !out.is_empty() {
1172        out.push(last.trim());
1173    }
1174    out
1175}
1176
1177/// Parse a single argument text as a `u64`. Errors carry the
1178/// expected-form context for the user.
1179fn parse_u64_arg(text: &str, what: &str) -> Result<u64, String> {
1180    let trimmed = text.trim();
1181    trimmed
1182        .parse::<u64>()
1183        .map_err(|_| format!("{what}: expected non-negative integer, got '{trimmed}'"))
1184}
1185
1186/// Parse a single argument as either u64 or f64. Returns the
1187/// f64 representation regardless (callers that need an int
1188/// check `.fract() == 0.0`).
1189fn parse_num_arg(text: &str, what: &str) -> Result<f64, String> {
1190    let trimmed = text.trim();
1191    trimmed
1192        .parse::<f64>()
1193        .map_err(|_| format!("{what}: expected numeric, got '{trimmed}'"))
1194}
1195
1196// ============================================================
1197// Named generators (comprehension_forms.md §3.1.3)
1198// ============================================================
1199
1200/// A named generator: a call in source position that expands its
1201/// literal arguments into a finite list of values
1202/// (comprehension_forms.md §3.1.3, "Named generators").
1203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1204pub enum NamedGenerator {
1205    /// `fib(n)`: the first `n` Fibonacci numbers.
1206    Fib,
1207    /// `fib_until(max)`: the Fibonacci numbers up to `max`.
1208    FibUntil,
1209    /// `pow2(n)`: the first `n` powers of two.
1210    Pow2,
1211    /// `pow2_until(max)`: the powers of two up to `max`.
1212    Pow2Until,
1213    /// `binomial(n)`: row `n` of Pascal's triangle.
1214    Binomial,
1215    /// `geometric(start, factor, n)`: `n` terms of a geometric series.
1216    Geometric,
1217    /// `geometric_until(start, factor, max)`: a geometric series up to `max`.
1218    GeometricUntil,
1219    /// `linear_starts(start, end, n)`: the starts of `n` equal steps.
1220    LinearStarts,
1221    /// `linear_steps(start, end, n)`: `n` evenly spaced points, both ends included.
1222    LinearSteps,
1223    /// `log_steps(start, end, n)`: `n` log-spaced points, both ends included.
1224    LogSteps,
1225}
1226
1227impl NamedGenerator {
1228    /// Every named generator, in declaration order.
1229    pub fn all() -> impl Iterator<Item = NamedGenerator> {
1230        std::iter::successors(Some(Self::Fib), |g| g.after())
1231    }
1232
1233    /// The generator after `self` in [`Self::all`], `None` after the
1234    /// last. The match is exhaustive, so a new variant does not
1235    /// compile until it has a place in the walk.
1236    fn after(self) -> Option<Self> {
1237        use NamedGenerator as G;
1238        match self {
1239            G::Fib => Some(G::FibUntil),
1240            G::FibUntil => Some(G::Pow2),
1241            G::Pow2 => Some(G::Pow2Until),
1242            G::Pow2Until => Some(G::Binomial),
1243            G::Binomial => Some(G::Geometric),
1244            G::Geometric => Some(G::GeometricUntil),
1245            G::GeometricUntil => Some(G::LinearStarts),
1246            G::LinearStarts => Some(G::LinearSteps),
1247            G::LinearSteps => Some(G::LogSteps),
1248            G::LogSteps => None,
1249        }
1250    }
1251
1252    /// The call signature, as written in source position.
1253    pub fn signature(self) -> &'static str {
1254        use NamedGenerator as G;
1255        match self {
1256            G::Fib => "fib(n)",
1257            G::FibUntil => "fib_until(max)",
1258            G::Pow2 => "pow2(n)",
1259            G::Pow2Until => "pow2_until(max)",
1260            G::Binomial => "binomial(n)",
1261            G::Geometric => "geometric(start, factor, n)",
1262            G::GeometricUntil => "geometric_until(start, factor, max)",
1263            G::LinearStarts => "linear_starts(start, end, n)",
1264            G::LinearSteps => "linear_steps(start, end, n)",
1265            G::LogSteps => "log_steps(start, end, n)",
1266        }
1267    }
1268
1269    /// The name a call is written with: the signature up to `(`.
1270    pub fn name(self) -> &'static str {
1271        let sig = self.signature();
1272        &sig[..sig.find('(').unwrap_or(sig.len())]
1273    }
1274
1275    /// The parameter names, from the signature.
1276    fn params(self) -> Vec<&'static str> {
1277        let sig = self.signature();
1278        let inner = &sig[self.name().len() + 1..sig.len() - 1];
1279        inner.split(',').map(str::trim).collect()
1280    }
1281
1282    /// The generator a call name names, if any.
1283    pub fn from_name(name: &str) -> Option<Self> {
1284        Self::all().find(|g| g.name() == name)
1285    }
1286
1287    /// The generator `text` calls, when it is a call of one
1288    /// (`fib({n})`, `log_steps(1, 1000, 4)`).
1289    pub fn of_call(text: &str) -> Option<Self> {
1290        parse_func_call(text).and_then(|(name, _)| Self::from_name(name))
1291    }
1292
1293    /// Whether the generator's values are integers (`u64`); the others
1294    /// yield floats (`f64`).
1295    pub fn yields_integers(self) -> bool {
1296        use NamedGenerator as G;
1297        match self {
1298            G::Fib | G::FibUntil | G::Pow2 | G::Pow2Until | G::Binomial => true,
1299            G::Geometric | G::GeometricUntil | G::LinearStarts | G::LinearSteps | G::LogSteps => {
1300                false
1301            }
1302        }
1303    }
1304
1305    /// Expand the call's argument texts into the generator's values.
1306    fn expand(self, args: &[&str]) -> Result<Vec<Value>, String> {
1307        use NamedGenerator as G;
1308        let params = self.params();
1309        if args.len() != params.len() {
1310            return Err(format!(
1311                "{}: expected {} argument{}, got {}",
1312                self.signature(),
1313                params.len(),
1314                if params.len() == 1 { "" } else { "s" },
1315                args.len()
1316            ));
1317        }
1318        let what = |i: usize| format!("{}.{}", self.name(), params[i]);
1319        let int = |i: usize| parse_u64_arg(args[i], &what(i));
1320        let num = |i: usize| parse_num_arg(args[i], &what(i));
1321        let call = format!("{}({})", self.name(), args.join(", "));
1322        match self {
1323            G::Fib => generate_fib_n(int(0)?, &call),
1324            G::FibUntil => Ok(generate_fib_until(int(0)?)),
1325            G::Pow2 => generate_pow2_n(int(0)?, &call),
1326            G::Pow2Until => Ok(generate_pow2_until(int(0)?)),
1327            G::Binomial => generate_binomial(int(0)?, &call),
1328            G::Geometric => {
1329                let (start, factor) = (num(0)?, num(1)?);
1330                if !(factor.is_finite() && factor > 0.0) {
1331                    return Err(format!(
1332                        "{}: expected a positive, finite number, got {factor}",
1333                        what(1)
1334                    ));
1335                }
1336                generate_geometric(start, factor, int(2)?)
1337            }
1338            G::GeometricUntil => {
1339                let (start, factor) = (num(0)?, num(1)?);
1340                if !(factor.is_finite() && factor > 1.0) {
1341                    return Err(format!(
1342                        "{}: expected a finite number greater than 1, got {factor}",
1343                        what(1)
1344                    ));
1345                }
1346                Ok(generate_geometric_until(start, factor, num(2)?))
1347            }
1348            G::LinearStarts => generate_linear_points(num(0)?, num(1)?, int(2)?, false),
1349            G::LinearSteps => generate_linear_points(num(0)?, num(1)?, int(2)?, true),
1350            G::LogSteps => {
1351                let (start, end) = (num(0)?, num(1)?);
1352                for (i, bound) in [(0, start), (1, end)] {
1353                    if bound.is_nan() || bound <= 0.0 {
1354                        return Err(format!(
1355                            "{}: expected a positive number, got {bound}",
1356                            what(i)
1357                        ));
1358                    }
1359                }
1360                generate_log_steps(start, end, int(2)?)
1361            }
1362        }
1363    }
1364
1365    /// The largest argument a call yields every term of, for a
1366    /// generator whose terms outgrow `u64` as its argument grows:
1367    /// `fib` 93, `pow2` 64, `binomial` 67. `None` for the others.
1368    pub fn largest_valid_argument(self) -> Option<u64> {
1369        use NamedGenerator as G;
1370        match self {
1371            G::Fib => Some(FIB_MAX_N),
1372            G::Pow2 => Some(POW2_MAX_N),
1373            G::Binomial => Some(BINOMIAL_MAX_N),
1374            _ => None,
1375        }
1376    }
1377}
1378
1379/// The largest `n` whose first `n` Fibonacci numbers fit `u64`: term
1380/// 94 is `19740274219868223167`, past `u64::MAX`.
1381const FIB_MAX_N: u64 = 93;
1382/// The largest `n` whose first `n` powers of two fit `u64`: term 65 is
1383/// `2^64`.
1384const POW2_MAX_N: u64 = 64;
1385/// The largest row of Pascal's triangle whose coefficients all fit
1386/// `u64`: `C(68, 31)` is the first coefficient of row 68 past
1387/// `u64::MAX`.
1388const BINOMIAL_MAX_N: u64 = 67;
1389
1390/// Expand a named generator call (`fib(8)`, `linear_steps(0, 1, 4)`)
1391/// into its values. Returns `Ok(None)` when the text is not a call of
1392/// a [`NamedGenerator`] (the caller falls through to the set-op,
1393/// sequencer, and const-eval paths).
1394fn try_eval_generator(text: &str) -> Result<Option<Vec<Value>>, String> {
1395    let Some((name, args)) = parse_func_call(text) else {
1396        return Ok(None);
1397    };
1398    let Some(generator) = NamedGenerator::from_name(name) else {
1399        return Ok(None);
1400    };
1401    generator.expand(&split_args_top_level(args)).map(Some)
1402}
1403
1404/// The refusal of the first named generator call in `text` that fails,
1405/// looking through the arguments of the calls that enclose it
1406/// (`concat(fib(94), 1..3)`), after `{name}` interpolation against
1407/// `kernel`. A named generator's values depend on nothing but its
1408/// arguments, so once they are resolved its failure is the call's
1409/// error wherever it is evaluated (comprehension_forms.md §3.1.3).
1410/// `None` when every named generator call in `text` expands, when an
1411/// interpolation does not resolve, or when `text` calls none.
1412pub fn refused_generator_call(text: &str, kernel: &dyn Lookup) -> Option<String> {
1413    let interpolated = crate::kernel::interp::interpolate_with_lookup(text, |name| {
1414        kernel.lookup(name).map(|v| v.to_display_string())
1415    })
1416    .ok()?;
1417    first_refused_call(&interpolated)
1418}
1419
1420fn first_refused_call(text: &str) -> Option<String> {
1421    let (name, args) = parse_func_call(text)?;
1422    let args = split_args_top_level(args);
1423    match NamedGenerator::from_name(name) {
1424        Some(generator) => generator.expand(&args).err(),
1425        None => args.iter().find_map(|a| first_refused_call(a)),
1426    }
1427}
1428
1429/// First `n` Fibonacci numbers: 1, 1, 2, 3, 5, 8, ...
1430///
1431/// Term 94 is past `u64::MAX`, so `n` above 93 is refused before any
1432/// term is computed.
1433fn generate_fib_n(n: u64, call: &str) -> Result<Vec<Value>, String> {
1434    if n > FIB_MAX_N {
1435        return Err(format!(
1436            "{call}: term {} is past u64::MAX; fib.n is at most {FIB_MAX_N}",
1437            FIB_MAX_N + 1
1438        ));
1439    }
1440    let mut out = Vec::with_capacity(n as usize);
1441    // The pair runs two terms ahead of the last one pushed, past
1442    // `u64::MAX` at the end of `fib(93)`, so it is held in `u128`.
1443    let (mut a, mut b): (u128, u128) = (1, 1);
1444    for _ in 0..n {
1445        out.push(Value::U64(a as u64));
1446        (a, b) = (b, a + b);
1447    }
1448    Ok(out)
1449}
1450
1451/// Fibonacci values up to and including the largest ≤ `max`.
1452///
1453/// The pair is held in `u128`, so the walk reaches the 93rd term,
1454/// the largest in `u64`, even though the term after it does not fit.
1455fn generate_fib_until(max: u64) -> Vec<Value> {
1456    let mut out = Vec::new();
1457    let (mut a, mut b): (u128, u128) = (1, 1);
1458    while a <= u128::from(max) {
1459        out.push(Value::U64(a as u64));
1460        (a, b) = (b, a + b);
1461    }
1462    out
1463}
1464
1465/// `1, 2, 4, ..., 2^(n-1)`. Term 65 is `2^64`, past `u64::MAX`, so `n`
1466/// above 64 is refused.
1467fn generate_pow2_n(n: u64, call: &str) -> Result<Vec<Value>, String> {
1468    if n > POW2_MAX_N {
1469        return Err(format!(
1470            "{call}: term {}, 2^64, is past u64::MAX; pow2.n is at most {POW2_MAX_N}",
1471            POW2_MAX_N + 1
1472        ));
1473    }
1474    Ok((0..n).map(|i| Value::U64(1u64 << i)).collect())
1475}
1476
1477/// Powers of two ≤ max.
1478fn generate_pow2_until(max: u64) -> Vec<Value> {
1479    let mut out = Vec::new();
1480    let mut v: u64 = 1;
1481    loop {
1482        if v > max {
1483            break;
1484        }
1485        out.push(Value::U64(v));
1486        v = match v.checked_mul(2) {
1487            Some(x) => x,
1488            None => break,
1489        };
1490    }
1491    out
1492}
1493
1494/// `start, start*factor, start*factor², …` (n terms).
1495fn generate_geometric(start: f64, factor: f64, n: u64) -> Result<Vec<Value>, String> {
1496    let mut out = crate::derive_support::try_buffer_for(n, "geometric(start, factor, n)")?;
1497    let mut v = start;
1498    for _ in 0..n {
1499        out.push(Value::F64(v));
1500        v *= factor;
1501    }
1502    Ok(out)
1503}
1504
1505/// `start, start*factor, …` ≤ max. The caller refuses a `factor` that
1506/// is not a finite number above 1, so a positive `start` grows past
1507/// `max`; a `start` of zero or less never does and yields nothing.
1508fn generate_geometric_until(start: f64, factor: f64, max: f64) -> Vec<Value> {
1509    let mut out = Vec::new();
1510    let mut v = start;
1511    if start.is_nan() || start <= 0.0 {
1512        return out;
1513    }
1514    while v <= max {
1515        out.push(Value::F64(v));
1516        v *= factor;
1517    }
1518    out
1519}
1520
1521/// Binomial coefficients `C(n, 0), C(n, 1), …, C(n, n)`. Every
1522/// coefficient of rows up to 67 fits `u64`, and every later row has one
1523/// past `u64::MAX`, so a row past 67 is refused, naming its first
1524/// coefficient that does not fit. The walk reaches that coefficient
1525/// within a few terms for any large `n`: `binomial(10^12)` fails at
1526/// `C(n, 2)`, not after a trillion terms.
1527fn generate_binomial(n: u64, call: &str) -> Result<Vec<Value>, String> {
1528    let mut out = Vec::with_capacity(n.min(BINOMIAL_MAX_N) as usize + 1);
1529    // `c ≤ u64::MAX` before each step, so `c · (n − k + 1)` fits u128.
1530    let mut c: u128 = 1;
1531    out.push(Value::U64(1));
1532    for k in 1..=n {
1533        c = c * u128::from(n - k + 1) / u128::from(k);
1534        if c > u128::from(u64::MAX) {
1535            return Err(format!(
1536                "{call}: term C({n}, {k}) is past u64::MAX; binomial.n is at most \
1537                 {BINOMIAL_MAX_N}"
1538            ));
1539        }
1540        out.push(Value::U64(c as u64));
1541    }
1542    Ok(out)
1543}
1544
1545/// Kernel-aware partition comprehension sources
1546/// (cursor_partitions.md §7.1).
1547///
1548/// `subdivide(<ident>, n)` — resolve `<ident>` through the
1549/// kernel's scope chain to a `Partition` (typically an iter-var
1550/// bound by an enclosing `for:` clause) and split it into `n`
1551/// sub-partitions, same boundary math as the `subdivide(p, n)`
1552/// node in polydat-nodes and the `*/N` spec token:
1553///
1554/// ```yaml
1555/// - for: "outer in partitions(\"50%,*\", 1000)"
1556///   phases:
1557///     - for: "inner in subdivide(outer, 5)"
1558///       phases: [walk]
1559/// ```
1560///
1561/// When the ident does not resolve and `probe` is set (synthesis-time
1562/// pre-evaluation probes the clause before the outer iteration
1563/// installs its value), a single placeholder partition is
1564/// returned so iter-var type detection still classifies the
1565/// variable as `ext`. At evaluation (`probe` clear) the source reads
1566/// the ident as any source reads a name: unbound or bound to None, it
1567/// reads None ([`SpecError::ReadsNone`]).
1568fn try_eval_partition_call(
1569    text: &str,
1570    kernel: &dyn Lookup,
1571    probe: bool,
1572) -> Result<Option<Vec<Value>>, SpecError> {
1573    let Some((name, args)) = parse_func_call(text) else {
1574        return Ok(None);
1575    };
1576    let arg_list = split_args_top_level(args);
1577    match name {
1578        "subdivide" => {
1579            if arg_list.len() != 2 {
1580                return Err(format!(
1581                    "subdivide(p, n): expected 2 arguments (a partition and a count), got {}",
1582                    arg_list.len()
1583                )
1584                .into());
1585            }
1586            let src = arg_list[0].trim();
1587            let n = parse_u64_arg(arg_list[1], "subdivide.n")?;
1588            if probe && kernel.lookup(src).is_none() {
1589                // Pre-evaluation probe: the outer iter-var isn't
1590                // installed yet. Return one placeholder so the clause's
1591                // iter-var type-detects as `ext`; real values arrive at
1592                // runtime dispatch.
1593                return Ok(Some(vec![placeholder_partition()]));
1594            }
1595            let value = read_name(kernel, src, || {
1596                format!("subdivide({src}, {n}): `{src}` is not bound in scope")
1597            })?;
1598            let Some(p) = value.as_partition().copied() else {
1599                return Err(format!(
1600                    "subdivide({src}, {n}): `{src}` resolved to {} — expected a \
1601                     Partition value (an iter-var from `for: \"p in partitions(...)\"` \
1602                     or a cursor's `.cursor` projection)",
1603                    value.to_display_string(),
1604                )
1605                .into());
1606            };
1607            let subs = crate::iteration::cursor_partition::subdivide_partition(&p, n)?;
1608            Ok(Some(subs.into_iter().map(Value::from_partition).collect()))
1609        }
1610        // Desugaring of an explicit `partitions(spec, [extent])` source
1611        // in comprehension position (cursor_partitions.md §3, §7.1). The spec string is in a
1612        // comprehension position, so it is parsed + resolved HERE, on the
1613        // Result path — a bad spec (over-sum list, bad recipe/order/window,
1614        // malformed tail) surfaces a clean comprehension error rather than the
1615        // `partitions()` node's eval-time `panic!` (which const-fold swallows
1616        // into a misleading downstream type mismatch). The node is unchanged;
1617        // a spec in comprehension position simply never reaches its eval.
1618        // Default extent 100 (pct space) matches the node; the cursor's
1619        // `over p` re-scales each partition to its declared range.
1620        "partitions" => {
1621            if arg_list.is_empty() || arg_list.len() > 2 {
1622                return Err(format!(
1623                    "partitions(spec, [extent]): expected 1 or 2 arguments, got {}",
1624                    arg_list.len(),
1625                )
1626                .into());
1627            }
1628            let spec = resolve_partition_spec_arg(arg_list[0], kernel)?;
1629            let extent = match arg_list.get(1) {
1630                Some(a) => parse_u64_arg(a, "partitions.extent")?,
1631                None => 100,
1632            };
1633            Ok(Some(desugar_partition_spec(
1634                &spec,
1635                extent,
1636                "comprehension source `partitions(...)`",
1637            )?))
1638        }
1639        // Profile-driven partition source: `profile_partitions(dataset,
1640        // pattern)` cuts the dataset's vector space at the cumulative
1641        // sizes of the profiles matching `pattern`, one partition per
1642        // masked tier (see `library::vectors::build_profile_partitions`).
1643        // Resolved here (like `partitions`/`subdivide`) so the iter-var
1644        // type-detects as a partition even when the dataset can't be
1645        // const-folded at compile time: a resolvable group yields the
1646        // real tiers; an unresolvable one (a compile-time probe, or a
1647        // catalog miss surfaced later by the prebuffer) yields a single
1648        // placeholder so the iter-var still types as `ext`.
1649        "profile_partitions" => {
1650            #[cfg(not(feature = "vectordata"))]
1651            {
1652                Err("profile_partitions requires the `vectordata` Cargo feature"
1653                    .to_string()
1654                    .into())
1655            }
1656
1657            #[cfg(feature = "vectordata")]
1658            {
1659                if arg_list.len() != 2 {
1660                    return Err(format!(
1661                        "profile_partitions(dataset, pattern): expected 2 arguments, got {}",
1662                        arg_list.len()
1663                    )
1664                    .into());
1665                }
1666                // Both args are literal strings after `{...}` interpolation;
1667                // strip matching outer quotes.
1668                let strip = |s: &str| -> String {
1669                    let s = s.trim();
1670                    let b = s.as_bytes();
1671                    if b.len() >= 2 && (b[0] == b'\'' || b[0] == b'"') && b[b.len() - 1] == b[0] {
1672                        s[1..s.len() - 1].to_string()
1673                    } else {
1674                        s.to_string()
1675                    }
1676                };
1677                let dataset = strip(arg_list[0]);
1678                let pattern = strip(arg_list[1]);
1679                match crate::library::vectors::load_dataset_group(&dataset) {
1680                    Ok(group) => {
1681                        let parts =
1682                            crate::library::vectors::build_profile_partitions(&group, &pattern);
1683                        Ok(Some(parts.into_iter().map(Value::from_partition).collect()))
1684                    }
1685                    Err(_) => {
1686                        // Probe / dataset unavailable: one placeholder so the
1687                        // clause's iter-var type-detects as `ext`. Real tiers
1688                        // arrive once the catalog resolves the group.
1689                        Ok(Some(vec![placeholder_partition()]))
1690                    }
1691                }
1692            }
1693        }
1694        _ => Ok(None),
1695    }
1696}
1697
1698/// The one partition a pre-evaluation probe stands in for a partition
1699/// source whose values are not installed yet, so the clause's iter-var
1700/// type-detects as `ext`.
1701fn placeholder_partition() -> Value {
1702    Value::from_partition(crate::iteration::cursor_partition::Partition {
1703        idx: 0,
1704        count: 1,
1705        start_ord: 0,
1706        end_ord: 1,
1707        start_pct: 0.0,
1708        end_pct: 100.0,
1709        base_extent: 1,
1710    })
1711}
1712
1713/// Comprehension-position desugaring (cursor_partitions.md §7.1): a `<ident>.partitions`
1714/// source (the primary operator sweep flow, `for: "p in cursor.partitions"`).
1715///
1716/// In comprehension position a *string* spec desugars per the partition
1717/// grammar. `<ident>.partitions` resolves `<ident>` against the kernel chain
1718/// to its spec string — a workload param such as `cursor=linear:4` — and the
1719/// `.partitions` projection selects the partition-spec desugaring (as opposed
1720/// to the string→token-list desugaring a bare string source would get),
1721/// expanding it into the same `PartitionList` that `partitions(spec)` yields.
1722/// Resolution uses the `partitions(spec)` node's (polydat-nodes) default extent (100, pct
1723/// space); the cursor's `over p` clause re-scales each partition's percentages
1724/// to its actual declared range.
1725///
1726/// This MUST live here (not in `eval_const_expr`, which is kernel-less and
1727/// resolves the `cursor.partitions` field-access to `None`): only the
1728/// comprehension eval has the kernel needed to look the param up.
1729///
1730/// Returns `Ok(None)` when `text` is not a `<ident>.partitions` form. When the
1731/// ident does not resolve and `probe` is set (a pre-evaluation probe before
1732/// the value is installed), a single placeholder partition is returned so
1733/// iter-var type detection yields `ext`; at evaluation the ident reads None
1734/// — the same contract as [`try_eval_partition_call`].
1735fn try_eval_param_partitions(
1736    text: &str,
1737    kernel: &dyn Lookup,
1738    probe: bool,
1739) -> Result<Option<Vec<Value>>, SpecError> {
1740    let Some(ident) = text.trim().strip_suffix(".partitions") else {
1741        return Ok(None);
1742    };
1743    let ident = ident.trim();
1744    if !is_single_bare_ident(ident) {
1745        return Ok(None);
1746    }
1747    if probe && kernel.lookup(ident).is_none() {
1748        // Pre-eval probe: the param value isn't installed yet. Return one
1749        // placeholder so the clause's iter-var type-detects as `ext`.
1750        return Ok(Some(vec![placeholder_partition()]));
1751    }
1752    let value = read_name(kernel, ident, || {
1753        format!("comprehension source `{ident}.partitions`: `{ident}` is not bound in scope")
1754    })?;
1755    // Already a resolved PartitionList → unpack directly.
1756    if let Some(list) = value.as_partition_list() {
1757        return Ok(Some(
1758            list.as_slice()
1759                .iter()
1760                .map(|p| Value::from_partition(*p))
1761                .collect(),
1762        ));
1763    }
1764    // Otherwise it must be a spec string — desugar it per the partition
1765    // spec language (cursor_partitions.md §3).
1766    let Value::Str(spec) = &value else {
1767        return Err(format!(
1768            "comprehension source `{ident}.partitions`: `{ident}` resolved to \
1769             {} — expected a partition-spec string (a workload param such as \
1770             `cursor=linear:4`) or a PartitionList.",
1771            value.to_display_string(),
1772        )
1773        .into());
1774    };
1775    Ok(Some(desugar_partition_spec(
1776        spec,
1777        100,
1778        &format!("comprehension source `{ident}.partitions`"),
1779    )?))
1780}
1781
1782/// Parse + resolve a partition spec string into its unpacked partition
1783/// values, on the Result path. Shared by the comprehension-position
1784/// desugaring forms (`<ident>.partitions` and `partitions("...")`): a bad
1785/// spec surfaces a clean error labelled by `ctx` HERE — it never reaches the
1786/// `partitions()` node's eval-time `panic!`. This is a grammar-position
1787/// concern (cursor_partitions.md §7.1), so spec validation lives where the
1788/// spec is recognized.
1789fn desugar_partition_spec(spec: &str, extent: u64, ctx: &str) -> Result<Vec<Value>, String> {
1790    let parsed = crate::iteration::cursor_partition::parse(spec)
1791        .map_err(|e| format!("{ctx}: bad spec `{spec}`: {e}"))?;
1792    let parts = crate::iteration::cursor_partition::resolve(&parsed, 0, extent)
1793        .map_err(|e| format!("{ctx}: resolve failed for `{spec}`: {e}"))?;
1794    Ok(parts.into_iter().map(Value::from_partition).collect())
1795}
1796
1797/// Resolve a `partitions(...)` spec argument to its string form: a quoted
1798/// string literal yields its inner text; a bare identifier resolves against
1799/// the kernel chain to its string value; anything else is taken verbatim (an
1800/// unquoted spec such as a raw percentage list).
1801fn resolve_partition_spec_arg(arg: &str, kernel: &dyn Lookup) -> Result<String, SpecError> {
1802    let a = arg.trim();
1803    if a.len() >= 2
1804        && ((a.starts_with('"') && a.ends_with('"')) || (a.starts_with('\'') && a.ends_with('\'')))
1805    {
1806        return Ok(a[1..a.len() - 1].to_string());
1807    }
1808    if is_single_bare_ident(a) {
1809        return match read_name(kernel, a, || {
1810            format!("partitions(...): `{a}` did not resolve to a spec string in scope")
1811        })? {
1812            Value::Str(s) => Ok(s.to_string()),
1813            other => Err(format!(
1814                "partitions(...): `{a}` resolved to {} — expected a spec string",
1815                other.to_display_string(),
1816            )
1817            .into()),
1818        };
1819    }
1820    Ok(a.to_string())
1821}
1822
1823/// Evenly spaced numeric points over `[start, end]`.
1824///
1825/// Half-open form (`linear_starts`): the start of each of `n`
1826/// equal subdivisions of `[start, end)` — `end` is never
1827/// emitted. Inclusive form (`linear_steps`): `n` fence-post
1828/// points covering `[start, end]`, both ends emitted.
1829///
1830/// These yield *values*, not partitions; splitting a
1831/// `Partition` into sub-partitions is `subdivide(p, n)` in the
1832/// partition stdlib (cursor_partitions.md §7.3).
1833fn generate_linear_points(
1834    start: f64,
1835    end: f64,
1836    n: u64,
1837    inclusive: bool,
1838) -> Result<Vec<Value>, String> {
1839    let denom = if inclusive {
1840        (n.saturating_sub(1)).max(1) as f64
1841    } else {
1842        n as f64
1843    };
1844    let step = (end - start) / denom;
1845    // Not `(0..n).collect()`: a `u64` range reports its exact length,
1846    // so collecting reserves all `n` up front and a count from the
1847    // spec text no machine can hold aborts the process.
1848    let mut out = crate::derive_support::try_buffer_for(n, "linear points")?;
1849    out.extend((0..n).map(|i| Value::F64(start + step * i as f64)));
1850    // The inclusive form's last point is `end` itself, not the sum
1851    // that rounds near it.
1852    if inclusive && n >= 2 {
1853        out[n as usize - 1] = Value::F64(end);
1854    }
1855    Ok(out)
1856}
1857
1858/// `n` log-spaced points from `start` to `end`, both emitted exactly
1859/// as given; the points between are `exp` of evenly spaced logarithms.
1860/// The caller refuses a bound that is not positive.
1861fn generate_log_steps(start: f64, end: f64, n: u64) -> Result<Vec<Value>, String> {
1862    if n == 0 {
1863        return Ok(Vec::new());
1864    }
1865    if n == 1 {
1866        return Ok(vec![Value::F64(start)]);
1867    }
1868    let log_s = start.ln();
1869    let log_e = end.ln();
1870    let step = (log_e - log_s) / (n - 1) as f64;
1871    let mut out = crate::derive_support::try_buffer_for(n, "log_steps(start, end, n)")?;
1872    out.push(Value::F64(start));
1873    out.extend((1..n - 1).map(|i| Value::F64((log_s + step * i as f64).exp())));
1874    out.push(Value::F64(end));
1875    Ok(out)
1876}
1877
1878// ============================================================
1879// Set operators (comprehension_forms.md §3.1)
1880// ============================================================
1881
1882/// Recognise `concat(...)`, `unique(...)`, etc. Each set op
1883/// recursively evaluates its arguments as sources
1884/// (so `concat(1..10, fib(8))` works), then combines the
1885/// resulting lists. An argument that reads None makes the whole
1886/// source read None.
1887fn try_eval_setop(text: &str, kernel: &dyn Lookup) -> Result<Option<Vec<Value>>, SpecError> {
1888    let Some((name, args)) = parse_func_call(text) else {
1889        return Ok(None);
1890    };
1891    let arg_texts = split_args_top_level(args);
1892    let recursively_evaluate = |t: &str| evaluate_spec_internal(t, kernel);
1893    match name {
1894        "concat" => {
1895            let mut out = Vec::new();
1896            for a in &arg_texts {
1897                out.extend(recursively_evaluate(a)?);
1898            }
1899            Ok(Some(out))
1900        }
1901        "unique" => {
1902            let mut out: Vec<Value> = Vec::new();
1903            for a in &arg_texts {
1904                for v in recursively_evaluate(a)? {
1905                    if !out.contains(&v) {
1906                        out.push(v);
1907                    }
1908                }
1909            }
1910            Ok(Some(out))
1911        }
1912        "intersect" => {
1913            if arg_texts.is_empty() {
1914                return Ok(Some(Vec::new()));
1915            }
1916            let first = recursively_evaluate(arg_texts[0])?;
1917            let mut out: Vec<Value> = Vec::new();
1918            for v in first {
1919                let mut in_all = true;
1920                for a in &arg_texts[1..] {
1921                    let other = recursively_evaluate(a)?;
1922                    if !other.contains(&v) {
1923                        in_all = false;
1924                        break;
1925                    }
1926                }
1927                if in_all && !out.contains(&v) {
1928                    out.push(v);
1929                }
1930            }
1931            Ok(Some(out))
1932        }
1933        "subtract" => {
1934            if arg_texts.len() != 2 {
1935                return Err(
1936                    format!("subtract(a, b): expected 2 args, got {}", arg_texts.len()).into(),
1937                );
1938            }
1939            let a = recursively_evaluate(arg_texts[0])?;
1940            let b = recursively_evaluate(arg_texts[1])?;
1941            Ok(Some(a.into_iter().filter(|v| !b.contains(v)).collect()))
1942        }
1943        "interleave" => {
1944            let lists: Result<Vec<Vec<Value>>, SpecError> =
1945                arg_texts.iter().map(|a| recursively_evaluate(a)).collect();
1946            let lists = lists?;
1947            let mut out = Vec::new();
1948            let max_len = lists.iter().map(|l| l.len()).max().unwrap_or(0);
1949            for i in 0..max_len {
1950                for l in &lists {
1951                    if let Some(v) = l.get(i) {
1952                        out.push(v.clone());
1953                    }
1954                }
1955            }
1956            Ok(Some(out))
1957        }
1958        "cycle" => {
1959            if arg_texts.len() != 2 {
1960                return Err(
1961                    format!("cycle(a, n): expected 2 args, got {}", arg_texts.len()).into(),
1962                );
1963            }
1964            let a = recursively_evaluate(arg_texts[0])?;
1965            let n = parse_u64_arg(arg_texts[1], "cycle.n")?;
1966            let total = (a.len() as u64).checked_mul(n).ok_or_else(|| {
1967                format!(
1968                    "cycle(a, n): {} values repeated {n} times is more than can be counted",
1969                    a.len()
1970                )
1971            })?;
1972            let mut out = crate::derive_support::try_buffer_for(total, "cycle(a, n)")?;
1973            for _ in 0..n {
1974                out.extend(a.iter().cloned());
1975            }
1976            Ok(Some(out))
1977        }
1978        "reverse" => {
1979            if arg_texts.len() != 1 {
1980                return Err(format!("reverse(a): expected 1 arg, got {}", arg_texts.len()).into());
1981            }
1982            let mut a = recursively_evaluate(arg_texts[0])?;
1983            a.reverse();
1984            Ok(Some(a))
1985        }
1986        "take" => {
1987            if arg_texts.len() != 2 {
1988                return Err(format!("take(a, n): expected 2 args, got {}", arg_texts.len()).into());
1989            }
1990            let a = recursively_evaluate(arg_texts[0])?;
1991            let n = parse_u64_arg(arg_texts[1], "take.n")?;
1992            Ok(Some(a.into_iter().take(n as usize).collect()))
1993        }
1994        "skip" => {
1995            if arg_texts.len() != 2 {
1996                return Err(format!("skip(a, n): expected 2 args, got {}", arg_texts.len()).into());
1997            }
1998            let a = recursively_evaluate(arg_texts[0])?;
1999            let n = parse_u64_arg(arg_texts[1], "skip.n")?;
2000            Ok(Some(a.into_iter().skip(n as usize).collect()))
2001        }
2002        _ => Ok(None),
2003    }
2004}
2005
2006// ============================================================
2007// Sequencer expansions (comprehension_forms.md §3.1): bucket /
2008// concat_seq / interval_seq, a lookup-table facility reusing the
2009// op-sequencing algorithms.
2010// ============================================================
2011
2012/// Recognise `bucket(items, ratios)` / `bucket("3:a, 1:b")`,
2013/// `concat_seq(...)`, `interval_seq(...)`. Reuses the
2014/// algorithms from the host's op-sequencing.
2015///
2016/// The algorithms aren't exposed cross-crate as raw functions
2017/// today, so we re-implement the small set we need here. The
2018/// outputs match `build_bucket_lut` / `build_concat_lut` /
2019/// `build_interval_lut` byte-for-byte (covered by the
2020/// the host's op-sequencing tests).
2021fn try_eval_sequencer(text: &str, kernel: &dyn Lookup) -> Result<Option<Vec<Value>>, SpecError> {
2022    let Some((name, args)) = parse_func_call(text) else {
2023        return Ok(None);
2024    };
2025    if !matches!(name, "bucket" | "concat_seq" | "interval_seq") {
2026        return Ok(None);
2027    }
2028    let arg_texts = split_args_top_level(args);
2029
2030    // Two acceptable shapes:
2031    //   1. Single string arg: ratio-prefix shorthand
2032    //      `"3:ann, 1:scan, 2:fetch"`.
2033    //   2. Two list args: items + ratios in lockstep.
2034    let (items, ratios): (Vec<Value>, Vec<usize>) = match arg_texts.len() {
2035        1 => parse_ratio_prefix_shorthand(arg_texts[0])?,
2036        2 => {
2037            let items = evaluate_spec_internal(arg_texts[0], kernel)?;
2038            let raw_ratios = evaluate_spec_internal(arg_texts[1], kernel)?;
2039            let ratios: Result<Vec<usize>, String> = raw_ratios
2040                .iter()
2041                .map(|v| match v {
2042                    Value::U64(n) => Ok(*n as usize),
2043                    other => Err(format!(
2044                        "{name}: ratio must be non-negative integer, got {other:?}"
2045                    )),
2046                })
2047                .collect();
2048            (items, ratios?)
2049        }
2050        _ => {
2051            return Err(format!(
2052                "{name}: expected `(items, ratios)` or `(\"r1:item1, r2:item2, ...\")`; got {} args",
2053                arg_texts.len()
2054            )
2055            .into());
2056        }
2057    };
2058
2059    if items.len() != ratios.len() {
2060        return Err(format!(
2061            "{name}: items.len() ({}) != ratios.len() ({})",
2062            items.len(),
2063            ratios.len(),
2064        )
2065        .into());
2066    }
2067    // The output length is the sum of the ratios, which come from the
2068    // spec text: summed checked, and reserved fallibly, so an absurd
2069    // ratio is this error rather than a wrapped sum or an abort.
2070    let total = ratios
2071        .iter()
2072        .try_fold(0usize, |acc, &r| acc.checked_add(r))
2073        .ok_or_else(|| format!("{name}: the ratios sum past what can be counted"))?;
2074    let out = crate::derive_support::try_buffer_for(total as u64, name)?;
2075    Ok(Some(match name {
2076        "bucket" => seq_bucket(&items, &ratios, total, out),
2077        "concat_seq" => seq_concat(&items, &ratios, out),
2078        "interval_seq" => seq_interval(&items, &ratios, total, out),
2079        _ => unreachable!(),
2080    }))
2081}
2082
2083/// Parse `"r1:item1, r2:item2, …"`. Each element is a
2084/// ratio (positive integer) and an item value separated
2085/// by `:`. The string itself comes through `evaluate_spec`
2086/// — typically as a quoted string literal.
2087fn parse_ratio_prefix_shorthand(text: &str) -> Result<(Vec<Value>, Vec<usize>), String> {
2088    // The arg might be a literal `"3:a, 1:b"` (with quotes
2089    // in the source) or already-stripped `3:a, 1:b`.
2090    let stripped = text
2091        .trim()
2092        .trim_start_matches(['"', '\''])
2093        .trim_end_matches(['"', '\'']);
2094    let mut items = Vec::new();
2095    let mut ratios = Vec::new();
2096    for part in stripped.split(',') {
2097        let part = part.trim();
2098        if part.is_empty() {
2099            continue;
2100        }
2101        let (r, i) = part
2102            .split_once(':')
2103            .ok_or_else(|| format!("ratio-prefix shorthand: missing ':' in '{part}'"))?;
2104        let ratio: usize = r.trim().parse().map_err(|_| {
2105            format!("ratio-prefix shorthand: ratio '{r}' is not a non-negative integer")
2106        })?;
2107        ratios.push(ratio);
2108        items.push(parse_one_value(i.trim()));
2109    }
2110    Ok((items, ratios))
2111}
2112
2113fn parse_one_value(s: &str) -> Value {
2114    if let Ok(n) = s.parse::<u64>() {
2115        return Value::U64(n);
2116    }
2117    if let Ok(f) = s.parse::<f64>() {
2118        return Value::F64(f);
2119    }
2120    if s == "true" {
2121        return Value::Bool(true);
2122    }
2123    if s == "false" {
2124        return Value::Bool(false);
2125    }
2126    Value::Str(s.to_string().into())
2127}
2128
2129/// Bucket sequencer: round-robin from per-item buckets sized
2130/// by ratio. Output length = sum(ratios), which is `total`; `out` is
2131/// reserved for it.
2132fn seq_bucket(items: &[Value], ratios: &[usize], total: usize, mut out: Vec<Value>) -> Vec<Value> {
2133    let mut remaining: Vec<usize> = ratios.to_vec();
2134    while out.len() < total {
2135        let mut emitted_any = false;
2136        for (i, item) in items.iter().enumerate() {
2137            if remaining[i] > 0 {
2138                out.push(item.clone());
2139                remaining[i] -= 1;
2140                emitted_any = true;
2141            }
2142        }
2143        if !emitted_any {
2144            break;
2145        }
2146    }
2147    out
2148}
2149
2150/// Concat sequencer: contiguous runs (all of item 1, then
2151/// all of item 2, …).
2152fn seq_concat(items: &[Value], ratios: &[usize], mut out: Vec<Value>) -> Vec<Value> {
2153    for (item, &r) in items.iter().zip(ratios.iter()) {
2154        for _ in 0..r {
2155            out.push(item.clone());
2156        }
2157    }
2158    out
2159}
2160
2161/// Interval sequencer: evenly spaced occurrences of each
2162/// item across the output. Picks each output position from
2163/// the item with the largest "weight × position - already
2164/// emitted" — same algorithm as op-sequencing's
2165/// build_interval_lut.
2166fn seq_interval(
2167    items: &[Value],
2168    ratios: &[usize],
2169    total: usize,
2170    mut out: Vec<Value>,
2171) -> Vec<Value> {
2172    if total == 0 {
2173        return out;
2174    }
2175    let mut emitted: Vec<usize> = vec![0; items.len()];
2176    for slot in 0..total {
2177        // Pick the item whose target ratio is most under-met
2178        // at this slot. Target at slot k = (ratio_i * (k+1)) / total.
2179        let mut best = 0usize;
2180        let mut best_deficit: f64 = f64::NEG_INFINITY;
2181        for i in 0..items.len() {
2182            let target = ratios[i] as f64 * (slot + 1) as f64 / total as f64;
2183            let deficit = target - emitted[i] as f64;
2184            if deficit > best_deficit {
2185                best_deficit = deficit;
2186                best = i;
2187            }
2188        }
2189        out.push(items[best].clone());
2190        emitted[best] += 1;
2191    }
2192    out
2193}
2194
2195/// Map a `Value` to the canonical polydat extern type keyword.
2196///
2197/// Delegates to [`Value::port_type`] + [`PortType::to_keyword`](crate::ast::PortType::to_keyword) —
2198/// the single source of truth for the str↔PortType table. The
2199/// returned keyword round-trips byte-cleanly through
2200/// [`PortType::from_keyword`](crate::ast::PortType::from_keyword) in the DSL extern parser, so every
2201/// typed `Value` variant (including `VecF32`, `Bytes`, `Json`,
2202/// `Handle`) becomes a precisely-typed input on the synthesized
2203/// inner kernel.
2204pub fn value_to_polydat_type_name(v: &Value) -> &'static str {
2205    v.port_type().to_keyword()
2206}
2207
2208// Expand `{name}` placeholders in `text`, resolving each leaf
2209// placeholder against `kernel`'s in-scope name space.
2210//
2211// `interpolate_via_kernel`, `interpolate_with_lookup`, and the
2212// internal `one_pass` / `first_unresolved` / `unescape` helpers
2213// live in `crate::kernel::interp`.
2214// `interpolate_via_kernel` and `interpolate_with_lookup` are
2215// imported above for internal use; external callers use the
2216// `polydat::kernel::interp` module directly.
2217
2218#[cfg(test)]
2219mod tests {
2220    use super::*;
2221    use crate::kernel::PolydatKernel;
2222    use crate::kernel::interp::interpolate_via_kernel;
2223
2224    fn h(pairs: &[(&str, &str)]) -> HashMap<String, String> {
2225        pairs
2226            .iter()
2227            .map(|(k, v)| (k.to_string(), v.to_string()))
2228            .collect()
2229    }
2230
2231    fn interpolate(
2232        text: &str,
2233        bindings: &HashMap<String, String>,
2234        workload_params: &HashMap<String, String>,
2235    ) -> Result<String, String> {
2236        interpolate_with_lookup(text, |name| {
2237            bindings
2238                .get(name)
2239                .or_else(|| workload_params.get(name))
2240                .cloned()
2241        })
2242    }
2243
2244    #[test]
2245    fn flat_substitution() {
2246        let params = h(&[("dataset", "example"), ("prefix", "label")]);
2247        let out = interpolate("matching('{dataset}', '{prefix}')", &h(&[]), &params).unwrap();
2248        assert_eq!(out, "matching('example', 'label')");
2249    }
2250
2251    #[test]
2252    fn bindings_shadow_params() {
2253        let params = h(&[("profile", "default")]);
2254        let bindings = h(&[("profile", "label_07")]);
2255        let out = interpolate("vec_{profile}", &bindings, &params).unwrap();
2256        assert_eq!(out, "vec_label_07");
2257    }
2258
2259    #[test]
2260    fn nested_placeholder_resolves_inside_out() {
2261        let params = h(&[("k_1_limits", "1,2,4,8"), ("k_10_limits", "10,20,30")]);
2262        let bindings = h(&[("k", "1")]);
2263        let out = interpolate("{k_{k}_limits}", &bindings, &params).unwrap();
2264        assert_eq!(out, "1,2,4,8");
2265    }
2266
2267    #[test]
2268    fn deeply_nested() {
2269        let params = h(&[("a_b_c", "WIN")]);
2270        let bindings = h(&[("x", "a"), ("y", "b"), ("z", "c")]);
2271        let out = interpolate("{{x}_{y}_{z}}", &bindings, &params).unwrap();
2272        assert_eq!(out, "WIN");
2273    }
2274
2275    #[test]
2276    fn escape_emits_literal_brace() {
2277        let out = interpolate("\\{not_a_var\\}", &h(&[]), &h(&[])).unwrap();
2278        assert_eq!(out, "{not_a_var}");
2279    }
2280
2281    #[test]
2282    fn escape_inside_otherwise_resolved_text() {
2283        let params = h(&[("x", "1")]);
2284        let out = interpolate("a={x} literal=\\{x\\}", &h(&[]), &params).unwrap();
2285        assert_eq!(out, "a=1 literal={x}");
2286    }
2287
2288    #[test]
2289    fn unresolved_is_hard_error() {
2290        let err = interpolate("hello {nope}", &h(&[]), &h(&[])).unwrap_err();
2291        assert!(err.contains("unresolved"));
2292        assert!(err.contains("nope"));
2293    }
2294
2295    #[test]
2296    fn empty_placeholder_rejected() {
2297        let err = interpolate("a{}b", &h(&[]), &h(&[])).unwrap_err();
2298        assert!(err.contains("empty"));
2299    }
2300
2301    #[test]
2302    fn unmatched_brace_rejected() {
2303        let err = interpolate("a {x", &h(&[]), &h(&[])).unwrap_err();
2304        assert!(err.contains("unmatched"));
2305    }
2306
2307    #[test]
2308    fn idempotent_when_no_placeholders() {
2309        let out = interpolate("plain text", &h(&[]), &h(&[])).unwrap();
2310        assert_eq!(out, "plain text");
2311    }
2312
2313    #[test]
2314    fn resolved_value_with_braces_does_not_re_expand() {
2315        let params = h(&[("greeting", "hello {planet}")]);
2316        let err = interpolate("{greeting}", &h(&[]), &params).unwrap_err();
2317        assert!(err.contains("planet"));
2318    }
2319
2320    #[test]
2321    fn cyclic_placeholders_hit_round_cap() {
2322        let params = h(&[("a", "{b}"), ("b", "{a}")]);
2323        let err = interpolate("{a}", &h(&[]), &params).unwrap_err();
2324        assert!(err.contains("did not stabilize") || err.contains("rounds"));
2325    }
2326
2327    #[test]
2328    fn kernel_resolves_via_get_constant() {
2329        let kernel =
2330            crate::dsl::compile::compile_polydat_interpreter("const dataset := \"example\"\n")
2331                .unwrap();
2332        let out = interpolate_via_kernel("path/{dataset}/data", &kernel).unwrap();
2333        assert_eq!(out, "path/example/data");
2334    }
2335
2336    #[test]
2337    fn kernel_resolves_via_get_input() {
2338        let parent =
2339            crate::dsl::compile::compile_polydat_interpreter("const k_values := \"1, 10\"\n")
2340                .unwrap();
2341        let child_program =
2342            crate::dsl::compile::compile_polydat_interpreter("extern k_values: str\n")
2343                .unwrap()
2344                .program()
2345                .clone();
2346        let child = parent.materialize_subscope(child_program, &[]);
2347        let out = interpolate_via_kernel("values={k_values}", &child).unwrap();
2348        assert_eq!(out, "values=1, 10");
2349    }
2350
2351    #[test]
2352    fn kernel_unresolved_name_errors() {
2353        let kernel = crate::dsl::compile::compile_polydat_interpreter("const x := 1\n").unwrap();
2354        let err = interpolate_via_kernel("hello {nope}", &kernel)
2355            .unwrap_err()
2356            .to_string();
2357        assert!(err.contains("unresolved"));
2358        assert!(err.contains("nope"));
2359    }
2360
2361    #[test]
2362    fn kernel_nested_template_iterates_to_fixed_point() {
2363        let kernel = crate::dsl::compile::compile_polydat_interpreter(
2364            "const k := \"1\"\nconst k_1_limits := \"1, 2, 4, 8\"\n",
2365        )
2366        .unwrap();
2367        let out = interpolate_via_kernel("{k_{k}_limits}", &kernel).unwrap();
2368        assert_eq!(out, "1, 2, 4, 8");
2369    }
2370
2371    #[test]
2372    fn parse_list_native_types() {
2373        let v = parse_list_with_types("1, 10, 100");
2374        assert_eq!(v, vec![Value::U64(1), Value::U64(10), Value::U64(100)]);
2375    }
2376
2377    #[test]
2378    fn parse_list_mixed_types() {
2379        let v = parse_list_with_types("1, 1.5, true, hello");
2380        assert_eq!(
2381            v,
2382            vec![
2383                Value::U64(1),
2384                Value::F64(1.5),
2385                Value::Bool(true),
2386                Value::Str("hello".to_string().into()),
2387            ]
2388        );
2389    }
2390
2391    #[test]
2392    fn all_cursor_returns_extent_range() {
2393        // Simulate a cursor declaration at the parent scope by
2394        // exposing the auxiliary extent outputs as folded
2395        // constants. The real cursor compiler emits these via
2396        // `__cursor_extent_<name>_{start,end}` outputs; for this
2397        // test we synthesize them directly.
2398        let kernel = crate::dsl::compile::compile_polydat_interpreter(
2399            "const __cursor_extent_row_start := 0\n\
2400             const __cursor_extent_row_end := 5\n",
2401        )
2402        .unwrap();
2403        let values = evaluate_spec("all(row)", &kernel).unwrap();
2404        assert_eq!(
2405            values,
2406            vec![
2407                Value::U64(0),
2408                Value::U64(1),
2409                Value::U64(2),
2410                Value::U64(3),
2411                Value::U64(4),
2412            ]
2413        );
2414    }
2415
2416    #[test]
2417    fn all_cursor_non_zero_start() {
2418        let kernel = crate::dsl::compile::compile_polydat_interpreter(
2419            "const __cursor_extent_data_start := 100\n\
2420             const __cursor_extent_data_end := 103\n",
2421        )
2422        .unwrap();
2423        let values = evaluate_spec("all(data)", &kernel).unwrap();
2424        assert_eq!(
2425            values,
2426            vec![Value::U64(100), Value::U64(101), Value::U64(102)]
2427        );
2428    }
2429
2430    #[test]
2431    fn all_cursor_missing_extent_errors() {
2432        let kernel =
2433            crate::dsl::compile::compile_polydat_interpreter("const unrelated := 1\n").unwrap();
2434        let err = evaluate_spec("all(no_such_cursor)", &kernel)
2435            .unwrap_err()
2436            .to_string();
2437        assert!(err.contains("all(no_such_cursor)"));
2438        assert!(err.contains("no resolvable extent"));
2439    }
2440
2441    #[test]
2442    fn all_cursor_only_matches_exact_shape() {
2443        // `all(<ident>)` is the only matched shape — anything
2444        // more complex falls through to the normal eval path.
2445        // `all(row, 5)` doesn't match the strict shape (the
2446        // comma breaks the bare-ident requirement), so the
2447        // pipeline tries to evaluate it as a regular GK
2448        // expression. There's no registered function named
2449        // `all`, so eval fails and the failure is propagated as
2450        // a clean clause-level error rather than split into a
2451        // literal list.
2452        let kernel = crate::dsl::compile::compile_polydat_interpreter(
2453            "const __cursor_extent_row_start := 0\n\
2454             const __cursor_extent_row_end := 5\n",
2455        )
2456        .unwrap();
2457        let err = evaluate_spec("all(row, 5)", &kernel)
2458            .unwrap_err()
2459            .to_string();
2460        assert!(
2461            err.contains("all(row, 5)"),
2462            "error must mention the failing spec, got: {err}"
2463        );
2464        assert!(
2465            err.contains("failed to evaluate") || err.contains("unknown function"),
2466            "error must explain the eval failure, got: {err}"
2467        );
2468    }
2469
2470    #[test]
2471    fn missing_dataset_surface_as_clean_error_not_garbage() {
2472        // A workload runs on a system whose vectordata catalog
2473        // doesn't have the requested dataset. The source
2474        //   `profile in matching_profiles('nonexistent_dataset_xyz', 'label_')`
2475        // produces a clean clause-level error naming the
2476        // resolution failure, never a garbage iter-var like
2477        // `matching_profiles('nonexistent_dataset_xyz'`
2478        // (truncated at the first comma) that would flow
2479        // downstream into malformed output. Every layer on the
2480        // way (the dataset open, the handle read, and
2481        // `evaluate_spec`) propagates an actionable diagnostic.
2482        let kernel =
2483            crate::dsl::compile::compile_polydat_interpreter("const unrelated := 1\n").unwrap();
2484        let result = evaluate_spec(
2485            "matching_profiles('nonexistent_dataset_xyz_qqq', 'label_')",
2486            &kernel,
2487        );
2488        let err = result
2489            .expect_err("missing dataset must surface as Err, not silent literal-list fallback")
2490            .to_string();
2491        // Doesn't matter which exact error string we get from
2492        // the catalog layer — the test guards the *contract*:
2493        // the spec text appears in the error, the failure is
2494        // attributed to the dataset / resolver / open path, and
2495        // it is a Result::Err (not garbage data).
2496        assert!(
2497            err.contains("nonexistent_dataset_xyz_qqq")
2498                || err.contains("matching_profiles")
2499                || err.contains("dataset"),
2500            "error must point at the actual fault, got: {err}"
2501        );
2502    }
2503
2504    #[test]
2505    fn function_call_eval_failure_is_not_silently_split() {
2506        // Defensive: any text containing `(` is an
2507        // expression — never a literal list. If eval fails, we
2508        // must propagate the failure rather than splitting on
2509        // commas. This guards the broader contract that
2510        // protected the dataset-resolution case above.
2511        let kernel =
2512            crate::dsl::compile::compile_polydat_interpreter("const unrelated := 1\n").unwrap();
2513        let err = evaluate_spec("nonexistent_func('a', 'b', 'c')", &kernel)
2514            .unwrap_err()
2515            .to_string();
2516        assert!(
2517            err.contains("failed to evaluate") || err.contains("unknown"),
2518            "expected a clean eval-failure error, got: {err}"
2519        );
2520    }
2521
2522    #[test]
2523    fn literal_list_path_still_works() {
2524        // Counter-case: a plain comma-separated list of
2525        // literals (no parens, no operators) MUST still work
2526        // through the literal-list fallback after eval fails
2527        // (which it should — `1, 10, 100` isn't a single GK
2528        // expression). This is the legitimate use case that the
2529        // fallback exists for.
2530        let kernel =
2531            crate::dsl::compile::compile_polydat_interpreter("const unrelated := 1\n").unwrap();
2532        let values = evaluate_spec("1, 10, 100", &kernel).unwrap();
2533        assert_eq!(values, vec![Value::U64(1), Value::U64(10), Value::U64(100)]);
2534
2535        let names = evaluate_spec("foo, bar, baz", &kernel).unwrap();
2536        assert_eq!(
2537            names,
2538            vec![
2539                Value::Str("foo".into()),
2540                Value::Str("bar".into()),
2541                Value::Str("baz".into()),
2542            ]
2543        );
2544    }
2545
2546    #[test]
2547    fn literal_cursor_exposes_extent_auxiliaries() {
2548        // Real cursor declaration with literal extent — verifies
2549        // the compiler-side change that emits
2550        // __cursor_extent_<name>_{start,end} as final bindings
2551        // even in the literal-args case.
2552        let kernel =
2553            crate::dsl::compile::compile_polydat_interpreter("cursor row = range(0, 50)\n")
2554                .unwrap();
2555        let start = kernel.lookup("__cursor_extent_row_start");
2556        let end = kernel.lookup("__cursor_extent_row_end");
2557        assert_eq!(
2558            start,
2559            Some(Value::U64(0)),
2560            "expected start=0, got {start:?}"
2561        );
2562        assert_eq!(end, Some(Value::U64(50)), "expected end=50, got {end:?}");
2563    }
2564
2565    #[test]
2566    fn all_cursor_with_real_cursor_decl_works() {
2567        let kernel =
2568            crate::dsl::compile::compile_polydat_interpreter("cursor row = range(0, 5)\n").unwrap();
2569        let values = evaluate_spec("all(row)", &kernel).unwrap();
2570        assert_eq!(
2571            values,
2572            vec![
2573                Value::U64(0),
2574                Value::U64(1),
2575                Value::U64(2),
2576                Value::U64(3),
2577                Value::U64(4),
2578            ]
2579        );
2580    }
2581
2582    #[test]
2583    fn all_cursor_ignores_whitespace() {
2584        let kernel = crate::dsl::compile::compile_polydat_interpreter(
2585            "const __cursor_extent_row_start := 0\n\
2586             const __cursor_extent_row_end := 3\n",
2587        )
2588        .unwrap();
2589        let values = evaluate_spec("  all( row )  ", &kernel).unwrap();
2590        assert_eq!(values.len(), 3);
2591    }
2592
2593    #[test]
2594    fn evaluate_spec_resolves_against_kernel() {
2595        let kernel =
2596            crate::dsl::compile::compile_polydat_interpreter("const k_values := \"1, 10, 100\"\n")
2597                .unwrap();
2598        let v = evaluate_spec("{k_values}", &kernel).unwrap();
2599        assert_eq!(v, vec![Value::U64(1), Value::U64(10), Value::U64(100)]);
2600    }
2601
2602    /// Pre-evaluation reads a whole-source placeholder as the runtime
2603    /// path does, so the type it infers is the type the runtime binds:
2604    /// a string whose text reads as a number stays a string, from the
2605    /// kernel and through a composed name.
2606    #[test]
2607    fn pre_evaluation_reads_a_whole_placeholder_as_the_reference() {
2608        let kernel = crate::dsl::compile::compile_polydat_interpreter(
2609            "extern load_timeout_1m: str = \"30m\"\nextern count: u64 = 4\n",
2610        )
2611        .unwrap();
2612        let none = HashMap::new();
2613        let probes: HashMap<String, String> = [("size".to_string(), "1m".to_string())].into();
2614        for (text, expected) in [
2615            ("{load_timeout_1m}", Value::Str("30m".into())),
2616            ("load_timeout_1m", Value::Str("30m".into())),
2617            ("{load_timeout_{size}}", Value::Str("30m".into())),
2618            ("{count}", Value::U64(4)),
2619        ] {
2620            assert_eq!(
2621                pre_evaluate_clause(text, &kernel, &none, &probes).unwrap(),
2622                vec![expected],
2623                "{text}"
2624            );
2625        }
2626        // A workload param is text, read as the bare name reads it.
2627        let params: HashMap<String, String> = [("lt".to_string(), "30m".to_string())].into();
2628        assert_eq!(
2629            pre_evaluate_clause("{lt}", &kernel, &params, &none).unwrap(),
2630            pre_evaluate_clause("lt", &kernel, &params, &none).unwrap(),
2631        );
2632        // A name nothing binds is still reported as unresolved.
2633        let err = pre_evaluate_clause("{nope}", &kernel, &none, &none).unwrap_err();
2634        assert!(err.contains("unresolved placeholder '{nope}'"), "{err}");
2635    }
2636
2637    #[test]
2638    fn evaluate_spec_bare_ident_resolves_like_braced() {
2639        // A bare identifier source is a direct wire/param reference
2640        // (comprehension_forms.md §3.1.4) and resolves identically to
2641        // the braced `{name}` interpolation form.
2642        let kernel =
2643            crate::dsl::compile::compile_polydat_interpreter("const k_values := \"1, 10, 100\"\n")
2644                .unwrap();
2645        let bare = evaluate_spec("k_values", &kernel).unwrap();
2646        let braced = evaluate_spec("{k_values}", &kernel).unwrap();
2647        assert_eq!(bare, braced);
2648        assert_eq!(bare, vec![Value::U64(1), Value::U64(10), Value::U64(100)]);
2649    }
2650
2651    #[test]
2652    fn evaluate_spec_unresolved_bare_is_error_with_quoting_hint() {
2653        // A bare identifier source that doesn't resolve is a hard
2654        // error (comprehension_forms.md §3.1.4) (not silently bound as its own
2655        // name-string), and the message points at the fix.
2656        let kernel = crate::dsl::compile::compile_polydat_interpreter("\n").unwrap();
2657        let err = evaluate_spec("nonexistent", &kernel)
2658            .unwrap_err()
2659            .to_string();
2660        assert!(err.contains("did not resolve"), "got: {err}");
2661        assert!(err.contains("quote it"), "should hint quoting: {err}");
2662    }
2663
2664    /// A source reads None for the names it reads after composition: the
2665    /// composed target of `{k_{k}_limits}`, and a name bound to None, are
2666    /// reads of None, and a failure over a name the scope has is not.
2667    #[test]
2668    fn a_read_of_none_is_decided_on_the_composed_name() {
2669        let kernel = crate::dsl::compile::compile_polydat_interpreter(
2670            "const k_1_limits := \"1, 2\"\nconst n := 3\n",
2671        )
2672        .unwrap();
2673        let at = |k: u64| vec![("k".to_string(), Value::U64(k))];
2674        let reads = |spec: &str, prefix: &[(String, Value)]| {
2675            let scope = crate::kernel::interp::Layered {
2676                prefix,
2677                inner: &kernel,
2678            };
2679            match evaluate_spec_internal(spec, &scope) {
2680                Ok(values) => Ok(values.len()),
2681                Err(SpecError::ReadsNone { reads, .. }) => Err(Some(reads)),
2682                Err(SpecError::Failed(_)) => Err(None),
2683            }
2684        };
2685        assert_eq!(reads("{k_{k}_limits}", &at(1)), Ok(2));
2686        assert_eq!(
2687            reads("{k_{k}_limits}", &at(7)),
2688            Err(Some(vec![NoneRead::Unbound("k_7_limits".into())]))
2689        );
2690        let none = [("z".to_string(), Value::None)];
2691        for spec in ["{z}", "z", "[z]", "pow2({z})", "concat(z, 1..3)"] {
2692            assert_eq!(
2693                reads(spec, &none),
2694                Err(Some(vec![NoneRead::BoundNone("z".into())])),
2695                "{spec}"
2696            );
2697        }
2698        assert_eq!(
2699            reads("u64_add(zz, 1)", &[]),
2700            Err(Some(vec![NoneRead::Unbound("zz".into())]))
2701        );
2702        assert_eq!(reads("pow2(99999)", &[]), Err(None));
2703        // The public evaluator reads a name bound to None as None and
2704        // still refuses one nothing binds.
2705        let scope = crate::kernel::interp::Layered {
2706            prefix: &none,
2707            inner: &kernel,
2708        };
2709        assert_eq!(evaluate_spec("{z}", &scope).unwrap(), Vec::<Value>::new());
2710        assert!(matches!(
2711            evaluate_spec("{zz}", &scope),
2712            Err(crate::dsl::compile::EmbeddingError::UnresolvedPlaceholder { .. })
2713        ));
2714    }
2715
2716    #[test]
2717    fn bracket_list_spread_and_no_peel() {
2718        // `[xs…]` destructures (peels one level); `[xs]` binds the
2719        // whole value once.
2720        let kernel =
2721            crate::dsl::compile::compile_polydat_interpreter("const xs := \"1, 2, 3\"\n").unwrap();
2722        // spread → peel the string's tokens
2723        let spread = evaluate_spec("[xs…]", &kernel).unwrap();
2724        assert_eq!(spread, vec![Value::U64(1), Value::U64(2), Value::U64(3)]);
2725        // no-peel → the whole value once (the string, un-striped)
2726        let whole = evaluate_spec("[xs]", &kernel).unwrap();
2727        assert_eq!(whole, vec![Value::Str("1, 2, 3".into())]);
2728    }
2729
2730    #[test]
2731    fn bracket_list_mixes_refs_literals_and_spread() {
2732        let kernel =
2733            crate::dsl::compile::compile_polydat_interpreter("const mid := \"7, 8\"\n").unwrap();
2734        let v = evaluate_spec("[1, mid…, \"x\"]", &kernel).unwrap();
2735        assert_eq!(
2736            v,
2737            vec![
2738                Value::U64(1),
2739                Value::U64(7),
2740                Value::U64(8),
2741                Value::Str("x".into()),
2742            ]
2743        );
2744    }
2745
2746    // ── Partition-list unpacking (cursor_partitions.md §7.1) ──
2747
2748    #[test]
2749    fn evaluate_spec_unpacks_partition_list_into_partition_values() {
2750        // `partitions("linear:3")` evaluates to a PartitionList
2751        // Ext value. evaluate_spec must unpack the list into a
2752        // Vec of individual Partition values so the for-clause
2753        // iterates partition-by-partition (one iteration per
2754        // partition).
2755        let kernel = empty_kernel();
2756        let v = evaluate_spec("partitions(\"linear:3\")", &kernel).unwrap();
2757        assert_eq!(v.len(), 3, "expected 3 partitions, got {}", v.len());
2758        for value in &v {
2759            assert!(
2760                value.as_partition().is_some(),
2761                "every iter value should be a Partition, got {value:?}"
2762            );
2763        }
2764    }
2765
2766    #[test]
2767    fn evaluate_spec_unpacks_partition_list_with_explicit_extent() {
2768        let kernel = empty_kernel();
2769        let v = evaluate_spec("partitions(\"fib:5\", 1000)", &kernel).unwrap();
2770        assert_eq!(v.len(), 5);
2771        // Partition indices increment from 0.
2772        for (i, value) in v.iter().enumerate() {
2773            let p = value.as_partition().unwrap();
2774            assert_eq!(p.idx, i as u64);
2775            assert_eq!(p.base_extent, 1000);
2776        }
2777    }
2778
2779    #[test]
2780    fn pre_evaluate_clause_returns_partition_values_for_partitions_call() {
2781        // Same as the evaluate_spec test above but via the
2782        // synthesis-side pre_evaluate_clause entry point.
2783        let kernel = empty_kernel();
2784        let v = pre_evaluate_clause(
2785            "partitions(\"linear:4\")",
2786            &kernel,
2787            &HashMap::new(),
2788            &HashMap::new(),
2789        )
2790        .unwrap();
2791        assert_eq!(v.len(), 4);
2792        for value in &v {
2793            assert!(
2794                value.as_partition().is_some(),
2795                "pre_evaluate_clause must unpack PartitionList, got {value:?}"
2796            );
2797        }
2798    }
2799
2800    #[test]
2801    fn value_to_polydat_type_name_returns_ext_for_partition_value() {
2802        // The for_each scope synthesizer uses this to emit
2803        // `extern <var>: <keyword>` for each iter-var. Ext-typed
2804        // values (Partition, PartitionSpec, PartitionList) must
2805        // declare as `ext` so the resulting input port is
2806        // PortType::Ext and downstream `over <iter-var>` clauses
2807        // see the right shape.
2808        let p = crate::iteration::cursor_partition::Partition {
2809            idx: 0,
2810            count: 1,
2811            start_ord: 0,
2812            end_ord: 10,
2813            start_pct: 0.0,
2814            end_pct: 100.0,
2815            base_extent: 10,
2816        };
2817        let v = Value::from_partition(p);
2818        assert_eq!(value_to_polydat_type_name(&v), "ext");
2819    }
2820
2821    // ── Range operator ──
2822
2823    fn empty_kernel() -> PolydatKernel {
2824        crate::dsl::compile::compile_polydat_interpreter("\n").unwrap()
2825    }
2826
2827    #[test]
2828    fn range_half_open_integer() {
2829        let v = evaluate_spec("1..5", &empty_kernel()).unwrap();
2830        assert_eq!(
2831            v,
2832            vec![Value::U64(1), Value::U64(2), Value::U64(3), Value::U64(4),]
2833        );
2834    }
2835
2836    #[test]
2837    fn range_inclusive_integer() {
2838        let v = evaluate_spec("1..=5", &empty_kernel()).unwrap();
2839        assert_eq!(
2840            v,
2841            vec![
2842                Value::U64(1),
2843                Value::U64(2),
2844                Value::U64(3),
2845                Value::U64(4),
2846                Value::U64(5),
2847            ]
2848        );
2849    }
2850
2851    #[test]
2852    fn range_with_step() {
2853        let v = evaluate_spec("0..100..10", &empty_kernel()).unwrap();
2854        assert_eq!(
2855            v,
2856            vec![
2857                Value::U64(0),
2858                Value::U64(10),
2859                Value::U64(20),
2860                Value::U64(30),
2861                Value::U64(40),
2862                Value::U64(50),
2863                Value::U64(60),
2864                Value::U64(70),
2865                Value::U64(80),
2866                Value::U64(90),
2867            ]
2868        );
2869    }
2870
2871    #[test]
2872    fn range_inclusive_with_step() {
2873        let v = evaluate_spec("0..=100..25", &empty_kernel()).unwrap();
2874        assert_eq!(
2875            v,
2876            vec![
2877                Value::U64(0),
2878                Value::U64(25),
2879                Value::U64(50),
2880                Value::U64(75),
2881                Value::U64(100),
2882            ]
2883        );
2884    }
2885
2886    #[test]
2887    fn range_float_step() {
2888        let v = evaluate_spec("0.0..=1.0..0.25", &empty_kernel()).unwrap();
2889        assert_eq!(v.len(), 5, "got {v:?}");
2890        if let [
2891            Value::F64(a),
2892            Value::F64(b),
2893            Value::F64(c),
2894            Value::F64(d),
2895            Value::F64(e),
2896        ] = v.as_slice()
2897        {
2898            assert!((a - 0.0).abs() < 1e-12);
2899            assert!((b - 0.25).abs() < 1e-12);
2900            assert!((c - 0.5).abs() < 1e-12);
2901            assert!((d - 0.75).abs() < 1e-12);
2902            assert!((e - 1.0).abs() < 1e-12);
2903        } else {
2904            panic!("expected 5 floats, got {v:?}");
2905        }
2906    }
2907
2908    #[test]
2909    fn range_empty_when_start_equals_end_half_open() {
2910        let v = evaluate_spec("5..5", &empty_kernel()).unwrap();
2911        assert!(v.is_empty(), "got {v:?}");
2912    }
2913
2914    #[test]
2915    fn range_inclusive_with_equal_bounds_emits_one() {
2916        let v = evaluate_spec("5..=5", &empty_kernel()).unwrap();
2917        assert_eq!(v, vec![Value::U64(5)]);
2918    }
2919
2920    #[test]
2921    fn range_with_si_suffix_bounds() {
2922        // SI suffixes (polydat_grammar.md §2.3) compose with range
2923        // bounds.
2924        let v = evaluate_spec("1K..1K..200", &empty_kernel()).unwrap();
2925        assert!(v.is_empty(), "1K..1K with positive step → empty");
2926
2927        let v = evaluate_spec("0..1K..200", &empty_kernel()).unwrap();
2928        assert_eq!(
2929            v,
2930            vec![
2931                Value::U64(0),
2932                Value::U64(200),
2933                Value::U64(400),
2934                Value::U64(600),
2935                Value::U64(800),
2936            ]
2937        );
2938    }
2939
2940    #[test]
2941    fn range_zero_step_errors() {
2942        let err = evaluate_spec("1..10..0", &empty_kernel())
2943            .unwrap_err()
2944            .to_string();
2945        assert!(err.contains("step is zero"), "{err}");
2946    }
2947
2948    #[test]
2949    fn range_too_many_dotdot_errors() {
2950        let err = evaluate_spec("1..2..3..4", &empty_kernel())
2951            .unwrap_err()
2952            .to_string();
2953        assert!(err.contains("more than two `..`"), "{err}");
2954    }
2955
2956    #[test]
2957    fn range_inside_parens_doesnt_split() {
2958        // `range(1, 10)` — the dots inside the function
2959        // call shouldn't trigger range-splitting at top
2960        // depth (there are no `..` here anyway, but verify
2961        // paren-balanced text passes through cleanly).
2962        // Use a literal with internal parens to exercise
2963        // the depth tracking.
2964        let v = evaluate_spec("(1)..(5)", &empty_kernel()).unwrap();
2965        assert_eq!(v.len(), 4); // 1, 2, 3, 4
2966    }
2967
2968    #[test]
2969    fn range_step_with_inclusive_separator_errors() {
2970        let err = evaluate_spec("1..10..=2", &empty_kernel())
2971            .unwrap_err()
2972            .to_string();
2973        assert!(err.contains("step delimiter cannot be `..=`"), "{err}");
2974    }
2975
2976    #[test]
2977    fn range_with_kernel_referenced_bounds() {
2978        let kernel =
2979            crate::dsl::compile::compile_polydat_interpreter("const lo := 5\nconst hi := 12\n")
2980                .unwrap();
2981        let v = evaluate_spec("{lo}..{hi}", &kernel).unwrap();
2982        assert_eq!(
2983            v,
2984            vec![
2985                Value::U64(5),
2986                Value::U64(6),
2987                Value::U64(7),
2988                Value::U64(8),
2989                Value::U64(9),
2990                Value::U64(10),
2991                Value::U64(11),
2992            ]
2993        );
2994    }
2995
2996    // ── Named generators ──
2997
2998    #[test]
2999    fn fib_n_first_eight() {
3000        let v = evaluate_spec("fib(8)", &empty_kernel()).unwrap();
3001        assert_eq!(
3002            v,
3003            vec![
3004                Value::U64(1),
3005                Value::U64(1),
3006                Value::U64(2),
3007                Value::U64(3),
3008                Value::U64(5),
3009                Value::U64(8),
3010                Value::U64(13),
3011                Value::U64(21),
3012            ]
3013        );
3014    }
3015
3016    #[test]
3017    fn fib_until_50() {
3018        let v = evaluate_spec("fib_until(50)", &empty_kernel()).unwrap();
3019        assert_eq!(
3020            v,
3021            vec![
3022                Value::U64(1),
3023                Value::U64(1),
3024                Value::U64(2),
3025                Value::U64(3),
3026                Value::U64(5),
3027                Value::U64(8),
3028                Value::U64(13),
3029                Value::U64(21),
3030                Value::U64(34),
3031            ]
3032        );
3033    }
3034
3035    #[test]
3036    fn pow2_n_six() {
3037        let v = evaluate_spec("pow2(6)", &empty_kernel()).unwrap();
3038        assert_eq!(
3039            v,
3040            vec![
3041                Value::U64(1),
3042                Value::U64(2),
3043                Value::U64(4),
3044                Value::U64(8),
3045                Value::U64(16),
3046                Value::U64(32),
3047            ]
3048        );
3049    }
3050
3051    #[test]
3052    fn pow2_until_100() {
3053        let v = evaluate_spec("pow2_until(100)", &empty_kernel()).unwrap();
3054        assert_eq!(
3055            v,
3056            vec![
3057                Value::U64(1),
3058                Value::U64(2),
3059                Value::U64(4),
3060                Value::U64(8),
3061                Value::U64(16),
3062                Value::U64(32),
3063                Value::U64(64),
3064            ]
3065        );
3066    }
3067
3068    #[test]
3069    fn binomial_n_5() {
3070        // C(5,0..5) = 1, 5, 10, 10, 5, 1
3071        let v = evaluate_spec("binomial(5)", &empty_kernel()).unwrap();
3072        assert_eq!(
3073            v,
3074            vec![
3075                Value::U64(1),
3076                Value::U64(5),
3077                Value::U64(10),
3078                Value::U64(10),
3079                Value::U64(5),
3080                Value::U64(1),
3081            ]
3082        );
3083    }
3084
3085    #[test]
3086    fn geometric_2_doubles_4_terms() {
3087        let v = evaluate_spec("geometric(1, 2, 4)", &empty_kernel()).unwrap();
3088        // Floats because factor is float-cast at eval.
3089        if let [Value::F64(a), Value::F64(b), Value::F64(c), Value::F64(d)] = v.as_slice() {
3090            assert!((a - 1.0).abs() < 1e-12);
3091            assert!((b - 2.0).abs() < 1e-12);
3092            assert!((c - 4.0).abs() < 1e-12);
3093            assert!((d - 8.0).abs() < 1e-12);
3094        } else {
3095            panic!("expected 4 f64 values, got {v:?}");
3096        }
3097    }
3098
3099    #[test]
3100    fn linear_starts_half_open_5_points() {
3101        let v = evaluate_spec("linear_starts(0, 100, 5)", &empty_kernel()).unwrap();
3102        // (100-0)/5 = 20 step. 0, 20, 40, 60, 80.
3103        if let [
3104            Value::F64(a),
3105            Value::F64(b),
3106            Value::F64(c),
3107            Value::F64(d),
3108            Value::F64(e),
3109        ] = v.as_slice()
3110        {
3111            assert!((a - 0.0).abs() < 1e-12);
3112            assert!((b - 20.0).abs() < 1e-12);
3113            assert!((c - 40.0).abs() < 1e-12);
3114            assert!((d - 60.0).abs() < 1e-12);
3115            assert!((e - 80.0).abs() < 1e-12);
3116        } else {
3117            panic!("got {v:?}");
3118        }
3119    }
3120
3121    #[test]
3122    fn linear_steps_inclusive_5_points() {
3123        let v = evaluate_spec("linear_steps(0, 100, 5)", &empty_kernel()).unwrap();
3124        // 0, 25, 50, 75, 100
3125        if let [
3126            Value::F64(a),
3127            Value::F64(b),
3128            Value::F64(c),
3129            Value::F64(d),
3130            Value::F64(e),
3131        ] = v.as_slice()
3132        {
3133            assert!((a - 0.0).abs() < 1e-12);
3134            assert!((b - 25.0).abs() < 1e-12);
3135            assert!((c - 50.0).abs() < 1e-12);
3136            assert!((d - 75.0).abs() < 1e-12);
3137            assert!((e - 100.0).abs() < 1e-12);
3138        } else {
3139            panic!("got {v:?}");
3140        }
3141    }
3142
3143    #[test]
3144    fn log_steps_3_decades() {
3145        let v = evaluate_spec("log_steps(1, 1000, 4)", &empty_kernel()).unwrap();
3146        // 1, 10, 100, 1000
3147        if let [Value::F64(a), Value::F64(b), Value::F64(c), Value::F64(d)] = v.as_slice() {
3148            assert!((a - 1.0).abs() < 1e-9);
3149            assert!((b - 10.0).abs() < 1e-9);
3150            assert!((c - 100.0).abs() < 1e-9);
3151            assert_eq!(*d, 1000.0);
3152        } else {
3153            panic!("got {v:?}");
3154        }
3155    }
3156
3157    #[test]
3158    fn log_steps_rejects_non_positive_bounds() {
3159        let err = evaluate_spec("log_steps(0, 100, 5)", &empty_kernel())
3160            .unwrap_err()
3161            .to_string();
3162        assert!(
3163            err.contains("log_steps.start: expected a positive number, got 0"),
3164            "{err}"
3165        );
3166        let err = evaluate_spec("log_steps(1, -2, 5)", &empty_kernel())
3167            .unwrap_err()
3168            .to_string();
3169        assert!(
3170            err.contains("log_steps.end: expected a positive number, got -2"),
3171            "{err}"
3172        );
3173    }
3174
3175    /// The last point of `linear_steps` and both ends of `log_steps` are
3176    /// the given bounds exactly, not sums or `exp`s that round near them.
3177    #[test]
3178    fn inclusive_steps_end_exactly_at_their_bounds() {
3179        let floats = |spec: &str| -> Vec<f64> {
3180            evaluate_spec(spec, &empty_kernel())
3181                .unwrap()
3182                .iter()
3183                .map(|v| match v {
3184                    Value::F64(f) => *f,
3185                    other => panic!("{spec}: {other:?}"),
3186                })
3187                .collect()
3188        };
3189        for (spec, start, end) in [
3190            ("log_steps(1, 1000, 4)", 1.0, 1000.0),
3191            ("log_steps(3, 7, 9)", 3.0, 7.0),
3192            ("log_steps(0.1, 0.7, 13)", 0.1, 0.7),
3193            ("log_steps(1000, 1, 4)", 1000.0, 1.0),
3194            ("linear_steps(0, 1, 4)", 0.0, 1.0),
3195            ("linear_steps(0.1, 0.7, 13)", 0.1, 0.7),
3196            ("linear_steps(-3, 1e9, 7)", -3.0, 1e9),
3197        ] {
3198            let v = floats(spec);
3199            assert_eq!(v.first(), Some(&start), "{spec}: {v:?}");
3200            assert_eq!(v.last(), Some(&end), "{spec}: {v:?}");
3201        }
3202        assert_eq!(floats("linear_steps(2, 5, 1)"), vec![2.0]);
3203        assert_eq!(floats("log_steps(2, 5, 1)"), vec![2.0]);
3204    }
3205
3206    /// The largest valid argument of each generator whose terms outgrow
3207    /// `u64`, found by computing the terms in `u128`: the first term
3208    /// past `u64::MAX` is the one the refusal names.
3209    #[test]
3210    fn overflow_limits_are_where_the_terms_leave_u64() {
3211        let max = u128::from(u64::MAX);
3212        // Fibonacci: the first term past u64::MAX, 1-based.
3213        let (mut a, mut b, mut term) = (1u128, 1u128, 1u64);
3214        while a <= max {
3215            (a, b, term) = (b, a + b, term + 1);
3216        }
3217        assert_eq!(term, 94);
3218        assert_eq!(NamedGenerator::Fib.largest_valid_argument(), Some(term - 1));
3219        // Powers of two: 2^64 is term 65.
3220        assert_eq!(1u128 << 64, max + 1);
3221        assert_eq!(NamedGenerator::Pow2.largest_valid_argument(), Some(64));
3222        // Pascal's triangle: the first row with a coefficient past
3223        // u64::MAX, and that coefficient.
3224        let row_overflow = |n: u64| -> Option<u64> {
3225            let mut c = 1u128;
3226            (1..=n).find(|&k| {
3227                c = c * u128::from(n - k + 1) / u128::from(k);
3228                c > max
3229            })
3230        };
3231        let first_row = (0..).find(|&n| row_overflow(n).is_some()).unwrap();
3232        assert_eq!(first_row, 68);
3233        assert_eq!(row_overflow(68), Some(31));
3234        assert_eq!(
3235            NamedGenerator::Binomial.largest_valid_argument(),
3236            Some(first_row - 1)
3237        );
3238        assert_eq!(NamedGenerator::Geometric.largest_valid_argument(), None);
3239    }
3240
3241    /// Each limit is the last argument that yields every term, and the
3242    /// next is refused, naming the call, the first term past
3243    /// `u64::MAX`, and the limit.
3244    #[test]
3245    fn a_call_past_its_limit_is_refused_by_its_first_overflowing_term() {
3246        let k = empty_kernel();
3247        let fib = evaluate_spec("fib(93)", &k).unwrap();
3248        assert_eq!(fib.len(), 93);
3249        assert_eq!(fib[92], Value::U64(12_200_160_415_121_876_738));
3250        let pow2 = evaluate_spec("pow2(64)", &k).unwrap();
3251        assert_eq!(pow2.last(), Some(&Value::U64(1 << 63)));
3252        let row = evaluate_spec("binomial(67)", &k).unwrap();
3253        assert_eq!(row.len(), 68);
3254        assert_eq!(row[33], Value::U64(14_226_520_737_620_288_370));
3255        for (spec, message) in [
3256            (
3257                "fib(94)",
3258                "fib(94): term 94 is past u64::MAX; fib.n is at most 93",
3259            ),
3260            (
3261                "fib(18446744073709551615)",
3262                "fib(18446744073709551615): term 94 is past u64::MAX",
3263            ),
3264            (
3265                "pow2(65)",
3266                "pow2(65): term 65, 2^64, is past u64::MAX; pow2.n is at most 64",
3267            ),
3268            (
3269                "binomial(68)",
3270                "binomial(68): term C(68, 31) is past u64::MAX; binomial.n is at most 67",
3271            ),
3272            (
3273                "binomial(70)",
3274                "binomial(70): term C(70, 28) is past u64::MAX",
3275            ),
3276            (
3277                "binomial(1000000000000)",
3278                "binomial(1000000000000): term C(1000000000000, 2) is past u64::MAX",
3279            ),
3280        ] {
3281            let err = evaluate_spec(spec, &k).unwrap_err().to_string();
3282            assert!(err.contains(message), "{spec}: {err}");
3283        }
3284    }
3285
3286    /// `geometric` takes a positive, finite factor, and
3287    /// `geometric_until` a finite factor above 1; the refusal names the
3288    /// argument.
3289    #[test]
3290    fn a_geometric_factor_out_of_range_is_refused_by_name() {
3291        let k = empty_kernel();
3292        for (spec, message) in [
3293            (
3294                "geometric(1, 0, 4)",
3295                "geometric.factor: expected a positive, finite number, got 0",
3296            ),
3297            (
3298                "geometric(1, -2, 4)",
3299                "geometric.factor: expected a positive, finite number, got -2",
3300            ),
3301            (
3302                "geometric(1, inf, 4)",
3303                "geometric.factor: expected a positive, finite number, got inf",
3304            ),
3305            (
3306                "geometric_until(1, 1, 100)",
3307                "geometric_until.factor: expected a finite number greater than 1, got 1",
3308            ),
3309            (
3310                "geometric_until(1, 0.5, 100)",
3311                "geometric_until.factor: expected a finite number greater than 1, got 0.5",
3312            ),
3313        ] {
3314            let err = evaluate_spec(spec, &k).unwrap_err().to_string();
3315            assert!(err.contains(message), "{spec}: {err}");
3316        }
3317        assert_eq!(
3318            evaluate_spec("geometric(8, 0.5, 3)", &k).unwrap(),
3319            vec![Value::F64(8.0), Value::F64(4.0), Value::F64(2.0)]
3320        );
3321        assert!(
3322            evaluate_spec("geometric_until(0, 2, 100)", &k)
3323                .unwrap()
3324                .is_empty()
3325        );
3326    }
3327
3328    /// The refusal of a named generator is found through the calls that
3329    /// enclose it; a call that expands, and a call of anything else, is
3330    /// not a refusal.
3331    #[test]
3332    fn refused_generator_call_looks_through_enclosing_calls() {
3333        let k = empty_kernel();
3334        let refused = refused_generator_call("concat(1..3, take(fib(94), 2))", &k).unwrap();
3335        assert!(refused.starts_with("fib(94): term 94"), "{refused}");
3336        assert_eq!(refused_generator_call("concat(fib(8), pow2(64))", &k), None);
3337        assert_eq!(refused_generator_call("hash(3)", &k), None);
3338        assert_eq!(refused_generator_call("1, 2, 3", &k), None);
3339        let refused = refused_generator_call("fib(-1)", &k).unwrap();
3340        assert!(
3341            refused.contains("fib.n: expected non-negative integer, got '-1'"),
3342            "{refused}"
3343        );
3344    }
3345
3346    // ── Set operators ──
3347
3348    #[test]
3349    fn concat_two_ranges() {
3350        let v = evaluate_spec("concat(1..4, 10..13)", &empty_kernel()).unwrap();
3351        assert_eq!(
3352            v,
3353            vec![
3354                Value::U64(1),
3355                Value::U64(2),
3356                Value::U64(3),
3357                Value::U64(10),
3358                Value::U64(11),
3359                Value::U64(12),
3360            ]
3361        );
3362    }
3363
3364    #[test]
3365    fn unique_dedupes_first_occurrence() {
3366        let v = evaluate_spec("unique(1..4, 3..6)", &empty_kernel()).unwrap();
3367        // 1,2,3 (from first) + 4,5 (from second; 3 already present)
3368        assert_eq!(
3369            v,
3370            vec![
3371                Value::U64(1),
3372                Value::U64(2),
3373                Value::U64(3),
3374                Value::U64(4),
3375                Value::U64(5),
3376            ]
3377        );
3378    }
3379
3380    #[test]
3381    fn intersect_keeps_only_common_values() {
3382        let v = evaluate_spec("intersect(1..10, 5..15)", &empty_kernel()).unwrap();
3383        assert_eq!(
3384            v,
3385            vec![
3386                Value::U64(5),
3387                Value::U64(6),
3388                Value::U64(7),
3389                Value::U64(8),
3390                Value::U64(9),
3391            ]
3392        );
3393    }
3394
3395    #[test]
3396    fn subtract_drops_values_in_b() {
3397        let v = evaluate_spec("subtract(1..6, 3..5)", &empty_kernel()).unwrap();
3398        // 1..6 = [1,2,3,4,5], minus [3,4] = [1, 2, 5]
3399        assert_eq!(v, vec![Value::U64(1), Value::U64(2), Value::U64(5)]);
3400    }
3401
3402    #[test]
3403    fn interleave_round_robin_two_lists() {
3404        let v = evaluate_spec("interleave(1..4, 10..13)", &empty_kernel()).unwrap();
3405        assert_eq!(
3406            v,
3407            vec![
3408                Value::U64(1),
3409                Value::U64(10),
3410                Value::U64(2),
3411                Value::U64(11),
3412                Value::U64(3),
3413                Value::U64(12),
3414            ]
3415        );
3416    }
3417
3418    #[test]
3419    fn cycle_repeats_n_times() {
3420        let v = evaluate_spec("cycle(1..3, 3)", &empty_kernel()).unwrap();
3421        assert_eq!(
3422            v,
3423            vec![
3424                Value::U64(1),
3425                Value::U64(2),
3426                Value::U64(1),
3427                Value::U64(2),
3428                Value::U64(1),
3429                Value::U64(2),
3430            ]
3431        );
3432    }
3433
3434    #[test]
3435    fn reverse_inverts_list() {
3436        let v = evaluate_spec("reverse(1..5)", &empty_kernel()).unwrap();
3437        assert_eq!(
3438            v,
3439            vec![Value::U64(4), Value::U64(3), Value::U64(2), Value::U64(1),]
3440        );
3441    }
3442
3443    #[test]
3444    fn take_n_takes_prefix() {
3445        let v = evaluate_spec("take(1..10, 3)", &empty_kernel()).unwrap();
3446        assert_eq!(v, vec![Value::U64(1), Value::U64(2), Value::U64(3)]);
3447    }
3448
3449    #[test]
3450    fn skip_n_drops_prefix() {
3451        let v = evaluate_spec("skip(1..6, 2)", &empty_kernel()).unwrap();
3452        assert_eq!(v, vec![Value::U64(3), Value::U64(4), Value::U64(5)]);
3453    }
3454
3455    #[test]
3456    fn unique_composes_with_pow2_and_range() {
3457        let v = evaluate_spec("unique(pow2(8), 1..1000..100)", &empty_kernel()).unwrap();
3458        // pow2(8) = 1, 2, 4, 8, 16, 32, 64, 128
3459        // 1..1000..100 = 1, 101, 201, 301, 401, 501, 601, 701, 801, 901
3460        // dedupe: 1, 2, 4, 8, 16, 32, 64, 128, 101, 201, 301, 401, 501, 601, 701, 801, 901
3461        assert_eq!(v.len(), 17);
3462        assert_eq!(v[0], Value::U64(1));
3463        assert_eq!(v[7], Value::U64(128));
3464        assert_eq!(v[8], Value::U64(101));
3465    }
3466
3467    // ── Sequencer expansions ──
3468
3469    #[test]
3470    fn bucket_round_robin_3_1_2() {
3471        // Two-arg form: items list + ratios list.
3472        let v = evaluate_spec(
3473            "bucket(concat('ann', 'scan', 'fetch'), concat(3, 1, 2))",
3474            &empty_kernel(),
3475        )
3476        .unwrap();
3477        // Wait — concat doesn't make sense with these args (mixed types).
3478        // Use the literal form via the Polydat list parser.
3479        let _ = v;
3480    }
3481
3482    #[test]
3483    fn bucket_ratio_prefix_shorthand_round_robin() {
3484        let v = evaluate_spec("bucket(\"3:ann, 1:scan, 2:fetch\")", &empty_kernel()).unwrap();
3485        // Bucket sequencer round-robins; each "tick" pulls
3486        // one from each remaining bucket. Total = 6.
3487        assert_eq!(v.len(), 6);
3488        let strs: Vec<&str> = v
3489            .iter()
3490            .filter_map(|v| match v {
3491                Value::Str(s) => Some(&**s),
3492                _ => None,
3493            })
3494            .collect();
3495        // First tick: ann, scan, fetch (one from each).
3496        // Then ann (3 left), fetch (2 left). Next: ann, fetch.
3497        // Then ann. Total: ann*3, scan*1, fetch*2.
3498        let counts = strs.iter().fold(
3499            std::collections::HashMap::<&str, usize>::new(),
3500            |mut m, s| {
3501                *m.entry(s).or_insert(0) += 1;
3502                m
3503            },
3504        );
3505        assert_eq!(counts.get("ann"), Some(&3));
3506        assert_eq!(counts.get("scan"), Some(&1));
3507        assert_eq!(counts.get("fetch"), Some(&2));
3508    }
3509
3510    #[test]
3511    fn concat_seq_emits_contiguous_runs() {
3512        let v = evaluate_spec(
3513            "concat_seq(\"2:warmup, 3:bench, 1:cooldown\")",
3514            &empty_kernel(),
3515        )
3516        .unwrap();
3517        let strs: Vec<String> = v
3518            .iter()
3519            .filter_map(|v| match v {
3520                Value::Str(s) => Some(s.to_string()),
3521                _ => None,
3522            })
3523            .collect();
3524        assert_eq!(
3525            strs,
3526            vec!["warmup", "warmup", "bench", "bench", "bench", "cooldown",]
3527        );
3528    }
3529
3530    #[test]
3531    fn interval_seq_evenly_spreads_higher_ratio() {
3532        let v = evaluate_spec("interval_seq(\"3:read, 1:write\")", &empty_kernel()).unwrap();
3533        // Total length 4. write should appear once,
3534        // somewhere in the middle (not bunched at edges).
3535        let strs: Vec<String> = v
3536            .iter()
3537            .filter_map(|v| match v {
3538                Value::Str(s) => Some(s.to_string()),
3539                _ => None,
3540            })
3541            .collect();
3542        assert_eq!(strs.len(), 4);
3543        let writes: Vec<usize> = strs
3544            .iter()
3545            .enumerate()
3546            .filter(|(_, s)| *s == "write")
3547            .map(|(i, _)| i)
3548            .collect();
3549        assert_eq!(writes.len(), 1, "expected exactly one write: {strs:?}");
3550    }
3551
3552    #[test]
3553    fn parse_func_call_recognises_simple_call() {
3554        let (n, a) = parse_func_call("fib(8)").unwrap();
3555        assert_eq!(n, "fib");
3556        assert_eq!(a, "8");
3557    }
3558
3559    #[test]
3560    fn parse_func_call_rejects_non_calls() {
3561        assert!(parse_func_call("1..10").is_none());
3562        assert!(parse_func_call("foo + bar").is_none());
3563        assert!(parse_func_call("f(a) + g(b)").is_none()); // mid-text close
3564    }
3565
3566    #[test]
3567    fn split_args_top_level_skips_inner_commas() {
3568        let args = split_args_top_level("a, f(b, c), \"x, y\", 3");
3569        assert_eq!(args, vec!["a", "f(b, c)", "\"x, y\"", "3"]);
3570    }
3571}