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