Skip to main content

polydat_core/dsl/
compile.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! DSL-to-assembly bridge: compile a parsed Polydat AST into a runtime kernel.
5//!
6//! Walks the AST, resolves function names to node constructors, wires
7//! the `PolydatAssembler`, and produces the interpreter's
8//! `PolydatKernel` or any engine's boxed `Kernel`.
9
10use std::path::{Path, PathBuf};
11
12use crate::compile::assembly::{PolydatAssembler, WireRef};
13use crate::dsl::ast::*;
14use crate::dsl::lexer;
15use crate::dsl::parser;
16use crate::kernel::PolydatKernel;
17
18use crate::dsl::error::DiagnosticReport;
19use crate::dsl::validate::{collect_references, validate_ast};
20
21use std::collections::HashSet;
22
23use super::modules::ResolvedModule;
24
25/// Typed error ontology for the embedded-evaluation surface.
26///
27/// Per `expression_engine.md` §6 Error Ontology (under
28/// `crates/polydat/docs/design/`), every failure mode the embedding
29/// surface can produce maps to one of these variants. Hosts
30/// pattern-match on the variant to drive UX, recovery, or logging
31/// without parsing message strings.
32///
33/// The embedding surfaces (`eval_const_expr*`, the typed surfaces,
34/// `interpolate_via_kernel`) return this type; the `compile_polydat*`
35/// entry points return `String` errors, and `From<EmbeddingError>
36/// for String` bridges the two.
37#[derive(Debug, Clone)]
38pub enum EmbeddingError {
39    /// Text could not be parsed as polydat expression source.
40    /// The lexer or parser rejected the input before any
41    /// semantic analysis.
42    Parse {
43        /// The source text.
44        source: String,
45        /// The lexer's or parser's message.
46        message: String,
47        /// The byte offset of the error, when known.
48        position: Option<usize>,
49    },
50
51    /// A `{name}` placeholder in the text had no matching
52    /// binding in the kernel chain. Produced by
53    /// `interpolate_via_kernel` only.
54    UnresolvedPlaceholder {
55        /// The placeholder's name.
56        name: String,
57        /// The source text.
58        source: String,
59    },
60
61    /// The expression's upstream cone reaches a dynamic input,
62    /// but the requested evaluation surface requires
63    /// effectively-const lifecycle. Produced by
64    /// `eval_const_expr` (directly or via the two-step
65    /// composition).
66    LifecycleMismatch {
67        /// The source text.
68        source: String,
69        /// The dynamic inputs the cone reaches.
70        dynamic_inputs: Vec<String>,
71    },
72
73    /// A node mentioned in the expression is not registered
74    /// in the runtime. Includes a suggested alternative when
75    /// the name is close to a known node.
76    UnknownNode {
77        /// The unknown node's name.
78        name: String,
79        /// The source text.
80        source: String,
81        /// A registered name close to it, if any.
82        suggestion: Option<String>,
83    },
84
85    /// The expression's wire chain has a type mismatch that
86    /// auto-adapters cannot heal. Produced by the assembly
87    /// pass during compilation.
88    TypeMismatch {
89        /// The producing node.
90        from_node: String,
91        /// Its output type.
92        from_type: crate::ast::PortType,
93        /// The consuming node.
94        to_node: String,
95        /// The type its port requires.
96        to_type: crate::ast::PortType,
97        /// The source text.
98        source: String,
99    },
100
101    /// A node's `eval` panicked during scope-init evaluation.
102    /// The kernel's `catch_unwind` boundary captured the
103    /// panic; the message is the panic payload's
104    /// human-readable form.
105    NodeEvalPanic {
106        /// The node that panicked.
107        node_name: String,
108        /// The panic's message.
109        message: String,
110        /// The source text.
111        source: String,
112    },
113
114    /// A `Value::None` propagated to the expression's output
115    /// where a concrete value was required. Produced by a
116    /// `HostType::from_value` conversion that meets `Value::None`,
117    /// or by a host's own strict accessor (`as_bool` on
118    /// `Value::None`, etc.). See none_semantics.md.
119    NonePropagated {
120        /// The accessor the host called.
121        accessor: &'static str,
122        /// The source text.
123        source: String,
124    },
125}
126
127impl std::fmt::Display for EmbeddingError {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        match self {
130            EmbeddingError::Parse {
131                source,
132                message,
133                position,
134            } => match position {
135                Some(p) => write!(f, "parse error at position {p} in '{source}': {message}"),
136                None => write!(f, "parse error in '{source}': {message}"),
137            },
138            EmbeddingError::UnresolvedPlaceholder { name, source } => write!(
139                f,
140                "unresolved placeholder '{{{name}}}' in '{source}' — \
141                 no matching binding in the kernel chain"
142            ),
143            EmbeddingError::LifecycleMismatch {
144                source,
145                dynamic_inputs,
146            } => write!(
147                f,
148                "not a const expression: '{source}' depends on runtime inputs ({})",
149                dynamic_inputs.join(", ")
150            ),
151            EmbeddingError::UnknownNode {
152                name,
153                source,
154                suggestion,
155            } => match suggestion {
156                Some(sug) => write!(
157                    f,
158                    "unknown function: '{name}' in '{source}'\n\n  Did you mean '{sug}'?"
159                ),
160                None => write!(
161                    f,
162                    "unknown function: '{name}' in '{source}'\n\n  \
163                     This function is not registered in the Polydat function library."
164                ),
165            },
166            EmbeddingError::TypeMismatch {
167                from_node,
168                from_type,
169                to_node,
170                to_type,
171                source,
172            } => {
173                write!(
174                    f,
175                    "type mismatch in '{source}': cannot connect \
176                     {from_type:?} output of '{from_node}' to {to_type:?} \
177                     input of '{to_node}'"
178                )
179            }
180            EmbeddingError::NodeEvalPanic {
181                node_name,
182                message,
183                source,
184            } => write!(
185                f,
186                "node-eval panic in '{source}' (node '{node_name}'): {message}"
187            ),
188            EmbeddingError::NonePropagated { accessor, source } => write!(
189                f,
190                "Value::None propagated to '{source}'; \
191                 host called strict accessor `{accessor}`. \
192                 Use a non-strict accessor (`try_as_*`) or surface the None to the user."
193            ),
194        }
195    }
196}
197
198impl std::error::Error for EmbeddingError {}
199
200/// Renders the error as its message for callers on the
201/// `Result<_, String>` entry points.
202impl From<EmbeddingError> for String {
203    fn from(e: EmbeddingError) -> String {
204        e.to_string()
205    }
206}
207
208/// Embedded standard library modules, compiled into the binary.
209///
210/// Each entry is (filename, source). Multiple modules per file —
211/// each top-level binding is a separate module, resolved by name.
212/// Searched as the final fallback after the source directory and
213/// `CompileOptions::lib_paths` (the binary's `--lib`).
214pub(super) static STDLIB_MODULES: &[(&str, &str)] = &[
215    (
216        "hashing.polydat",
217        include_str!("../../stdlib/hashing.polydat"),
218    ),
219    (
220        "strings.polydat",
221        include_str!("../../stdlib/strings.polydat"),
222    ),
223    (
224        "identity.polydat",
225        include_str!("../../stdlib/identity.polydat"),
226    ),
227    (
228        "distributions.polydat",
229        include_str!("../../stdlib/distributions.polydat"),
230    ),
231    (
232        "latency.polydat",
233        include_str!("../../stdlib/latency.polydat"),
234    ),
235    (
236        "timeseries.polydat",
237        include_str!("../../stdlib/timeseries.polydat"),
238    ),
239    ("waves.polydat", include_str!("../../stdlib/waves.polydat")),
240    (
241        "fourier.polydat",
242        include_str!("../../stdlib/fourier.polydat"),
243    ),
244    (
245        "modeling.polydat",
246        include_str!("../../stdlib/modeling.polydat"),
247    ),
248];
249
250/// Return the embedded standard library module sources.
251pub fn stdlib_sources() -> &'static [(&'static str, &'static str)] {
252    STDLIB_MODULES
253}
254
255/// Compile a `.polydat` source string under the default options, on the
256/// engine those options name — which is [`Engine::default`](crate::Engine::default),
257/// the most native form the build has.
258///
259/// This is the way in. The kernel comes back as `dyn Kernel`, which is
260/// the surface every use of a kernel goes through, and the engine is a
261/// value the options carry rather than a branch in the code: a caller
262/// that wants a different one sets `options.engine` and calls
263/// [`compile_polydat_kernel_with_options`], rather than calling a
264/// differently-named function.
265///
266/// Naming an engine is for the callers whose *subject* is the engine:
267///
268/// - [`compile_polydat_interpreter`] for the interpreter's concrete
269///   kernel, when a test or diagnostic needs its own internals, or when
270///   it is being used as the semantic oracle a differential test
271///   compares a compiled engine against. That is a real need, and it
272///   says so by name, so a host that names no engine never gets the
273///   slowest one.
274/// - [`compile_polydat_with`] to walk the tiers with one source.
275pub fn compile_polydat(source: &str) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
276    compile_polydat_kernel(source)
277}
278
279/// [`compile_polydat`] returning the interpreter's concrete kernel.
280///
281/// This is the carve-out from the rule that kernels are used through
282/// the [`Kernel`](crate::Kernel) trait, and it is narrow on purpose:
283/// the concrete type carries the interpreter's implementation detail
284/// (`program()`, `lookup()`, `state()`, `build_subscope()`, the
285/// constant and wire readers), which a test asserting on that detail
286/// and a diagnostic reporting it both need and nothing else should
287/// reach for. Driving a kernel — coordinates, externs, cursors,
288/// evaluation, reads, traversals — is the trait's, on every engine
289/// including this one.
290pub fn compile_polydat_interpreter(source: &str) -> Result<PolydatKernel, crate::KernelError> {
291    compile_polydat_interpreter_with_options(source, &CompileOptions::default(), None)
292}
293
294/// Parse Polydat source into the program tree, the form every
295/// transform reads and rewrites.
296///
297/// This is the first of the three steps a host takes when it shapes a
298/// program before running it: parse, transform, compile. A host with
299/// nothing to change calls a `compile_polydat*` entry point instead
300/// and never sees a tree; a host that injects a value
301/// ([`transform::assign_values`](super::transform::assign_values)),
302/// adds tiles it built from what it holds
303/// ([`transform::add_tiles`](super::transform::add_tiles)), or rewrites
304/// a definition in place applies as many of those as it means to the
305/// one tree and compiles it once with
306/// [`compile_ast_with_engine`] or
307/// [`compile_ast_interpreter_with_options`].
308///
309/// [`parse_polydat_with_tile_defaults`] is the same parse for a host
310/// that sets the hole delimiters a tile body is read with.
311pub fn parse_polydat(source: &str) -> Result<PolydatFile, crate::KernelError> {
312    let tokens = super::lexer::lex(source).map_err(crate::KernelError::Source)?;
313    super::parser::parse(tokens).map_err(crate::KernelError::Source)
314}
315
316/// [`parse_polydat`] with the hole delimiters and directive sigil a
317/// tile body that declares none of its own is read with.
318///
319/// These belong to the parse and not to a later rewrite: a tile body
320/// is raw text until it is read, so what counts as a hole has to be
321/// settled before there are pieces for a transform to address.
322pub fn parse_polydat_with_tile_defaults(
323    source: &str,
324    defaults: &super::ast::TileOptions,
325) -> Result<PolydatFile, crate::KernelError> {
326    let tokens = super::lexer::lex(source).map_err(crate::KernelError::Source)?;
327    super::parser::parse_with_tile_defaults(tokens, defaults).map_err(crate::KernelError::Source)
328}
329
330/// Compile Polydat source to an assembler (not yet compiled to a kernel).
331///
332/// Returns the `PolydatAssembler` with every node and wire in place,
333/// the graph a host may extend by hand before building it on any
334/// engine: [`PolydatAssembler::compile_kernel`] for the default engine,
335/// [`PolydatAssembler::compile_with`] for a named one,
336/// [`PolydatAssembler::compile`] for the interpreter's concrete kernel.
337/// An assembler carries no traversal, so a program with a `for`
338/// statement is refused here; the kernel entry points compile it.
339pub fn compile_polydat_to_assembler(source: &str) -> Result<PolydatAssembler, crate::KernelError> {
340    compile_polydat_to_assembler_with(source, &CompileOptions::default())
341}
342
343/// [`compile_polydat_to_assembler`] with the options the kernel entry
344/// points take: a source directory for relative imports, library
345/// directories, required outputs, strict typing, a diagnostic context,
346/// and a cursor limit. The assembler it returns is the graph
347/// [`compile_polydat_interpreter_with_options`] would compile from the same source
348/// and options, ready for any engine.
349pub fn compile_polydat_to_assembler_with(
350    source: &str,
351    options: &CompileOptions,
352) -> Result<PolydatAssembler, crate::KernelError> {
353    let tokens = super::lexer::lex(source).map_err(crate::KernelError::Source)?;
354    let ast = super::parser::parse(tokens).map_err(crate::KernelError::Source)?;
355    let mut prepared = Prepared::new(source, &ast, options, None);
356    let (compiler, filter) = prepared.parts();
357    compiler
358        .assemble_parent(&ast, filter)
359        .map_err(crate::KernelError::Source)
360}
361
362/// Compile one selected scalar output into the conservative perfect-ordinal
363/// Tier-1 SIMD executor.
364///
365/// This is an explicit execution surface: ordinary [`compile_polydat`] and
366/// `PolydatKernel::pull` remain scalar-cycle APIs. `driving_input` is normally
367/// a cursor projection such as `base__ordinal`; `output` names the only result
368/// drained by the batch executor.
369#[cfg(feature = "jit")]
370pub fn compile_polydat_tier1_simd_ordinal(
371    source: &str,
372    driving_input: &str,
373    output: &str,
374) -> Result<crate::compile::simd_tier1::Tier1SimdExecutor, String> {
375    compile_polydat_to_assembler(source)
376        .map_err(|e| e.to_string())?
377        .try_compile_tier1_simd_ordinal(driving_input, output)
378        .map_err(|error| error.to_string())
379}
380
381/// `const name := expr` declares a side-effect-carrying compile-time
382/// computation: download a dataset, prebuffer a facet, register a
383/// resource, etc. The user's signal that they want it evaluated is
384/// the `const` keyword itself, not a downstream wire reference. Yet
385/// the assembler's DCE pass walks back from the requested-outputs
386/// set and prunes anything not in that ancestry, which silently
387/// removes const bindings whose result nothing reads.
388///
389/// This helper extends a caller-supplied `required_outputs` list
390/// with every `const` binding target in the source. Two effects:
391/// the assembler keeps those nodes during DCE, and constant
392/// folding then evaluates them once at compile time — running the
393/// side effect exactly once, before any dispatch.
394///
395/// Plain bindings (`name := ...`) are *not* added; they only run
396/// when consumed. Modules and other statements are likewise not
397/// auto-promoted.
398fn extend_required_with_const_bindings(
399    required_outputs: &[String],
400    ast: &crate::dsl::ast::PolydatFile,
401) -> Vec<String> {
402    let mut out: Vec<String> = required_outputs.to_vec();
403    for stmt in &ast.statements {
404        if let crate::dsl::ast::Statement::Binding(b) = stmt
405            && b.modifier.is_const()
406        {
407            for name in &b.targets {
408                if !out.iter().any(|n| n == name) {
409                    out.push(name.clone());
410                }
411            }
412        }
413    }
414    out
415}
416
417/// RAII guard that sets the data-file base directory (see
418/// [`crate::library::datafile::set_data_base_dir`]) for the duration of
419/// a synchronous compile and restores the previous value on drop, so
420/// nested compiles unwind cleanly.
421struct DataBaseDirGuard(Option<PathBuf>);
422
423impl DataBaseDirGuard {
424    fn set(dir: &Path) -> Self {
425        DataBaseDirGuard(crate::library::datafile::set_data_base_dir(Some(
426            dir.to_path_buf(),
427        )))
428    }
429}
430
431impl Drop for DataBaseDirGuard {
432    fn drop(&mut self) {
433        crate::library::datafile::set_data_base_dir(self.0.take());
434    }
435}
436
437/// The options every entry point compiles under. A host that names
438/// none gets the defaults: no source directory, no library paths,
439/// every binding an output, lax typing, the default context label,
440/// no cursor limit, and the most compiled engine this build has.
441///
442/// `strict` refuses what lax compilation warns about, on every engine:
443/// an implicit type coercion, a config wire fed from a cycle-time
444/// source, a nondeterministic node no `volatile` output acknowledges, a
445/// binding nothing reads, an undeclared coordinate, and a positional
446/// module argument. It is also `pragma strict` at the program's top
447/// scope (polydat_grammar.md §14): strict value checks, strict type
448/// checks, and strict name checking hold in the program and in every
449/// scope that inherits its pragmas, and a module body follows its own
450/// pragmas alone.
451///
452/// `engine` is a **preference**, and the only place a caller expresses
453/// one. Leaving it alone is the normative path: [`Engine::default`](crate::Engine::default) is
454/// the most native form the build offers (native code with the `jit`
455/// feature, the closure tier without), so a host that never mentions
456/// the field still gets compiled code, and gets faster code for free
457/// when a build gains a tier. Naming an engine is for testing,
458/// measurement, and demonstration — a differential test that wants the
459/// interpreter as the reference, a bench that walks the tiers. A
460/// preference the build cannot realize is refused
461/// ([`crate::KernelError::Refused`]) rather than silently replaced, and
462/// every kernel reports what it actually runs through
463/// [`crate::Kernel::engine`].
464#[derive(Debug, Default, Clone)]
465pub struct CompileOptions {
466    /// The directory relative data-file paths resolve against.
467    pub source_dir: Option<PathBuf>,
468    /// Library search paths, tried after the source directory and before the embedded standard library.
469    pub lib_paths: Vec<PathBuf>,
470    /// The outputs to keep; every output when empty.
471    pub required_outputs: Vec<String>,
472    /// Whether to enforce strict validation, `pragma strict` at the
473    /// program's top scope included.
474    pub strict: bool,
475    /// The diagnostic context label, such as a file name.
476    pub context: String,
477    /// A limit on every cursor's extent, if any.
478    pub cursor_limit: Option<u64>,
479    /// The compile ledger to record this program tree in: a host that
480    /// holds one charges the compile to it; `None` mints a fresh one,
481    /// read back through the kernel's `ledger()`.
482    pub ledger: Option<std::sync::Arc<crate::kernel::CompileLedger>>,
483    /// The resource scope of the program tree: a host that holds one,
484    /// with or without an accessor installed, hands it here; `None`
485    /// gives the tree a fresh, empty one, read back through the
486    /// kernel's `resources()` and installable there.
487    pub resources: Option<crate::resource::ResourceScope>,
488    /// The engine to build on. Defaults to [`Engine::default`](crate::Engine::default), the
489    /// most native form this build has; see the type's documentation
490    /// for when to set it and what happens when it cannot be realized.
491    pub engine: crate::Engine,
492    /// What the compiler does with an input whose type the author did
493    /// not declare (input_variance.md §4). The default, `Fixed`, makes
494    /// the inferred type the input's and refuses a write of another
495    /// type.
496    pub input_variance: InputVariance,
497    /// Externs whose declared type the caller inferred rather than the
498    /// author wrote: the ones a program synthesizer emitted, such as a
499    /// scope builder's result and write-through externs. They are open
500    /// to `input_variance` as an auto-extern is (input_variance.md §3).
501    pub inferred_externs: Vec<String>,
502}
503
504/// What the compiler does with an *open* input, one whose type it
505/// inferred rather than the author declared: an auto-extern, or an
506/// `extern` a scope builder synthesized (input_variance.md §3, §4).
507/// Coordinates and declared inputs are never affected.
508///
509/// A converted input costs a converter node, which on the compiled
510/// engines is a closure step or a slot call from native code, run when
511/// the input changes (input_variance.md §5). A declared input and an
512/// open input under `Fixed` cost nothing, so conversion is asked for,
513/// never assumed.
514#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
515pub enum InputVariance {
516    /// An open input takes its inferred type, and a write of another
517    /// type is refused.
518    #[default]
519    Fixed,
520    /// An open input stops construction, naming it: every input's type
521    /// must be declared.
522    Error,
523    /// Every open input takes any value and gets a converter node to
524    /// the type its consumers read, each reported as a warning.
525    Warn,
526    /// As `Warn`, each converter reported as info.
527    Info,
528}
529
530/// Compile Polydat source into the interpreter's kernel under
531/// `options`, recording pragma and assembly events in `log` when one is
532/// given: the interpreter-typed entry point every other interpreter form
533/// reduces to. [`compile_polydat_with_engine`] is the same compile on
534/// any engine.
535pub fn compile_polydat_interpreter_with_options(
536    source: &str,
537    options: &CompileOptions,
538    mut log: Option<&mut super::events::CompileEventLog>,
539) -> Result<PolydatKernel, crate::KernelError> {
540    let tokens = lexer::lex(source).map_err(crate::KernelError::Source)?;
541    let ast = parser::parse(tokens).map_err(crate::KernelError::Source)?;
542    if let Some(log) = log.as_deref_mut() {
543        log.push(super::events::CompileEvent::Parsed {
544            statements: ast.statements.len(),
545        });
546    }
547    compile_ast_interpreter_with_options(&ast, source, options, log)
548}
549
550/// [`compile_polydat_interpreter_with_options`] for an already parsed, possibly
551/// transformed, program. `source` is the text the program was parsed
552/// from and is used for diagnostics only.
553pub fn compile_ast_interpreter_with_options(
554    ast: &PolydatFile,
555    source: &str,
556    options: &CompileOptions,
557    mut log: Option<&mut super::events::CompileEventLog>,
558) -> Result<PolydatKernel, crate::KernelError> {
559    let mut prepared = Prepared::new(source, ast, options, log.as_deref_mut());
560    let (compiler, filter) = prepared.parts();
561    // This path returns the interpreter's concrete kernel, so the
562    // options' engine preference can only say how much of the graph is
563    // fused into native cones. A preference naming the interpreter is
564    // honoured with its mode; any other preference is a caller asking a
565    // concrete-typed entry point for an engine it cannot return, and it
566    // gets the interpreter under the default cone mode. A caller that
567    // means the preference calls `compile_polydat_kernel_with_options`,
568    // which can return whichever engine the options name.
569    let cones = match options.engine {
570        crate::Engine::Interpreter(mode) => mode,
571        _ => crate::JitMode::Auto,
572    };
573    compiler.compile_interpreter(ast, filter, log, cones)
574}
575
576/// [`compile_polydat_interpreter_with_options`] under the default options, with the
577/// compile event log: the same kernel [`compile_polydat`] builds, with
578/// every pragma, assembly, fold, and tile event recorded.
579pub fn compile_polydat_interpreter_with_log(
580    source: &str,
581    log: &mut super::events::CompileEventLog,
582) -> Result<PolydatKernel, crate::KernelError> {
583    compile_polydat_interpreter_with_options(source, &CompileOptions::default(), Some(log))
584}
585
586/// Record one event per pragma in `set`: `PragmaAcknowledged`
587/// (advisory) for `strict_types`/`strict_values`/`strict`,
588/// `UnknownPragma` (warning) for the rest. Forward-compatible: an
589/// unknown pragma never blocks compilation.
590///
591/// Called from `Prepared::new` for every entry point given a log;
592/// the set comes from `pragmas::collect_from_ast`. A `for` body's and
593/// a module body's own pragmas are recorded when that scope compiles.
594pub(crate) fn record_pragma_events(
595    set: &super::pragmas::PragmaSet,
596    log: &mut super::events::CompileEventLog,
597) {
598    for entry in &set.entries {
599        log.push(pragma_event(entry));
600    }
601}
602
603/// The event one pragma records: `PragmaAcknowledged` for a
604/// recognised name, `UnknownPragma` for the rest.
605pub(crate) fn pragma_event(entry: &super::pragmas::Pragma) -> super::events::CompileEvent {
606    use super::events::CompileEvent;
607    if super::pragmas::is_known(&entry.name) {
608        CompileEvent::PragmaAcknowledged {
609            name: entry.name.clone(),
610            line: entry.line,
611        }
612    } else {
613        CompileEvent::UnknownPragma {
614            name: entry.name.clone(),
615            line: entry.line,
616        }
617    }
618}
619
620/// Compile with full diagnostics: errors, warnings, suggestions, on the
621/// default engine.
622///
623/// Returns `(Ok(kernel), report)` on success with possible warnings,
624/// or `(Err(()), report)` on failure with errors. The report always
625/// contains all diagnostics. The program the report describes is the
626/// program the kernel runs: the same compile every entry point makes.
627pub fn compile_polydat_checked(
628    source: &str,
629) -> (Result<Box<dyn crate::Kernel>, ()>, DiagnosticReport) {
630    let mut report = DiagnosticReport::new(source);
631
632    let tokens = match lexer::lex(source) {
633        Ok(t) => t,
634        Err(e) => {
635            report.error(crate::dsl::lexer::Span { line: 1, col: 1 }, e);
636            return (Err(()), report);
637        }
638    };
639
640    let ast = match parser::parse(tokens) {
641        Ok(a) => a,
642        Err(e) => {
643            report.error(crate::dsl::lexer::Span { line: 1, col: 1 }, e);
644            return (Err(()), report);
645        }
646    };
647
648    // Validate the AST before compiling
649    validate_ast(&ast, &mut report);
650
651    if report.has_errors() {
652        return (Err(()), report);
653    }
654
655    match compile_ast_with_engine(
656        &ast,
657        source,
658        &CompileOptions::default(),
659        None,
660        crate::Engine::default(),
661    ) {
662        Ok(kernel) => (Ok(kernel), report),
663        Err(e) => {
664            report.error(crate::dsl::lexer::Span { line: 1, col: 1 }, e.to_string());
665            (Err(()), report)
666        }
667    }
668}
669
670/// Cache of constant-expression results keyed by source text. A const
671/// expression compiles with no inputs, so its value is a pure function
672/// of its text; caching is exact. Bounded so a pathological caller
673/// cannot grow it without limit. This is what keeps repeated evaluation
674/// of the same range, list, or predicate text compile-free
675/// (for_traversal.md §5.2).
676static CONST_EXPR_CACHE: std::sync::OnceLock<
677    std::sync::Mutex<std::collections::HashMap<String, crate::ast::Value>>,
678> = std::sync::OnceLock::new();
679const CONST_EXPR_CACHE_CAP: usize = 8192;
680
681/// Evaluate a constant expression by compiling it as a one-binding
682/// program: what a comprehension source such as `partitions("*\/4", 1000)`
683/// goes through. Cached by source text, so the same text compiles once
684/// per process (for_traversal.md §5.2). An expression that reaches a dynamic
685/// input is a lifecycle error. The compile, when there is one, is
686/// recorded in a ledger of its own; [`eval_const_expr_for`] charges
687/// it to a tree's.
688///
689/// # Examples
690///
691/// Through the `polydat` facade, which links the node library the
692/// expression compiles against; `tests/rustdoc_examples.rs` in
693/// `polydat` runs it.
694///
695/// ```ignore
696/// use polydat::dsl::compile::eval_const_expr;
697/// let v = eval_const_expr("4 * 4").unwrap();
698/// assert_eq!(v.as_u64(), 16);  // both int literals → u64_mul
699/// let v = eval_const_expr("4.0 * 4.0").unwrap();
700/// assert_eq!(v.as_f64(), 16.0);  // both float literals → f64_mul
701/// ```
702pub fn eval_const_expr(source: &str) -> Result<crate::ast::Value, EmbeddingError> {
703    eval_const_expr_for(source, &crate::kernel::CompileLedger::new())
704}
705
706/// [`eval_const_expr`] with its compile, when the text is not cached,
707/// recorded in `ledger`: what a traversal source or predicate that has
708/// to compile charges to the tree that opened it.
709pub fn eval_const_expr_for(
710    source: &str,
711    ledger: &std::sync::Arc<crate::kernel::CompileLedger>,
712) -> Result<crate::ast::Value, EmbeddingError> {
713    let cache =
714        CONST_EXPR_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
715    if let Ok(map) = cache.lock()
716        && let Some(v) = map.get(source)
717    {
718        return Ok(v.clone());
719    }
720    let result = eval_const_expr_uncached(source, ledger);
721    if let Ok(v) = &result
722        && let Ok(mut map) = cache.lock()
723    {
724        if map.len() >= CONST_EXPR_CACHE_CAP {
725            map.clear();
726        }
727        map.insert(source.to_string(), v.clone());
728    }
729    result
730}
731
732fn eval_const_expr_uncached(
733    source: &str,
734    ledger: &std::sync::Arc<crate::kernel::CompileLedger>,
735) -> Result<crate::ast::Value, EmbeddingError> {
736    let wrapped = format!("\nout := {source}");
737    let source_owned = source.to_string();
738    let options = CompileOptions {
739        ledger: Some(ledger.clone()),
740        ..CompileOptions::default()
741    };
742    // Constant-folding inside `compile_polydat` invokes node `eval`
743    // for inputs-free DAGs, so any node that panics on bad data
744    // (e.g. `handle_of(&Value::None)` after a failed
745    // `dataset_open`) would unwind out past this function and
746    // crash any caller that doesn't itself catch panics. The
747    // kernel's `engines::eval_node` enriches node-eval panics
748    // with their provenance string; that string is what we
749    // extract.
750    let source_for_panic = source_owned.clone();
751    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(
752        move || -> Result<crate::ast::Value, EmbeddingError> {
753            let kernel = compile_polydat_interpreter_with_options(&wrapped, &options, None)
754                .map_err(|e| classify_compile_error(&source_owned, e))?;
755            kernel.get_constant("out").cloned().ok_or_else(|| {
756                // The expression compiled but did not fold, which
757                // means it reads something that is not known until
758                // the workload runs. The kernel's inputs are those
759                // things, and naming them is the whole point of the
760                // variant.
761                EmbeddingError::LifecycleMismatch {
762                    source: source_owned.clone(),
763                    dynamic_inputs: kernel.input_names(),
764                }
765            })
766        },
767    ));
768    match result {
769        Ok(r) => r,
770        Err(payload) => Err(EmbeddingError::NodeEvalPanic {
771            node_name: "(unknown)".to_string(),
772            message: panic_payload_message(&payload),
773            source: source_for_panic,
774        }),
775    }
776}
777
778/// Classify a compile failure into a typed [`EmbeddingError`].
779///
780/// The assembler's own errors are structured, so the fields are
781/// carried across rather than reconstructed: a wiring type mismatch
782/// keeps the two node names and the two types the assembler already
783/// knows. The DSL front end reports in strings, so the one shape a
784/// host acts on — an unregistered function — is read out of the
785/// message, and its suggestion comes from the registry rather than
786/// being dropped. Anything else keeps the compiler's own message.
787fn classify_compile_error(source: &str, err: crate::KernelError) -> EmbeddingError {
788    use crate::KernelError;
789    use crate::compile::assembly::AssemblyError;
790    if let KernelError::Assembly(AssemblyError::TypeMismatch {
791        from_node,
792        from_type,
793        to_node,
794        to_type,
795        ..
796    }) = err
797    {
798        return EmbeddingError::TypeMismatch {
799            from_node,
800            from_type,
801            to_node,
802            to_type,
803            source: source.to_string(),
804        };
805    }
806    let msg = err.to_string();
807    // The factory and the diagnostic pass both write "unknown
808    // function: '<name>'", the factory with the compiler's context
809    // ahead of it, so the marker is searched for rather than
810    // stripped from the front.
811    const UNKNOWN: &str = "unknown function: '";
812    if let Some(at) = msg.find(UNKNOWN)
813        && let Some(end) = msg[at + UNKNOWN.len()..].find('\'')
814    {
815        let name = msg[at + UNKNOWN.len()..][..end].to_string();
816        let suggestion = crate::dsl::registry::suggest_function(&name).map(str::to_string);
817        return EmbeddingError::UnknownNode {
818            name,
819            source: source.to_string(),
820            suggestion,
821        };
822    }
823    EmbeddingError::Parse {
824        source: source.to_string(),
825        message: msg,
826        position: None,
827    }
828}
829
830// ───── Typed embedding surface (γ-4) ─────
831
832/// Host-facing type that polydat can return from the typed
833/// embedding surfaces. The trait declares the polydat
834/// `PortType` the Rust type corresponds to and the conversion
835/// from the returned [`crate::ast::Value`] back to the host
836/// type.
837///
838/// Hosts that want compile-time type alignment use the typed
839/// surfaces ([`eval_const_expr_typed`] /
840/// [`eval_kernel_bound_typed`]) and let the type parameter
841/// drive the contract. The fall-back is the untyped surface
842/// (`eval_const_expr`) which returns a raw [`crate::ast::Value`]
843/// for hosts to coerce themselves.
844///
845/// See expression_engine.md §5.3.
846pub trait HostType: Sized {
847    /// The `PortType` that polydat compares the expression's
848    /// output type against. Used for compile-time / construction-
849    /// time type-mismatch detection.
850    fn target_port_type() -> crate::ast::PortType;
851
852    /// Convert a polydat [`crate::ast::Value`] into the host Rust
853    /// type. Returns a typed [`EmbeddingError::TypeMismatch`] when
854    /// the value cannot be represented as the host type; the impls
855    /// accept the lossless widenings (`U64` → `bool`/`f64`, scalars
856    /// → `String`).
857    fn from_value(v: crate::ast::Value) -> Result<Self, EmbeddingError>;
858}
859
860impl HostType for bool {
861    fn target_port_type() -> crate::ast::PortType {
862        crate::ast::PortType::Bool
863    }
864    fn from_value(v: crate::ast::Value) -> Result<Self, EmbeddingError> {
865        match v {
866            crate::ast::Value::Bool(b) => Ok(b),
867            crate::ast::Value::U64(n) => Ok(n != 0),
868            crate::ast::Value::None => Err(EmbeddingError::NonePropagated {
869                accessor: "HostType::<bool>::from_value",
870                source: "<typed-embedding result>".to_string(),
871            }),
872            other => Err(EmbeddingError::TypeMismatch {
873                from_node: "<expression-output>".to_string(),
874                from_type: other.port_type(),
875                to_node: "<host-target>".to_string(),
876                to_type: crate::ast::PortType::Bool,
877                source: "<typed-embedding result>".to_string(),
878            }),
879        }
880    }
881}
882
883impl HostType for u64 {
884    fn target_port_type() -> crate::ast::PortType {
885        crate::ast::PortType::U64
886    }
887    fn from_value(v: crate::ast::Value) -> Result<Self, EmbeddingError> {
888        match v {
889            crate::ast::Value::U64(n) => Ok(n),
890            crate::ast::Value::None => Err(EmbeddingError::NonePropagated {
891                accessor: "HostType::<u64>::from_value",
892                source: "<typed-embedding result>".to_string(),
893            }),
894            other => Err(EmbeddingError::TypeMismatch {
895                from_node: "<expression-output>".to_string(),
896                from_type: other.port_type(),
897                to_node: "<host-target>".to_string(),
898                to_type: crate::ast::PortType::U64,
899                source: "<typed-embedding result>".to_string(),
900            }),
901        }
902    }
903}
904
905impl HostType for f64 {
906    fn target_port_type() -> crate::ast::PortType {
907        crate::ast::PortType::F64
908    }
909    fn from_value(v: crate::ast::Value) -> Result<Self, EmbeddingError> {
910        match v {
911            crate::ast::Value::F64(n) => Ok(n),
912            crate::ast::Value::U64(n) => Ok(n as f64),
913            crate::ast::Value::None => Err(EmbeddingError::NonePropagated {
914                accessor: "HostType::<f64>::from_value",
915                source: "<typed-embedding result>".to_string(),
916            }),
917            other => Err(EmbeddingError::TypeMismatch {
918                from_node: "<expression-output>".to_string(),
919                from_type: other.port_type(),
920                to_node: "<host-target>".to_string(),
921                to_type: crate::ast::PortType::F64,
922                source: "<typed-embedding result>".to_string(),
923            }),
924        }
925    }
926}
927
928impl HostType for String {
929    fn target_port_type() -> crate::ast::PortType {
930        crate::ast::PortType::Str
931    }
932    fn from_value(v: crate::ast::Value) -> Result<Self, EmbeddingError> {
933        match v {
934            crate::ast::Value::Str(s) => Ok(s.to_string()),
935            crate::ast::Value::U64(n) => Ok(n.to_string()),
936            crate::ast::Value::F64(n) => Ok(n.to_string()),
937            crate::ast::Value::Bool(b) => Ok(b.to_string()),
938            crate::ast::Value::None => Err(EmbeddingError::NonePropagated {
939                accessor: "HostType::<String>::from_value",
940                source: "<typed-embedding result>".to_string(),
941            }),
942            other => Err(EmbeddingError::TypeMismatch {
943                from_node: "<expression-output>".to_string(),
944                from_type: other.port_type(),
945                to_node: "<host-target>".to_string(),
946                to_type: crate::ast::PortType::Str,
947                source: "<typed-embedding result>".to_string(),
948            }),
949        }
950    }
951}
952
953/// Const-fold the expression and convert the typed `Value`
954/// into the host's requested Rust type. Compile-time type
955/// alignment per expression_engine.md §5.3 + E5 + E7.
956///
957/// `T` must implement [`HostType`]. The expression's output
958/// `PortType` is compared against `T::target_port_type()`;
959/// matching types pass through directly to
960/// [`HostType::from_value`]. Mismatched types invoke the γ-6
961/// **return-path boundary adapter**: the catalog
962/// (`crate::compile::assembly::auto_adapter`) is consulted
963/// to heal the mismatch when possible. Only when no
964/// catalog entry exists for the (output_type, target_type)
965/// pair does this surface return
966/// `EmbeddingError::TypeMismatch`.
967///
968/// Pairs with [`eval_kernel_bound_typed`] for the
969/// kernel-bound (post-interpolation) case.
970pub fn eval_const_expr_typed<T: HostType>(source: &str) -> Result<T, EmbeddingError> {
971    let value = eval_const_expr(source)?;
972    let value_type = value.port_type();
973    let target_type = T::target_port_type();
974    if value_type == target_type {
975        return T::from_value(value);
976    }
977    // γ-6 return-path adapter: try the catalog before
978    // surfacing TypeMismatch.
979    if let Some(adapter) = crate::compile::assembly::auto_adapter(value_type, target_type) {
980        let inputs = vec![value];
981        let mut outputs = vec![crate::ast::Value::None];
982        adapter.eval(&inputs, &mut outputs);
983        return T::from_value(outputs.remove(0));
984    }
985    // No catalog entry — surface as typed error.
986    Err(EmbeddingError::TypeMismatch {
987        from_node: "<expression-output>".to_string(),
988        from_type: value_type,
989        to_node: "<host-target>".to_string(),
990        to_type: target_type,
991        source: source.to_string(),
992    })
993}
994
995/// Two-step: interpolate placeholders against `scope`, then
996/// const-fold + type-convert. The canonical pattern for
997/// kernel-bound typed embedding per expression_engine.md
998/// §3.2 + §5.3.
999///
1000/// `scope` is anything names resolve in: a kernel of any engine, a
1001/// [`Layered`](crate::kernel::interp::Layered) view of a tuple over
1002/// one, or the empty scope, so a host holding a compiled kernel reads a
1003/// binding through here without compiling its program again on the
1004/// interpreter.
1005pub fn eval_kernel_bound_typed<T: HostType>(
1006    text: &str,
1007    scope: &dyn crate::kernel::interp::Lookup,
1008) -> Result<T, EmbeddingError> {
1009    let interpolated = crate::kernel::interp::interpolate_via_kernel(text, scope)?;
1010    eval_const_expr_typed::<T>(&interpolated)
1011}
1012
1013/// Strict-mode variant of [`eval_const_expr_typed`].
1014///
1015/// Rejects type mismatches whose only catalog adapter is
1016/// **lossy** (e.g., `F64 → U64` truncation, `U64 → Bool`
1017/// boolean coercion). Hosts that want guaranteed-lossless
1018/// value passage opt into this surface per
1019/// `expression_engine.md` §5.1.3 (opt-in strict contract).
1020///
1021/// The "lossy" classification is per
1022/// [`is_lossless_adapter`] below; the function returns
1023/// `false` for catalog entries that change the value's
1024/// information content (truncation, narrowing, boolean
1025/// projection).
1026pub fn eval_const_expr_typed_strict<T: HostType>(source: &str) -> Result<T, EmbeddingError> {
1027    let value = eval_const_expr(source)?;
1028    let value_type = value.port_type();
1029    let target_type = T::target_port_type();
1030    if value_type == target_type {
1031        return T::from_value(value);
1032    }
1033    if !is_lossless_adapter(value_type, target_type) {
1034        return Err(EmbeddingError::TypeMismatch {
1035            from_node: "<expression-output>".to_string(),
1036            from_type: value_type,
1037            to_node: "<host-target>".to_string(),
1038            to_type: target_type,
1039            source: source.to_string(),
1040        });
1041    }
1042    if let Some(adapter) = crate::compile::assembly::auto_adapter(value_type, target_type) {
1043        let inputs = vec![value];
1044        let mut outputs = vec![crate::ast::Value::None];
1045        adapter.eval(&inputs, &mut outputs);
1046        return T::from_value(outputs.remove(0));
1047    }
1048    Err(EmbeddingError::TypeMismatch {
1049        from_node: "<expression-output>".to_string(),
1050        from_type: value_type,
1051        to_node: "<host-target>".to_string(),
1052        to_type: target_type,
1053        source: source.to_string(),
1054    })
1055}
1056
1057/// Strict-mode kernel-bound variant. Composes
1058/// [`crate::kernel::interp::interpolate_via_kernel`] with
1059/// [`eval_const_expr_typed_strict`].
1060pub fn eval_kernel_bound_typed_strict<T: HostType>(
1061    text: &str,
1062    scope: &dyn crate::kernel::interp::Lookup,
1063) -> Result<T, EmbeddingError> {
1064    let interpolated = crate::kernel::interp::interpolate_via_kernel(text, scope)?;
1065    eval_const_expr_typed_strict::<T>(&interpolated)
1066}
1067
1068/// Whether a conversion from one port type to another keeps the
1069/// value: whether every number `from` can carry is a number `to`
1070/// can carry.
1071///
1072/// The answer is read off the two types' own numeric domains
1073/// ([`crate::ast::PortType::numeric_domain`]) rather than looked up in a table of
1074/// pairs. A table has to be kept in step with the adapter catalog by
1075/// hand, and the catalog has well over a hundred pairs; the domains
1076/// answer every pair, including that `U8 → U64` is lossless and that
1077/// `U64 → F64` and `I64 → F64` round above `2^53`.
1078///
1079/// Rendering to `Str` keeps the value for the types that have a
1080/// numeric domain, since each of those renders with a round-trip
1081/// `Display`. Every other conversion — into `Bytes`, `Json`, a
1082/// vector, `Ext` — is out of the scalar world and is not claimed
1083/// lossless here, whatever the catalog can do with it.
1084///
1085/// Strict-mode embedding surfaces use this to gate which catalog
1086/// adapters they will invoke.
1087pub fn is_lossless_adapter(from: crate::ast::PortType, to: crate::ast::PortType) -> bool {
1088    use crate::ast::PortType;
1089    if from == to {
1090        return true;
1091    }
1092    let Some(f) = from.numeric_domain() else {
1093        return false;
1094    };
1095    if to == PortType::Str {
1096        return true;
1097    }
1098    to.numeric_domain().is_some_and(|t| f.fits_in(t))
1099}
1100
1101// ───── End typed embedding surface ─────
1102
1103/// Best-effort extraction of a human message from a
1104/// `catch_unwind` payload. The kernel's `enrich_eval_panic`
1105/// re-raises with a `String` payload, so the common case is one
1106/// line of context-bearing text; fall through to a sentinel for
1107/// non-string payloads (rare — third-party panic with a custom
1108/// payload type).
1109fn panic_payload_message(payload: &Box<dyn std::any::Any + Send>) -> String {
1110    if let Some(s) = payload.downcast_ref::<&str>() {
1111        (*s).to_string()
1112    } else if let Some(s) = payload.downcast_ref::<String>() {
1113        s.clone()
1114    } else {
1115        "<non-string panic payload>".to_string()
1116    }
1117}
1118
1119/// Run one of the assembler's str-to-typed coercion nodes over a string
1120/// literal at compile time, turning the node's panic diagnostic into a
1121/// compile error.
1122fn coerce_string_literal(
1123    node: Box<dyn crate::ast::PolydatNode>,
1124    s: &str,
1125) -> Result<crate::ast::Value, String> {
1126    use crate::ast::Value;
1127    // The coercion node reports a bad value by panicking with its
1128    // diagnostic. Silence the default hook so the diagnostic surfaces
1129    // once, as the compile error, rather than also on stderr.
1130    let hook = std::panic::take_hook();
1131    std::panic::set_hook(Box::new(|_| {}));
1132    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1133        let mut out = [Value::None];
1134        node.eval(&[Value::Str(s.into())], &mut out);
1135        out[0].clone()
1136    }));
1137    std::panic::set_hook(hook);
1138    result.map_err(|e| coercion_panic_message(&e))
1139}
1140
1141fn coercion_panic_message(payload: &Box<dyn std::any::Any + Send>) -> String {
1142    if let Some(s) = payload.downcast_ref::<&str>() {
1143        (*s).to_string()
1144    } else if let Some(s) = payload.downcast_ref::<String>() {
1145        s.clone()
1146    } else {
1147        "string value could not be coerced to the declared type".to_string()
1148    }
1149}
1150
1151/// Evaluate an `extern name: type = default` default expression
1152/// to a typed `Value`. Accepts literal forms only (`IntLit`,
1153/// `FloatLit`, `StringLit`, plus identifiers `true`/`false` for
1154/// `bool` ports). A string literal fuses to the declared type
1155/// through the same `StrToU64`/`StrToF64`/`StrToBool` coercions
1156/// the assembler inserts. Non-literal expressions are rejected
1157/// with a clear error; complex defaults belong in a binding, not
1158/// on the extern declaration.
1159fn evaluate_default_expr(
1160    expr: &crate::dsl::ast::Expr,
1161    port_type: crate::ast::PortType,
1162) -> Result<crate::ast::Value, String> {
1163    use crate::ast::{PortType, Value};
1164    use crate::dsl::ast::Expr;
1165    match (expr, port_type) {
1166        (Expr::IntLit(v, _), PortType::U64) => Ok(Value::U64(*v)),
1167        (Expr::IntLit(v, _), PortType::F64) => Ok(Value::F64(*v as f64)),
1168        (Expr::FloatLit(v, _), PortType::F64) => Ok(Value::F64(*v)),
1169        (Expr::StringLit(s, _), PortType::Str) => Ok(Value::Str(s.as_str().into())),
1170        (Expr::Ident(name, _), PortType::Bool) if name == "true" => Ok(Value::Bool(true)),
1171        (Expr::Ident(name, _), PortType::Bool) if name == "false" => Ok(Value::Bool(false)),
1172        // A string literal default fuses to the declared type through the
1173        // same coercions the assembler inserts when a str wire feeds a
1174        // typed port. This is what lets a host inject `name=value` text
1175        // as a program transform and leave typing to the program.
1176        (Expr::StringLit(s, _), PortType::U64) => {
1177            coerce_string_literal(Box::new(crate::library::convert::StrToU64::new()), s)
1178        }
1179        (Expr::StringLit(s, _), PortType::F64) => {
1180            coerce_string_literal(Box::new(crate::library::convert::StrToF64::new()), s)
1181        }
1182        (Expr::StringLit(s, _), PortType::Bool) => {
1183            coerce_string_literal(Box::new(crate::library::convert::StrToBool::new()), s)
1184        }
1185        // A `dyn` extern takes any value, so its default is the literal
1186        // as written, in the literal's own type.
1187        (Expr::IntLit(v, _), PortType::Dyn) => Ok(Value::U64(*v)),
1188        (Expr::FloatLit(v, _), PortType::Dyn) => Ok(Value::F64(*v)),
1189        (Expr::StringLit(s, _), PortType::Dyn) => Ok(Value::Str(s.as_str().into())),
1190        (Expr::Ident(name, _), PortType::Dyn) if name == "true" || name == "false" => {
1191            Ok(Value::Bool(name == "true"))
1192        }
1193        _ => Err(format!(
1194            "default expression must be a literal of type {port_type:?}; got {expr:?}"
1195        )),
1196    }
1197}
1198
1199/// Try to fold a `shared X := <expr>` initializer to a typed
1200/// `(Value, PortType)`. Returns `Some` for literal forms, which
1201/// become the register slot's default; returns `None` for any other
1202/// expression, which the declaring kernel's initialization evaluates
1203/// and writes through the register.
1204fn try_fold_shared_init(
1205    expr: &crate::dsl::ast::Expr,
1206) -> Option<(crate::ast::Value, crate::ast::PortType)> {
1207    use crate::ast::{PortType, Value};
1208    use crate::dsl::ast::Expr;
1209    match expr {
1210        Expr::IntLit(v, _) => Some((Value::U64(*v), PortType::U64)),
1211        Expr::FloatLit(v, _) => Some((Value::F64(*v), PortType::F64)),
1212        Expr::StringLit(s, _) => Some((Value::Str(s.as_str().into()), PortType::Str)),
1213        Expr::Ident(name, _) if name == "true" => Some((Value::Bool(true), PortType::Bool)),
1214        Expr::Ident(name, _) if name == "false" => Some((Value::Bool(false), PortType::Bool)),
1215        _ => None,
1216    }
1217}
1218
1219/// Apply the optional `shared name: type := …` annotation
1220/// (scope_model.md §"Type stability") to the folded `(value, type)`:
1221/// the annotation PINS the cell's type for life, winning over literal
1222/// inference. An integer literal widens to an f64-annotated cell (the
1223/// natural authoring, `shared m: f64 := 1`); any other mismatch is a
1224/// compile error at the declaration — not a runtime surprise.
1225fn apply_shared_type_annotation(
1226    name: &str,
1227    annotation: Option<&String>,
1228    init_value: crate::ast::Value,
1229    port_type: crate::ast::PortType,
1230) -> Result<(crate::ast::Value, crate::ast::PortType), String> {
1231    let Some(t) = annotation else {
1232        return Ok((init_value, port_type));
1233    };
1234    let annotated = crate::ast::PortType::from_keyword(t).ok_or_else(|| {
1235        format!(
1236            "shared binding '{name}': unknown type `{t}` in annotation. \
1237             Recognised types: u64, f64, str, bool."
1238        )
1239    })?;
1240    if annotated == port_type {
1241        Ok((init_value, annotated))
1242    } else if port_type == crate::ast::PortType::U64 && annotated == crate::ast::PortType::F64 {
1243        let widened = match init_value {
1244            crate::ast::Value::U64(v) => crate::ast::Value::F64(v as f64),
1245            other => other,
1246        };
1247        Ok((widened, annotated))
1248    } else {
1249        Err(format!(
1250            "shared binding '{name}: {t}': the initializer is {port_type:?}, \
1251             which doesn't match the annotated type. A cell keeps ONE type \
1252             for life — make the initializer match the annotation."
1253        ))
1254    }
1255}
1256
1257/// Extract an integer literal from a positional argument. Returns None
1258/// for named args, non-int-literal positional args, or any other form.
1259fn positional_int_lit(arg: &crate::dsl::ast::Arg) -> Option<u64> {
1260    match arg {
1261        crate::dsl::ast::Arg::Positional(crate::dsl::ast::Expr::IntLit(v, _)) => Some(*v),
1262        _ => None,
1263    }
1264}
1265
1266/// Collect the declared port type of every `input <name>: <type>`
1267/// declaration in the file (bare and tuple forms both lower to one
1268/// `InputDecl` per name). An unrecognised or absent type keyword is
1269/// omitted, leaving the assembler's `U64` default in force.
1270fn declared_input_types(
1271    file: &PolydatFile,
1272) -> std::collections::HashMap<String, crate::ast::PortType> {
1273    let mut types = std::collections::HashMap::new();
1274    for stmt in &file.statements {
1275        if let Statement::InputDecl(d) = stmt
1276            && let Some(ty) = &d.ty
1277            && let Some(pt) = crate::ast::PortType::from_keyword(ty)
1278        {
1279            types.insert(d.name.clone(), pt);
1280        }
1281    }
1282    types
1283}
1284
1285/// Extract a string literal from an optional positional argument.
1286/// Re-exported for cursor-sugar handlers in node modules that
1287/// validate string-literal-only constructor args.
1288pub fn positional_str_lit(arg: Option<&crate::dsl::ast::Arg>) -> Option<String> {
1289    match arg? {
1290        crate::dsl::ast::Arg::Positional(crate::dsl::ast::Expr::StringLit(s, _)) => Some(s.clone()),
1291        _ => None,
1292    }
1293}
1294
1295pub(super) struct Compiler {
1296    pub(super) input_names: Vec<String>,
1297    /// Track all named outputs so we can expose them.
1298    pub(super) all_names: Vec<String>,
1299    /// Auto-generated node counter for desugared intermediates.
1300    pub(super) anon_counter: usize,
1301    /// Directory for module resolution (search for .polydat files).
1302    pub(super) source_dir: Option<PathBuf>,
1303    /// Additional library directories for module resolution.
1304    ///
1305    /// Searched after `source_dir` but before the embedded stdlib.
1306    /// Populated from `CompileOptions::lib_paths` (the binary's
1307    /// `--lib`).
1308    pub(super) polydat_lib_paths: Vec<PathBuf>,
1309    /// Cache of already-resolved module ASTs: module_name → (inputs, statements).
1310    pub(super) module_cache: std::collections::HashMap<String, ResolvedModule>,
1311    /// When true, enforce strict validation.
1312    pub(super) strict: bool,
1313    /// Original source text, attached to compiled programs for diagnostics.
1314    source_text: String,
1315    /// Source schemas collected during compilation.
1316    pub(super) cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
1317    /// Deferred cursor extent resolutions: each entry maps a cursor
1318    /// schema index to the aux output names that, once folded, give
1319    /// the range's start and end values. These are resolved after the
1320    /// kernel compiles by reading `get_constant()` for each name.
1321    pub(super) deferred_extents: Vec<DeferredExtent>,
1322    /// Optional limit applied to all cursors (from `limit` activity param).
1323    pub(super) cursor_limit: Option<u64>,
1324    /// What the assembler does with inputs whose type was inferred.
1325    pub(super) input_variance: InputVariance,
1326    /// Externs whose type the caller inferred (`CompileOptions::inferred_externs`).
1327    pub(super) inferred_externs: Vec<String>,
1328    /// Diagnostic context label.
1329    context_label: String,
1330    /// Module-level pragmas extracted from the source. Drive the
1331    /// assembler's `strict_types` / `strict_values` flags
1332    /// (polydat_grammar.md §14, graph_compiler.md §2).
1333    pub(super) pragmas: super::pragmas::PragmaSet,
1334    /// LHS binding name currently being compiled, if any. Used as a
1335    /// prefix for auto-generated anonymous node names so type-mismatch
1336    /// errors point at the user-level binding (`overscan__anon_3`)
1337    /// instead of an opaque counter (`__anon_14`).
1338    pub(super) current_binding: Option<String>,
1339    /// The bindings under construction, outermost first: what every
1340    /// node factory receives as its build context's binding chain.
1341    pub(super) binding_chain: Vec<String>,
1342    /// The resource scope of the tree being compiled: the root's,
1343    /// handed to every body compiler and every node factory.
1344    pub(super) resources: crate::resource::ResourceScope,
1345    /// Tiles lowered so far in this compile, in order, so later tiles
1346    /// can splice earlier ones (polytile.md §5.5).
1347    pub(super) tiles: Vec<super::ast::TileDef>,
1348    /// Producer bindings seen so far, so tile projections over a
1349    /// producer can type their elements.
1350    pub(super) producers_seen: Vec<super::traversal::Producer>,
1351    /// Events raised while lowering, handed to the compile event log:
1352    /// one `TileHoleTyped` per hole (polytile.md §4.4), so `explain tiles`
1353    /// can show how each hole was typed and encoded, one
1354    /// `ComprehensionWarning` per degenerate composition (§5.8), and the
1355    /// steps of this compile that report themselves (a binding resolved,
1356    /// a module inlined, an output declared), merged into the log after
1357    /// the parent assembles.
1358    pub(super) pending_events: Vec<super::events::CompileEvent>,
1359    /// The compile ledger of the tree being compiled: the root's, handed
1360    /// to every body compiler and to the assembler of every program.
1361    pub(super) ledger: std::sync::Arc<crate::kernel::CompileLedger>,
1362    /// The program is a template whose inputs a binder supplies — a
1363    /// `for` body, a module image, a tile's projection body — so its
1364    /// build is not initialized: each kernel bound from it is.
1365    pub(crate) template: bool,
1366}
1367
1368/// Records a cursor whose `range(...)` bounds reference const
1369/// expressions (e.g., `vector_count("example:default")`) rather than
1370/// integer literals. The expressions are compiled as auxiliary outputs
1371/// and the extent is resolved after kernel compilation by querying the
1372/// constant values.
1373pub(super) struct DeferredExtent {
1374    /// Index into `cursor_schemas` whose extent needs resolution.
1375    pub schema_idx: usize,
1376    /// Name of the aux output that, when folded, gives the start value.
1377    pub start_output: String,
1378    /// Name of the aux output that, when folded, gives the end value.
1379    pub end_output: String,
1380}
1381
1382impl Compiler {
1383    /// The comprehension validation mode of this compile
1384    /// (comprehension_forms.md §5.8): a strict compile refuses a
1385    /// degenerate composition, a lax one warns about it.
1386    pub(super) fn validation_mode(&self) -> crate::iteration::comprehension::Mode {
1387        if self.strict {
1388            crate::iteration::comprehension::Mode::Strict
1389        } else {
1390            crate::iteration::comprehension::Mode::Permissive
1391        }
1392    }
1393
1394    /// V3 at a comprehension statement written in this compiler's scope
1395    /// (comprehension_forms.md §5): `reads` are the names its
1396    /// comprehension reads that nothing binds. Under `pragma strict` in
1397    /// this scope they are the statement's error. Outside it the
1398    /// statement compiles: the names are recorded on the tree's ledger
1399    /// ([`UnresolvedNameWarning`](crate::kernel::UnresolvedNameWarning)),
1400    /// the returned event carries them to the compile event log, and each
1401    /// reads None when the comprehension is evaluated.
1402    pub(super) fn check_statement_names(
1403        &self,
1404        statement: &str,
1405        span: super::lexer::Span,
1406        reads: Vec<crate::iteration::comprehension::NameRead>,
1407    ) -> Result<Option<super::events::CompileEvent>, String> {
1408        if reads.is_empty() {
1409            return Ok(None);
1410        }
1411        if self.pragmas.strict_names() {
1412            return Err(format!(
1413                "`{statement}` at line {}, col {}: {}",
1414                span.line,
1415                span.col,
1416                crate::iteration::comprehension::ValidationError::V3UnresolvedNames { reads }
1417            ));
1418        }
1419        let warning = crate::kernel::UnresolvedNameWarning {
1420            context: self.context_label.clone(),
1421            statement: statement.to_string(),
1422            line: span.line,
1423            col: span.col,
1424            reads,
1425        };
1426        let event = super::events::CompileEvent::Warning {
1427            message: warning.to_string(),
1428        };
1429        self.ledger.record_unresolved_names(warning);
1430        Ok(Some(event))
1431    }
1432
1433    /// A compiler with this one's settings and nothing compiled: the
1434    /// state a compile of this scope starts from.
1435    pub(super) fn fresh_like(&self) -> Compiler {
1436        let mut fresh = Compiler::with_lib_paths(
1437            self.source_dir.clone(),
1438            self.polydat_lib_paths.clone(),
1439            self.strict,
1440        );
1441        fresh.module_cache = self.module_cache.clone();
1442        fresh.source_text = self.source_text.clone();
1443        fresh.context_label = self.context_label.clone();
1444        fresh.cursor_limit = self.cursor_limit;
1445        fresh.input_variance = self.input_variance;
1446        fresh.inferred_externs = self.inferred_externs.clone();
1447        fresh.pragmas = self.pragmas.clone();
1448        fresh.resources = self.resources.clone();
1449        fresh.ledger = self.ledger.clone();
1450        fresh.template = self.template;
1451        fresh
1452    }
1453
1454    /// The scope a context-free source evaluates in during this
1455    /// compile (comprehension_forms.md §10.7.0): no name resolves, and
1456    /// what has to compile is charged to the program tree's ledger.
1457    pub(super) fn source_scope(&self) -> crate::kernel::interp::NoScope {
1458        crate::kernel::interp::NoScope::charged_to(self.ledger.clone())
1459    }
1460
1461    /// The build context a node factory receives at this point of the
1462    /// compile: the bindings under construction and the tree's
1463    /// resource scope.
1464    pub(super) fn build_context(&self) -> super::factory::BuildContext {
1465        super::factory::BuildContext::new(self.binding_chain.clone(), self.resources.clone())
1466    }
1467
1468    pub(super) fn with_lib_paths(
1469        source_dir: Option<PathBuf>,
1470        polydat_lib_paths: Vec<PathBuf>,
1471        strict: bool,
1472    ) -> Self {
1473        Self {
1474            input_names: Vec::new(),
1475            all_names: Vec::new(),
1476            anon_counter: 0,
1477            source_dir,
1478            polydat_lib_paths,
1479            module_cache: std::collections::HashMap::new(),
1480            strict,
1481            source_text: String::new(),
1482            context_label: "(polydat)".into(),
1483            cursor_schemas: Vec::new(),
1484            deferred_extents: Vec::new(),
1485            cursor_limit: None,
1486            input_variance: InputVariance::Fixed,
1487            inferred_externs: Vec::new(),
1488            pragmas: super::pragmas::PragmaSet::default(),
1489            current_binding: None,
1490            binding_chain: Vec::new(),
1491            resources: crate::resource::ResourceScope::new(),
1492            tiles: Vec::new(),
1493            producers_seen: Vec::new(),
1494            pending_events: Vec::new(),
1495            ledger: crate::kernel::CompileLedger::new(),
1496            template: false,
1497        }
1498    }
1499
1500    /// Process a source declaration: create input ports for projections,
1501    /// passthrough nodes, and record the schema.
1502    fn process_cursor(
1503        &mut self,
1504        asm: &mut PolydatAssembler,
1505        decl: &crate::dsl::ast::CursorDecl,
1506    ) -> Result<(), String> {
1507        let source_name = &decl.name;
1508
1509        // Cursor-sugar dispatch: any node module can register a
1510        // handler that recognizes a non-`range` constructor (e.g.
1511        // `vectordata_base("ds", "label_00")`) and rewrites it into
1512        // a synthetic `range(...)` plus a list of aux bindings to
1513        // emit after input ports are wired. The core stays
1514        // generic — nothing here knows that vectordata exists.
1515        // See `dsl::cursor_sugar` for the registry mechanism.
1516        let sugar = crate::dsl::cursor_sugar::dispatch(source_name, &decl.constructor)?;
1517        let effective_constructor = match &sugar {
1518            Some(s) => s.effective_constructor.clone(),
1519            None => decl.constructor.clone(),
1520        };
1521
1522        // All sources get an "ordinal" projection.
1523        let mut projections = vec![("ordinal".to_string(), crate::ast::PortType::U64)];
1524
1525        // Determine extent from constructor args. Three cases per arg:
1526        //   1. Integer literal → use directly
1527        //   2. Other const-foldable expression (e.g. `vector_count("...")`)
1528        //      → compile as an aux output and resolve after kernel compiles
1529        //   3. Arg references runtime state → no extent available
1530        //
1531        // Immediate-literal cases produce a concrete extent here.
1532        // Deferred cases push a DeferredExtent record; the outer compile
1533        // routine reads the folded values after compilation and updates
1534        // the schema's extent in place.
1535        let mut deferred: Option<(Option<u64>, String, Option<u64>, String)> = None;
1536        let mut cursor_kind_for_decl: crate::iteration::source::CursorKind =
1537            crate::iteration::source::CursorKind::Range;
1538        let extent = match &effective_constructor {
1539            // ── until_*(...) — extending cursors ────────────────
1540            // Recognise every cursor function whose constructor
1541            // declares an extending policy. The shape of each is:
1542            //   until_FAMILY(base, ...policy_args[, delta])
1543            // where `base` is the initial extent / pass size and
1544            // policy_args carry the family's stop-condition
1545            // parameters. An optional final `delta` overrides the
1546            // extension step size (defaults to `base`).
1547            //
1548            // Recognised families:
1549            //   until_elapsed(base, min_ms[, delta])
1550            //   until_passes(base, min_passes[, delta])
1551            //   until_count(base, min_count[, delta])
1552            //   until_elapsed_and_passes(base, min_ms, min_passes[, delta])
1553            //   until_elapsed_or_passes(base, min_ms, min_passes[, delta])
1554            //
1555            // Common shape: emit `base` as the cursor's `end` aux
1556            // output, `start` as a literal 0, and each policy arg
1557            // as a named aux output the runtime pulls at phase
1558            // setup. The CursorKind variant carries the output
1559            // names so the executor knows how to build the policy.
1560            crate::dsl::ast::Expr::Call(call)
1561                if matches!(
1562                    call.func.as_str(),
1563                    "until_elapsed"
1564                        | "until_passes"
1565                        | "until_count"
1566                        | "until_elapsed_and_passes"
1567                        | "until_elapsed_or_passes"
1568                ) =>
1569            {
1570                let family = call.func.as_str();
1571                let expected = match family {
1572                    "until_elapsed" | "until_passes" | "until_count" => (2usize, 3usize),
1573                    "until_elapsed_and_passes" | "until_elapsed_or_passes" => (3, 4),
1574                    _ => unreachable!(),
1575                };
1576                let n = call.args.len();
1577                if n < expected.0 || n > expected.1 {
1578                    return Err(format!(
1579                        "cursor '{source_name}': `{family}` takes {}-{} args, got {n}",
1580                        expected.0, expected.1,
1581                    ));
1582                }
1583                // Common: base, start, end aux outputs.
1584                let base_literal = positional_int_lit(&call.args[0]);
1585                let base_name = format!("__cursor_extent_{source_name}_end");
1586                let start_name = format!("__cursor_extent_{source_name}_start");
1587                let _ = self.compile_binding(
1588                    asm,
1589                    std::slice::from_ref(&start_name),
1590                    &crate::dsl::ast::Expr::IntLit(0, decl.span),
1591                );
1592                if let crate::dsl::ast::Arg::Positional(expr) = &call.args[0] {
1593                    self.compile_binding(asm, std::slice::from_ref(&base_name), expr)
1594                        .map_err(|e| {
1595                            format!("cursor '{source_name}': failed to compile {family} base: {e}")
1596                        })?;
1597                }
1598                // Helper closure: compile a positional arg as a
1599                // named aux output. Returns the name on success.
1600                let mut compile_aux = |idx: usize, suffix: &str| -> Result<String, String> {
1601                    let out_name = format!("__cursor_{suffix}_{source_name}");
1602                    if let crate::dsl::ast::Arg::Positional(expr) = &call.args[idx] {
1603                        self.compile_binding(asm, std::slice::from_ref(&out_name), expr)
1604                            .map_err(|e| {
1605                                format!(
1606                                    "cursor '{source_name}': failed to compile \
1607                                 {family} arg {idx}: {e}"
1608                                )
1609                            })?;
1610                    }
1611                    Ok(out_name)
1612                };
1613                // Family-specific arg layout.
1614                cursor_kind_for_decl = match family {
1615                    "until_elapsed" => {
1616                        let min_ms_name = compile_aux(1, "min_ms")?;
1617                        let delta_output = if n == 3 {
1618                            Some(compile_aux(2, "delta")?)
1619                        } else {
1620                            None
1621                        };
1622                        crate::iteration::source::CursorKind::ExtendingTimed {
1623                            min_ms_output: min_ms_name,
1624                            delta_output,
1625                        }
1626                    }
1627                    "until_passes" => {
1628                        let min_passes_name = compile_aux(1, "min_passes")?;
1629                        let delta_output = if n == 3 {
1630                            Some(compile_aux(2, "delta")?)
1631                        } else {
1632                            None
1633                        };
1634                        crate::iteration::source::CursorKind::ExtendingPasses {
1635                            min_passes_output: min_passes_name,
1636                            delta_output,
1637                        }
1638                    }
1639                    "until_count" => {
1640                        let min_count_name = compile_aux(1, "min_count")?;
1641                        let delta_output = if n == 3 {
1642                            Some(compile_aux(2, "delta")?)
1643                        } else {
1644                            None
1645                        };
1646                        crate::iteration::source::CursorKind::ExtendingCount {
1647                            min_count_output: min_count_name,
1648                            delta_output,
1649                        }
1650                    }
1651                    "until_elapsed_and_passes" => {
1652                        let min_ms_name = compile_aux(1, "min_ms")?;
1653                        let min_passes_name = compile_aux(2, "min_passes")?;
1654                        let delta_output = if n == 4 {
1655                            Some(compile_aux(3, "delta")?)
1656                        } else {
1657                            None
1658                        };
1659                        crate::iteration::source::CursorKind::ExtendingElapsedAndPasses {
1660                            min_ms_output: min_ms_name,
1661                            min_passes_output: min_passes_name,
1662                            delta_output,
1663                        }
1664                    }
1665                    "until_elapsed_or_passes" => {
1666                        let min_ms_name = compile_aux(1, "min_ms")?;
1667                        let min_passes_name = compile_aux(2, "min_passes")?;
1668                        let delta_output = if n == 4 {
1669                            Some(compile_aux(3, "delta")?)
1670                        } else {
1671                            None
1672                        };
1673                        crate::iteration::source::CursorKind::ExtendingElapsedOrPasses {
1674                            min_ms_output: min_ms_name,
1675                            min_passes_output: min_passes_name,
1676                            delta_output,
1677                        }
1678                    }
1679                    _ => unreachable!(),
1680                };
1681                deferred = Some((Some(0), start_name, base_literal, base_name));
1682                base_literal
1683            }
1684            crate::dsl::ast::Expr::Call(call) if call.func == "range" && call.args.len() >= 2 => {
1685                let start_literal = positional_int_lit(&call.args[0]);
1686                let end_literal = positional_int_lit(&call.args[1]);
1687
1688                match (start_literal, end_literal) {
1689                    // Both literal — compute directly. We also emit
1690                    // the start/end as named final bindings so the
1691                    // comprehension `all(<cursor>)` form (expression_engine.md §3.3)
1692                    // can resolve them uniformly with the deferred
1693                    // (non-literal) case below.
1694                    (Some(s), Some(e)) => {
1695                        let start_name = format!("__cursor_extent_{source_name}_start");
1696                        let end_name = format!("__cursor_extent_{source_name}_end");
1697                        let s_lit = crate::dsl::ast::Expr::IntLit(s, decl.span);
1698                        let e_lit = crate::dsl::ast::Expr::IntLit(e, decl.span);
1699                        let _ = self.compile_binding(asm, &[start_name], &s_lit);
1700                        let _ = self.compile_binding(asm, &[end_name], &e_lit);
1701                        Some(e.saturating_sub(s))
1702                    }
1703                    // At least one non-literal — compile as aux outputs.
1704                    _ => {
1705                        let start_name = format!("__cursor_extent_{source_name}_start");
1706                        let end_name = format!("__cursor_extent_{source_name}_end");
1707                        // Compile each arg as a named auxiliary output. Errors
1708                        // are returned so the user sees them — silently
1709                        // dropping them would leave extent=None and produce
1710                        // a phase that runs zero cycles with no explanation.
1711                        if let crate::dsl::ast::Arg::Positional(expr) = &call.args[0] {
1712                            self.compile_binding(asm, std::slice::from_ref(&start_name), expr)
1713                                .map_err(|e| {
1714                                    format!(
1715                                        "cursor '{source_name}': failed to compile range start: {e}"
1716                                    )
1717                                })?;
1718                        }
1719                        if let crate::dsl::ast::Arg::Positional(expr) = &call.args[1] {
1720                            self.compile_binding(asm, std::slice::from_ref(&end_name), expr)
1721                                .map_err(|e| {
1722                                    format!(
1723                                        "cursor '{source_name}': failed to compile range end: {e}"
1724                                    )
1725                                })?;
1726                        }
1727                        deferred = Some((start_literal, start_name, end_literal, end_name));
1728                        None
1729                    }
1730                }
1731            }
1732            _ => None,
1733        };
1734
1735        // Create input ports and passthrough nodes for each projection.
1736        for (field_name, port_type) in &projections {
1737            let input_name = format!("{source_name}__{field_name}");
1738            let default_value = match port_type {
1739                crate::ast::PortType::U64 => crate::ast::Value::U64(0),
1740                crate::ast::PortType::F64 => crate::ast::Value::F64(0.0),
1741                _ => crate::ast::Value::None,
1742            };
1743
1744            // Cursor projection slots are written by cursor advance
1745            // every cycle — dynamic for init-contract purposes.
1746            asm.add_input(
1747                &input_name,
1748                default_value,
1749                *port_type,
1750                crate::kernel::InputKind::ExternalWrite,
1751            );
1752            self.input_names.push(input_name.clone());
1753
1754            let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
1755                &input_name,
1756                *port_type,
1757            ));
1758            let node_name = format!("{source_name}__{field_name}");
1759            asm.add_node(&node_name, passthrough, vec![WireRef::input(&input_name)]);
1760            asm.add_output(&node_name, WireRef::node(&node_name));
1761        }
1762
1763        // Apply any aux bindings the sugar handler asked for.
1764        // Bindings whose `projection` is `Some` are also published
1765        // as cursor projections — both pinned on the schema and
1766        // exposed as kernel outputs the runtime can read.
1767        if let Some(sugar) = sugar {
1768            for aux in sugar.aux_bindings {
1769                self.compile_binding(asm, std::slice::from_ref(&aux.name), &aux.value)
1770                    .map_err(|e| {
1771                        format!(
1772                            "cursor '{source_name}': failed to compile aux binding '{}': {e}",
1773                            aux.name,
1774                        )
1775                    })?;
1776                if let Some((field, port_type)) = aux.projection {
1777                    projections.push((field, port_type));
1778                    asm.add_output(&aux.name, WireRef::node(&aux.name));
1779                }
1780            }
1781        }
1782
1783        // If a limit is set, insert a limit() node that shadows the cursor wire.
1784        // The limit node is a visible, documented passthrough that clamps extent.
1785        let effective_extent = if let Some(limit_val) = self.cursor_limit {
1786            let limit_node_name = format!("{source_name}__limit");
1787            let ordinal_wire = format!("{source_name}__ordinal");
1788            asm.add_node(
1789                &limit_node_name,
1790                Box::new(crate::library::context::Limit::new(limit_val)),
1791                vec![WireRef::node(&ordinal_wire)],
1792            );
1793            // Shadow the ordinal output with the limited version
1794            asm.add_output(&ordinal_wire, WireRef::node(&limit_node_name));
1795
1796            // Clamp extent
1797            extent.map(|e| e.min(limit_val)).or(Some(limit_val))
1798        } else {
1799            extent
1800        };
1801
1802        let schema_idx = self.cursor_schemas.len();
1803        let extent_outputs = deferred
1804            .as_ref()
1805            .map(|(_, start, _, end)| (start.clone(), end.clone()));
1806
1807        // If the cursor decl carries an `over <expr>` clause
1808        // (cursor_partitions.md §7.2), set up two pieces of plumbing:
1809        //
1810        // 1. An auxiliary output `<source>__over_raw` carrying
1811        //    the raw expression value (typically a string spec
1812        //    or a workload-param-typed value). The executor
1813        //    pulls this at phase setup to determine the
1814        //    narrowing range.
1815        //
1816        // 2. An input slot + passthrough output `<source>__cursor`
1817        //    of type `Ext` — this is the field-access wire that
1818        //    workload authors reference as `<source>.cursor`. At
1819        //    phase setup the executor resolves the raw value to
1820        //    a concrete `Partition` and writes it into this slot,
1821        //    so downstream nodes (`mod_in`, `cardinality`, etc.)
1822        //    can consume it as a `Partition`-typed wire.
1823        let mut partitions: Option<Vec<crate::iteration::cursor_partition::Partition>> = None;
1824        let partition_output = if let Some(over_expr) = decl.over.as_ref() {
1825            let raw_name = format!("__cursor_{source_name}_over_raw");
1826            self.compile_binding(asm, std::slice::from_ref(&raw_name), over_expr)
1827                .map_err(|e| {
1828                    format!("cursor '{source_name}': failed to compile `over` expression: {e}")
1829                })?;
1830            // The wire is a spec string or a partition-typed external
1831            // (for_traversal.md §5, §7): any other type is refused here,
1832            // not at the first activation.
1833            if let Some(ty) = asm.output_type(&raw_name)
1834                && !matches!(ty, crate::ast::PortType::Str | crate::ast::PortType::Ext)
1835            {
1836                return Err(format!(
1837                    "cursor '{source_name}': `over` names a {ty:?} wire; expected a spec string or a partition-typed value"
1838                ));
1839            }
1840            // A literal spec over a known extent resolves now
1841            // (engines.md §3.5): the schema carries the
1842            // partitions for the host, and a clause that denotes
1843            // exactly one partition seeds the cursor's slots, so the
1844            // program runs on every engine with no host call. A clause
1845            // that denotes several leaves the choice to the host or
1846            // the traversal runtime.
1847            if let (crate::dsl::ast::Expr::StringLit(spec, _), Some(extent)) =
1848                (over_expr, effective_extent)
1849            {
1850                let open = !matches!(
1851                    cursor_kind_for_decl,
1852                    crate::iteration::source::CursorKind::Range
1853                );
1854                let parts = crate::iteration::cursor_partition::resolve_over(
1855                    &crate::ast::Value::Str(spec.as_str().into()),
1856                    extent,
1857                    open,
1858                )
1859                .map_err(|e| format!("cursor '{source_name}': `over \"{spec}\"`: {e}"))?;
1860                partitions = Some(parts);
1861            }
1862            let seeded: Option<crate::iteration::cursor_partition::Partition> =
1863                partitions.as_ref().filter(|p| p.len() == 1).map(|p| p[0]);
1864            // Allocate the resolved-Partition input slot. Its default
1865            // is the one partition the clause denotes, or `Value::None`
1866            // until the host or the traversal runtime narrows it.
1867            let cursor_input_name = format!("{source_name}__cursor");
1868            asm.add_input(
1869                &cursor_input_name,
1870                seeded.map_or(crate::ast::Value::None, crate::ast::Value::from_partition),
1871                crate::ast::PortType::Ext,
1872                crate::kernel::InputKind::ExternalWrite,
1873            );
1874            self.input_names.push(cursor_input_name.clone());
1875            let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
1876                &cursor_input_name,
1877                crate::ast::PortType::Ext,
1878            ));
1879            asm.add_node(
1880                &cursor_input_name,
1881                passthrough,
1882                vec![WireRef::input(&cursor_input_name)],
1883            );
1884            asm.add_output(&cursor_input_name, WireRef::node(&cursor_input_name));
1885            // Cursor metadata wires (cursor_partitions.md §7.2): scalar projections
1886            // of the resolved partition, as plain typed slots —
1887            // `<source>.cursor.idx` and friends parse as chained
1888            // field access and flatten onto these wires. The
1889            // executor writes them alongside the Ext slot at
1890            // phase setup; defaults here cover the no-narrowing
1891            // case (idx 0, count 1, full-extent pcts; the
1892            // ordinal pair is patched by the executor once the
1893            // cursor's extent is known).
1894            use crate::ast::{PortType, Value};
1895            let scalar_slots: [(&str, Value, PortType); 6] = match seeded {
1896                Some(p) => [
1897                    ("idx", Value::U64(p.idx), PortType::U64),
1898                    ("partition_count", Value::U64(p.count.max(1)), PortType::U64),
1899                    ("start_pct", Value::F64(p.start_pct), PortType::F64),
1900                    ("end_pct", Value::F64(p.end_pct), PortType::F64),
1901                    ("start_ordinal", Value::U64(p.start_ord), PortType::U64),
1902                    ("end_ordinal", Value::U64(p.end_ord), PortType::U64),
1903                ],
1904                None => [
1905                    ("idx", Value::U64(0), PortType::U64),
1906                    ("partition_count", Value::U64(1), PortType::U64),
1907                    ("start_pct", Value::F64(0.0), PortType::F64),
1908                    ("end_pct", Value::F64(100.0), PortType::F64),
1909                    ("start_ordinal", Value::U64(0), PortType::U64),
1910                    ("end_ordinal", Value::U64(0), PortType::U64),
1911                ],
1912            };
1913            for (field, default, port_type) in scalar_slots {
1914                let slot = format!("{cursor_input_name}__{field}");
1915                asm.add_input(
1916                    &slot,
1917                    default,
1918                    port_type,
1919                    crate::kernel::InputKind::ExternalWrite,
1920                );
1921                self.input_names.push(slot.clone());
1922                let pass = Box::new(crate::library::identity::PortPassthrough::new(
1923                    &slot, port_type,
1924                ));
1925                asm.add_node(&slot, pass, vec![WireRef::input(&slot)]);
1926                asm.add_output(&slot, WireRef::node(&slot));
1927            }
1928            Some(raw_name)
1929        } else {
1930            None
1931        };
1932
1933        self.cursor_schemas
1934            .push(crate::iteration::source::SourceSchema {
1935                name: source_name.clone(),
1936                projections,
1937                extent: effective_extent,
1938                extent_outputs,
1939                extent_limit: self.cursor_limit,
1940                cursor_kind: cursor_kind_for_decl.clone(),
1941                partition_output,
1942                partitions,
1943            });
1944
1945        // Record deferred extent resolution if the range bounds are not
1946        // both literals. Post-compile, the outer compile routine will
1947        // query the aux outputs' folded constants and update this
1948        // schema's extent in place.
1949        if let Some((_start_lit, start_output, _end_lit, end_output)) = deferred {
1950            self.deferred_extents.push(DeferredExtent {
1951                schema_idx,
1952                start_output,
1953                end_output,
1954            });
1955        }
1956        Ok(())
1957    }
1958
1959    /// The interpreter's kernel of `file` as its concrete type: the one
1960    /// compile path with the interpreter's build, keeping the outputs in
1961    /// `filter` (every output when `None`) and recording events in `log`.
1962    /// The parent's AST is retained as program metadata for the subscope
1963    /// synthesizer.
1964    pub(super) fn compile_interpreter(
1965        &mut self,
1966        file: &PolydatFile,
1967        filter: Option<&[String]>,
1968        log: Option<&mut super::events::CompileEventLog>,
1969        cones: crate::JitMode,
1970    ) -> Result<PolydatKernel, crate::KernelError> {
1971        let (mut kernel, parent) = compile_file_with(self, file, filter, log, |mut asm, log| {
1972            asm.set_jit_mode(cones);
1973            asm.compile_with_log(log).map_err(crate::KernelError::from)
1974        })?;
1975        kernel.set_ast(std::sync::Arc::new(parent));
1976        Ok(kernel)
1977    }
1978
1979    /// The output type of a generator expression used as a comprehension
1980    /// source (for_traversal.md §3.3): compile `__probe := <expr>` on its own and
1981    /// read the port type. Shared by `for` bodies and tile projections.
1982    pub(super) fn probe_element_type(&self, expr: &str) -> Result<crate::ast::PortType, String> {
1983        let src = format!("input cycle: u64\n__probe := {expr}\n");
1984        let tokens = lexer::lex(&src)?;
1985        let ast = parser::parse(tokens)?;
1986        let mut probe_compiler = Compiler::with_lib_paths(
1987            self.source_dir.clone(),
1988            self.polydat_lib_paths.clone(),
1989            false,
1990        );
1991        probe_compiler.source_text = src.clone();
1992        probe_compiler.context_label = format!("{} (element probe)", self.context_label);
1993        probe_compiler.resources = self.resources.clone();
1994        probe_compiler.module_cache = self.module_cache.clone();
1995        // Assembly answers this: the assembler knows an output's
1996        // declared port type as soon as the node is registered, so the
1997        // probe builds no kernel.
1998        let asm = probe_compiler.assemble_parent(&ast, None)?;
1999        asm.output_type("__probe")
2000            .ok_or_else(|| "probe produced no output".to_string())
2001    }
2002
2003    /// Lower each `for` statement's body to a child program, typed from
2004    /// its comprehension and the parent's manifest (for_traversal.md §3.3, §4).
2005    fn compile_traversals(
2006        &mut self,
2007        for_stmts: &[super::ast::ForStmt],
2008        producers: &[super::traversal::Producer],
2009        type_of: &dyn Fn(&str) -> Option<crate::ast::PortType>,
2010    ) -> Result<Vec<super::traversal::Traversal>, String> {
2011        use super::traversal::{
2012            Traversal, child_file, element_types, resolve_source_with, warning_events,
2013        };
2014        let mut out = Vec::with_capacity(for_stmts.len());
2015        for f in for_stmts {
2016            let (comprehension, warnings) = resolve_source_with(
2017                &f.source,
2018                producers,
2019                self.validation_mode(),
2020                &self.source_scope(),
2021            )?;
2022            self.pending_events
2023                .extend(warning_events(&f.source, &warnings));
2024            // V3 (comprehension_forms.md §5): the traversal supplies the
2025            // names of the scope it opens in, this program's.
2026            let reads = crate::iteration::comprehension::unresolved_names(
2027                &comprehension,
2028                crate::iteration::comprehension::Surface::Traversal(&|n| type_of(n).is_some()),
2029            );
2030            let warnings =
2031                self.check_statement_names(&format!("for {}", f.source.to_text()), f.span, reads)?;
2032            self.pending_events.extend(warnings);
2033            let mut probe = |expr: &str| self.probe_element_type(expr);
2034            let elements = element_types(&comprehension, &mut probe).map_err(|e| {
2035                format!(
2036                    "`for {}` at line {}, col {}: {e}",
2037                    f.source.to_text(),
2038                    f.span.line,
2039                    f.span.col
2040                )
2041            })?;
2042            let (child, cascade) = child_file(f, &comprehension, &elements, type_of)?;
2043            let mut child_compiler = Compiler::with_lib_paths(
2044                self.source_dir.clone(),
2045                self.polydat_lib_paths.clone(),
2046                self.strict,
2047            );
2048            // The body sees every module the parent resolved, its own
2049            // definitions included, wherever it compiles.
2050            child_compiler.module_cache = self.module_cache.clone();
2051            // The body's program is one of the tree's.
2052            child_compiler.ledger = self.ledger.clone();
2053            child_compiler.resources = self.resources.clone();
2054            child_compiler.source_text = super::pprint::pp_file(&child);
2055            child_compiler.context_label = format!(
2056                "{} :: for {} (line {}, col {})",
2057                self.context_label,
2058                f.source.to_text(),
2059                f.span.line,
2060                f.span.col
2061            );
2062            child_compiler.cursor_limit = self.cursor_limit;
2063            // The body is a pragma scope (polydat_grammar.md §14): it
2064            // compiles under this program's set plus its own pragmas.
2065            child_compiler.pragmas = self.pragmas.nested(&f.body);
2066            for pragma in super::pragmas::declared_in(&f.body) {
2067                self.pending_events.push(pragma_event(&pragma));
2068            }
2069            let child_kernel = child_compiler
2070                .compile_interpreter(&child, None, None, crate::JitMode::Auto)
2071                .map_err(|e| {
2072                    format!(
2073                        "`for {}` at line {}, col {}: body failed to compile: {e}",
2074                        f.source.to_text(),
2075                        f.span.line,
2076                        f.span.col
2077                    )
2078                })?;
2079            self.pending_events
2080                .append(&mut child_compiler.pending_events);
2081            let body = super::traversal::BodySource {
2082                file: child,
2083                source_text: child_compiler.source_text.clone(),
2084                source_dir: self.source_dir.clone(),
2085                lib_paths: self.polydat_lib_paths.clone(),
2086                strict: self.strict,
2087                context_label: child_compiler.context_label.clone(),
2088                cursor_limit: self.cursor_limit,
2089                pragmas: child_compiler.pragmas.clone(),
2090                modules: self.module_cache.clone(),
2091                programs: std::sync::Mutex::new(std::collections::HashMap::new()),
2092                ledger: self.ledger.clone(),
2093                resources: self.resources.clone(),
2094            };
2095            out.push(Traversal {
2096                span: f.span,
2097                source_text: f.source.to_text(),
2098                comprehension,
2099                elements,
2100                cascade,
2101                program: child_kernel.into_program(),
2102                body: std::sync::Arc::new(body),
2103            });
2104        }
2105        Ok(out)
2106    }
2107
2108    /// A body of this program's, from its lowered source: the
2109    /// settings this compiler carries, so the body compiles the way
2110    /// the program around it does — its source directory and library
2111    /// paths, its strict flag, its pragmas, the modules it has
2112    /// resolved, and the tree's compile ledger.
2113    ///
2114    /// A `for` body gets these because `compile_traversals` builds its
2115    /// `BodySource` in this compiler, and a tile's projection body gets
2116    /// them through this function.
2117    pub(super) fn body_source_for(
2118        &self,
2119        source: &str,
2120        context_label: &str,
2121    ) -> Result<super::traversal::BodySource, String> {
2122        let file = super::lexer::lex(source).and_then(super::parser::parse)?;
2123        let pragmas = self.pragmas.nested(&file.statements);
2124        Ok(super::traversal::BodySource::from_parts(
2125            file,
2126            source.to_string(),
2127            self.source_dir.clone(),
2128            self.polydat_lib_paths.clone(),
2129            self.strict,
2130            format!("{} :: {context_label}", self.context_label),
2131            self.cursor_limit,
2132            pragmas,
2133            self.module_cache.clone(),
2134            self.ledger.clone(),
2135            self.resources.clone(),
2136        ))
2137    }
2138
2139    /// Compile a traversal body on `engine` (engines.md §3.6): the same child file and
2140    /// compiler settings the parent used for the interpreter's program,
2141    /// through the assembler, its own `for` statements and producers
2142    /// included.
2143    pub(super) fn compile_body_on(
2144        body: &super::traversal::BodySource,
2145        engine: crate::Engine,
2146    ) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2147        let _data_base = body.source_dir.as_deref().map(DataBaseDirGuard::set);
2148        let mut compiler =
2149            Compiler::with_lib_paths(body.source_dir.clone(), body.lib_paths.clone(), body.strict);
2150        compiler.source_text = body.source_text.clone();
2151        compiler.context_label = body.context_label.clone();
2152        compiler.cursor_limit = body.cursor_limit;
2153        compiler.pragmas = body.pragmas.clone();
2154        compiler.module_cache = body.modules.clone();
2155        compiler.ledger = body.ledger.clone();
2156        compiler.resources = body.resources.clone();
2157        compiler.template = true;
2158        compile_file_on_engine(&mut compiler, &body.file, None, engine, None)
2159    }
2160
2161    /// Assemble the parent program: inputs and their passthroughs,
2162    /// externs, bindings, cursors, tiles, and the output set. Every
2163    /// entry point builds its assembler here, so a kernel and an
2164    /// assembler from the same source are the same graph.
2165    fn assemble_parent(
2166        &mut self,
2167        file: &PolydatFile,
2168        required_outputs: Option<&[String]>,
2169    ) -> Result<PolydatAssembler, String> {
2170        self.register_local_modules(file);
2171        // First pass: collect explicit `input` declarations, dedup by name.
2172        for stmt in &file.statements {
2173            if let Statement::InputDecl(d) = stmt
2174                && !self.input_names.iter().any(|n| n == &d.name)
2175            {
2176                self.input_names.push(d.name.clone());
2177            }
2178        }
2179
2180        // Input declaration check: error in strict mode (modules, .polydat files)
2181        if self.input_names.is_empty() && self.strict {
2182            return Err(
2183                "strict mode: no `input` declaration — add `input <name>: <type>` \
2184                 (or the tuple form `input (a: u64, b: f64)`) to declare graph \
2185                 inputs explicitly"
2186                    .into(),
2187            );
2188        }
2189
2190        // If no explicit inputs, infer from unbound references
2191        if self.input_names.is_empty() {
2192            let defined: HashSet<String> = file
2193                .statements
2194                .iter()
2195                .flat_map(|stmt| match stmt {
2196                    Statement::Binding(b) => b.targets.clone(),
2197                    Statement::ModuleDef(m) => vec![m.name.clone()],
2198                    Statement::ExternPort(p) => vec![p.name.clone()],
2199                    Statement::InputDecl(_) => vec![],
2200                    Statement::Cursor(_) => vec![],
2201                    Statement::Pragma { .. } => vec![],
2202                    Statement::For(_) => vec![],
2203                    Statement::Tile(t) => vec![t.name.clone()],
2204                })
2205                .collect();
2206
2207            let mut referenced: HashSet<String> = HashSet::new();
2208            for stmt in &file.statements {
2209                let expr = match stmt {
2210                    Statement::InputDecl(_)
2211                    | Statement::ModuleDef(_)
2212                    | Statement::ExternPort(_)
2213                    | Statement::Cursor(_)
2214                    | Statement::Pragma { .. }
2215                    | Statement::For(_)
2216                    | Statement::Tile(_) => continue,
2217                    Statement::Binding(b) => &b.value,
2218                };
2219                collect_references(expr, &mut referenced);
2220            }
2221
2222            let mut inferred: Vec<String> = referenced
2223                .into_iter()
2224                .filter(|name| !defined.contains(name))
2225                .collect();
2226            inferred.sort();
2227            self.input_names = inferred;
2228        }
2229
2230        // Zero inferred inputs means all bindings are constants — valid.
2231
2232        let mut asm = PolydatAssembler::new(self.input_names.clone());
2233        asm.ledger = self.ledger.clone();
2234        asm.resources = self.resources.clone();
2235        asm.template = self.template;
2236        for (name, ty) in declared_input_types(file) {
2237            asm.set_input_type(&name, ty);
2238        }
2239
2240        // Auto-expose every declared input as a passthrough output
2241        // (parity with `extern`). See `compile()` for the same wiring.
2242        for input_name in self.input_names.clone() {
2243            // Mirror the input's (now correctly-typed) slot so the
2244            // auto-exposed output carries the declared type, not U64.
2245            let port_type = asm
2246                .input_type(&input_name)
2247                .unwrap_or(crate::ast::PortType::U64);
2248            let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
2249                &input_name,
2250                port_type,
2251            ));
2252            let passthrough_name = format!("__port_{input_name}");
2253            asm.add_node(
2254                &passthrough_name,
2255                passthrough,
2256                vec![WireRef::input(&input_name)],
2257            );
2258            asm.add_output(&input_name, WireRef::node(&passthrough_name));
2259        }
2260
2261        // Second pass: process all bindings into the assembler
2262        for stmt in &file.statements {
2263            match stmt {
2264                Statement::InputDecl(_) => {}
2265                Statement::Binding(b) => {
2266                    // `shared X := <expr>` compiles to an input slot +
2267                    // passthrough output, so the binder can wire a
2268                    // `SharedCell` for cross-scope mutability
2269                    // (scope_model.md §6). A literal
2270                    // is the slot's default; any other expression
2271                    // compiles as the output `__init_X`, which the
2272                    // declaring kernel's initialization evaluates once
2273                    // and writes through the register. Tuple-target
2274                    // shared bindings are rejected: a register holds
2275                    // one value.
2276                    if b.modifier == BindingModifier::SHARED {
2277                        if b.targets.len() != 1 {
2278                            return Err(format!(
2279                                "shared binding must be single-target, not tuple unpack \
2280                                 ({}). Declare each target separately if a shared cell \
2281                                 is intended.",
2282                                b.targets.join(", "),
2283                            ));
2284                        }
2285                        let name = &b.targets[0];
2286                        let (init_value, port_type) = match try_fold_shared_init(&b.value) {
2287                            Some((init_value, port_type)) => apply_shared_type_annotation(
2288                                name,
2289                                b.type_annotation.as_ref(),
2290                                init_value,
2291                                port_type,
2292                            )?,
2293                            None => {
2294                                let source = format!("__init_{name}");
2295                                self.compile_binding(
2296                                    &mut asm,
2297                                    std::slice::from_ref(&source),
2298                                    &b.value,
2299                                )?;
2300                                let Some(computed) = asm.output_type(&source) else {
2301                                    return Err(format!(
2302                                        "internal error: the starting value of shared '{name}' \
2303                                         was just compiled, so the assembler should carry its \
2304                                         type"
2305                                    ));
2306                                };
2307                                let port_type = match b.type_annotation.as_ref() {
2308                                    None => computed,
2309                                    Some(t) => {
2310                                        let annotated = crate::ast::PortType::from_keyword(t)
2311                                            .ok_or_else(|| {
2312                                                format!(
2313                                                    "shared binding '{name}': unknown type \
2314                                                     `{t}` in annotation"
2315                                                )
2316                                            })?;
2317                                        if annotated != computed {
2318                                            return Err(format!(
2319                                                "shared binding '{name}: {t}': the starting \
2320                                                 value is {computed:?}, which doesn't match the \
2321                                                 annotated type. A cell keeps ONE type for \
2322                                                 life — convert the starting value to {t}."
2323                                            ));
2324                                        }
2325                                        annotated
2326                                    }
2327                                };
2328                                asm.add_output(&source, WireRef::node(&source));
2329                                // One reading, at initialization, as a
2330                                // const takes it.
2331                                asm.set_output_modifier(&source, BindingModifier::CONST);
2332                                asm.mark_shared_start(name, &source);
2333                                (crate::ast::Value::None, port_type)
2334                            }
2335                        };
2336                        asm.add_input(
2337                            name,
2338                            init_value,
2339                            port_type,
2340                            crate::kernel::InputKind::ExternalWrite,
2341                        );
2342                        self.input_names.push(name.clone());
2343                        let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
2344                            name, port_type,
2345                        ));
2346                        let passthrough_name = format!("__port_{name}");
2347                        asm.add_node(&passthrough_name, passthrough, vec![WireRef::input(name)]);
2348                        asm.add_output(name, WireRef::node(&passthrough_name));
2349                        asm.set_output_modifier(name, BindingModifier::SHARED);
2350                        continue;
2351                    }
2352                    self.compile_binding(&mut asm, &b.targets, &b.value)?;
2353                    // Every target that now names a node reports what it
2354                    // resolved to: a call, an operator, or a literal alike.
2355                    for target in &b.targets {
2356                        if let Some(node_type) = asm.node_type_of(target) {
2357                            self.pending_events.push(
2358                                super::events::CompileEvent::BindingResolved {
2359                                    name: target.clone(),
2360                                    node_type,
2361                                },
2362                            );
2363                        }
2364                    }
2365                    if b.modifier != BindingModifier::NONE {
2366                        for target in &b.targets {
2367                            asm.set_output_modifier(target, b.modifier);
2368                        }
2369                    }
2370                    // A const is marked, and the assembler decides how it
2371                    // is fixed: a value known at build folds there, and any
2372                    // other is captured when the kernel is initialized.
2373                    if b.modifier.is_const() {
2374                        for target in &b.targets {
2375                            asm.mark_const_output(target);
2376                        }
2377                    }
2378                }
2379                Statement::ModuleDef(_) => {}
2380                Statement::ExternPort(port) => {
2381                    // Mirror `compile()`: same kind classification —
2382                    // a default expression marks this as a capture
2383                    // port (dynamic); no default marks it as an
2384                    // iteration extern (effectively-const at
2385                    // scope-init time).
2386                    let port_type = crate::ast::PortType::from_keyword(port.typ.as_str())
2387                        .ok_or_else(|| {
2388                            format!(
2389                                "extern '{}': unknown polydat type keyword '{}'. \
2390                             Canonical keywords are emitted by PortType::to_keyword \
2391                             (one per PortType variant).",
2392                                port.name, port.typ,
2393                            )
2394                        })?;
2395                    let (default_value, kind) = match &port.default {
2396                        Some(expr) => {
2397                            let v = evaluate_default_expr(expr, port_type)
2398                                .map_err(|e| format!("extern '{}' default: {e}", port.name,))?;
2399                            (v, crate::kernel::InputKind::ExternalWrite)
2400                        }
2401                        None => (
2402                            crate::ast::Value::None,
2403                            crate::kernel::InputKind::IterationExtern,
2404                        ),
2405                    };
2406                    asm.add_input(&port.name, default_value, port_type, kind);
2407                    if self.inferred_externs.contains(&port.name) {
2408                        asm.set_input_origin(&port.name, crate::kernel::TypeOrigin::Inferred);
2409                    }
2410                    self.input_names.push(port.name.clone());
2411                    let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
2412                        &port.name, port_type,
2413                    ));
2414                    let passthrough_name = format!("__port_{}", port.name);
2415                    asm.add_node(
2416                        &passthrough_name,
2417                        passthrough,
2418                        vec![crate::compile::assembly::WireRef::input(&port.name)],
2419                    );
2420                    asm.add_output(
2421                        &port.name,
2422                        crate::compile::assembly::WireRef::node(&passthrough_name),
2423                    );
2424                }
2425                Statement::Cursor(decl) => {
2426                    self.process_cursor(&mut asm, decl)?;
2427                }
2428                Statement::Pragma { .. } => {}
2429                Statement::For(f) => {
2430                    return Err(format!(
2431                        "`for {}` at line {}, col {}: {}",
2432                        f.source.to_text(),
2433                        f.span.line,
2434                        f.span.col,
2435                        "a `for` traversal compiles through `compile_polydat` and runs through `PolydatKernel::traverse`; the assembler entry point builds one program and cannot carry a traversal (docs/design/for_traversal.md §5)"
2436                    ));
2437                }
2438                Statement::Tile(t) => {
2439                    self.compile_tile(&mut asm, t)?;
2440                }
2441            }
2442        }
2443
2444        // Unused binding check: defer to kernel-level check in fold_init_constants_impl.
2445        // The kernel has the full wiring graph and can accurately determine which
2446        // nodes have no downstream consumers. The compiler can't do this reliably
2447        // because it doesn't track inter-binding wire dependencies.
2448
2449        // Expose outputs: only the required set, or all if no filter.
2450        // Cursor extent aux outputs (`__cursor_extent_*`) must always be
2451        // exposed regardless of the filter — they are queried by the
2452        // post-compile deferred extent resolution and would otherwise be
2453        // pruned by DCE, leaving the cursor extent unresolved.
2454        match required_outputs {
2455            Some(required) => {
2456                // `volatile` bindings (polydat_grammar.md §5) stay
2457                // exposed as outputs even when the caller's
2458                // required list doesn't mention them. The author
2459                // declared the wire as volatile to mark it as
2460                // non-deterministic across invocations — losing
2461                // it from the output set (DCE) would also lose
2462                // the "exclude from program identity" guarantee,
2463                // because the lifecycle classifier would no
2464                // longer find a volatile output pointing at the
2465                // producing node.
2466                let mut required_owned: Vec<String> = required.to_vec();
2467                for stmt in &file.statements {
2468                    if let crate::dsl::ast::Statement::Binding(b) = stmt
2469                        && b.modifier.is_volatile()
2470                    {
2471                        for t in &b.targets {
2472                            if !required_owned.iter().any(|n| n == t) {
2473                                required_owned.push(t.clone());
2474                            }
2475                        }
2476                    }
2477                }
2478                // A const stays an output whatever the caller asked for:
2479                // the assembler captures it from its output, and a binder
2480                // reads it from there.
2481                for stmt in &file.statements {
2482                    if let crate::dsl::ast::Statement::Binding(b) = stmt
2483                        && b.modifier.is_const()
2484                    {
2485                        for t in &b.targets {
2486                            if !required_owned.iter().any(|n| n == t) {
2487                                required_owned.push(t.clone());
2488                            }
2489                        }
2490                    }
2491                }
2492                for name in &required_owned {
2493                    if self.all_names.contains(name) {
2494                        self.pending_events
2495                            .push(super::events::CompileEvent::OutputDeclared {
2496                                name: name.clone(),
2497                            });
2498                    }
2499                    if self.all_names.contains(name) {
2500                        asm.add_output(name, WireRef::node(name));
2501                    }
2502                }
2503                for deferred in &self.deferred_extents {
2504                    if self.all_names.contains(&deferred.start_output) {
2505                        asm.add_output(
2506                            &deferred.start_output,
2507                            WireRef::node(&deferred.start_output),
2508                        );
2509                    }
2510                    if self.all_names.contains(&deferred.end_output) {
2511                        asm.add_output(&deferred.end_output, WireRef::node(&deferred.end_output));
2512                    }
2513                }
2514                // Always preserve `__cursor_extent_*` auxiliary
2515                // outputs — they're consumed by the comprehension
2516                // `all(<cursor>)` form (expression_engine.md §3.3) and
2517                // also by the post-compile deferred-extent
2518                // resolution above. DCE-ing them would leave the
2519                // cursor's extent unresolvable to descendant scopes.
2520                let pruned_aux: Vec<String> = self
2521                    .all_names
2522                    .iter()
2523                    .filter(|n| n.starts_with("__cursor_extent_"))
2524                    .cloned()
2525                    .collect();
2526                for name in pruned_aux {
2527                    asm.add_output(&name, WireRef::node(&name));
2528                }
2529            }
2530            None => {
2531                for name in &self.all_names {
2532                    self.pending_events
2533                        .push(super::events::CompileEvent::OutputDeclared { name: name.clone() });
2534                    asm.add_output(name, WireRef::node(name));
2535                }
2536            }
2537        }
2538
2539        asm.set_context(&self.source_text, &self.context_label);
2540        // The strictness pragmas reach every kernel built from this
2541        // assembler, on every engine and on every entry point.
2542        asm.set_strict_wires(self.pragmas.strict_types(), self.pragmas.strict_values());
2543        asm.set_strict(self.strict);
2544        asm.set_input_variance(self.input_variance);
2545        // The cursors, with their partitions resolved at build, reach
2546        // every kernel built from this assembler (engines.md §3.5).
2547        asm.set_cursor_schemas(self.cursor_schemas.clone());
2548        Ok(asm)
2549    }
2550}
2551
2552// ── The one entry point (engines.md §3.5) ──────────────────
2553
2554/// Compile `source` for `engine`: the interpreter, the closure tier,
2555/// the hybrid kernel, or pure native code. Every engine accepts every
2556/// program the interpreter accepts, or refuses it with a reason
2557/// ([`crate::KernelError::Refused`]); a host drives the result through
2558/// [`crate::Kernel`] without knowing which engine it holds. The
2559/// `compile_polydat_kernel*` and `compile_polydat_checked` entry
2560/// points and `compile_polydat` are this on `Engine::default()`;
2561/// `compile_polydat_interpreter_with_options` and the deprecated forms
2562/// build the interpreter's kernel.
2563pub fn compile_polydat_with(
2564    source: &str,
2565    engine: crate::Engine,
2566) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2567    compile_polydat_with_engine(source, engine, &CompileOptions::default(), None)
2568}
2569
2570/// [`compile_polydat_with`] on [`Engine::default`](crate::Engine::default):
2571/// compiled code, with the JIT where the build has it.
2572pub fn compile_polydat_kernel(source: &str) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2573    compile_polydat_with(source, crate::Engine::default())
2574}
2575
2576/// [`compile_polydat_kernel`] with the kernel path's options (source
2577/// directory, library paths, required outputs, strict typing, the
2578/// error context label, the cursor limit, and the engine preference)
2579/// and the compile event log.
2580///
2581/// This is the entry point the engine preference is read from: it
2582/// builds on `options.engine`, which defaults to the most native form
2583/// the build has, so a host that never sets the field gets compiled
2584/// code without naming one.
2585pub fn compile_polydat_kernel_with_options(
2586    source: &str,
2587    options: &CompileOptions,
2588    log: Option<&mut super::events::CompileEventLog>,
2589) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2590    compile_polydat_with_engine(source, options.engine, options, log)
2591}
2592
2593/// [`compile_polydat_with`] with the kernel path's options (source
2594/// directory, library paths, required outputs, strict typing, the
2595/// error context label, the cursor limit) and the compile event log.
2596/// On the interpreter this is the whole kernel path, traversals
2597/// included; on a compiled engine the assembler entry point followed
2598/// by [`PolydatAssembler::compile_engine_with_log`].
2599///
2600/// The `engine` argument is a per-call override of `options.engine`,
2601/// for a caller that holds one options value and walks the tiers with
2602/// it. A caller that has no such need expresses the preference once, in
2603/// the options, and calls [`compile_polydat_kernel_with_options`].
2604pub fn compile_polydat_with_engine(
2605    source: &str,
2606    engine: crate::Engine,
2607    options: &CompileOptions,
2608    mut log: Option<&mut super::events::CompileEventLog>,
2609) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2610    use crate::KernelError;
2611    let tokens = super::lexer::lex(source).map_err(KernelError::Source)?;
2612    let ast = super::parser::parse(tokens).map_err(KernelError::Source)?;
2613    if let Some(log) = log.as_deref_mut() {
2614        log.push(super::events::CompileEvent::Parsed {
2615            statements: ast.statements.len(),
2616        });
2617    }
2618    compile_ast_with_engine(&ast, source, options, log, engine)
2619}
2620
2621/// [`compile_polydat_with_engine`] from a parsed file: the parent
2622/// compiles on `engine` through the assembler, and each `for` body
2623/// compiles once for the interpreter as the traversal's record and on
2624/// any engine at activation (engines.md §3.6).
2625pub fn compile_ast_with_engine(
2626    ast: &PolydatFile,
2627    source: &str,
2628    options: &CompileOptions,
2629    mut log: Option<&mut super::events::CompileEventLog>,
2630    engine: crate::Engine,
2631) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2632    let mut prepared = Prepared::new(source, ast, options, log.as_deref_mut());
2633    let (compiler, filter) = prepared.parts();
2634    compile_file_on_engine(compiler, ast, filter, engine, log)
2635}
2636
2637/// [`compile_ast_with_engine`] for a template, a module image whose
2638/// inputs a binder supplies: the build is not initialized, each kernel
2639/// bound from it is.
2640pub(crate) fn compile_template_with_engine(
2641    ast: &PolydatFile,
2642    options: &CompileOptions,
2643    engine: crate::Engine,
2644) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2645    let mut prepared = Prepared::new("", ast, options, None);
2646    let (compiler, filter) = prepared.parts();
2647    compiler.template = true;
2648    compile_file_on_engine(compiler, ast, filter, engine, None)
2649}
2650
2651/// Everything an entry point sets up before a program assembles: the
2652/// compiler under its options, the outputs to keep, and the data-file
2653/// base directory for the compile's duration. One prologue for every
2654/// entry point, so the options mean the same thing whichever one
2655/// carries them.
2656struct Prepared {
2657    compiler: Compiler,
2658    required: Vec<String>,
2659    _data_base: Option<DataBaseDirGuard>,
2660}
2661
2662impl Prepared {
2663    fn new(
2664        source: &str,
2665        ast: &PolydatFile,
2666        options: &CompileOptions,
2667        log: Option<&mut super::events::CompileEventLog>,
2668    ) -> Self {
2669        // Relative data-file paths (csv/jsonl nodes) resolve against the
2670        // program's own directory for the duration of this synchronous
2671        // compile; see `library::datafile::set_data_base_dir`.
2672        let _data_base = options.source_dir.as_deref().map(DataBaseDirGuard::set);
2673        // `strict` in the options is `pragma strict` at the program's top
2674        // scope (polydat_grammar.md §14): the host seeds the set the
2675        // program's own pragmas add to. The log records the pragmas the
2676        // source declares.
2677        let pragmas = super::pragmas::PragmaSet::host(options.strict).nested(&ast.statements);
2678        if let Some(log) = log {
2679            record_pragma_events(&super::pragmas::collect_from_ast(ast), log);
2680        }
2681        // The required-outputs list is extended with the const bindings
2682        // only when the caller passed one: an empty list keeps every
2683        // binding, and extending it would flip its meaning.
2684        let required = if options.required_outputs.is_empty() {
2685            Vec::new()
2686        } else {
2687            extend_required_with_const_bindings(&options.required_outputs, ast)
2688        };
2689        let mut compiler = Compiler::with_lib_paths(
2690            options.source_dir.clone(),
2691            options.lib_paths.clone(),
2692            options.strict,
2693        );
2694        compiler.source_text = source.to_string();
2695        // An empty context keeps the compiler's default label, so a
2696        // failure reads the same whichever entry point built the kernel.
2697        if !options.context.is_empty() {
2698            compiler.context_label = options.context.clone();
2699        }
2700        compiler.cursor_limit = options.cursor_limit;
2701        compiler.input_variance = options.input_variance;
2702        compiler.inferred_externs = options.inferred_externs.clone();
2703        compiler.pragmas = pragmas;
2704        if let Some(ledger) = &options.ledger {
2705            compiler.ledger = ledger.clone();
2706        }
2707        if let Some(resources) = &options.resources {
2708            compiler.resources = resources.clone();
2709        }
2710        Prepared {
2711            compiler,
2712            required,
2713            _data_base,
2714        }
2715    }
2716
2717    /// The compiler and the output filter, `None` for every output.
2718    fn parts(&mut self) -> (&mut Compiler, Option<&[String]>) {
2719        let filter = if self.required.is_empty() {
2720            None
2721        } else {
2722            Some(self.required.as_slice())
2723        };
2724        (&mut self.compiler, filter)
2725    }
2726}
2727
2728/// The one path from a parsed file to a kernel, on every engine: the
2729/// `for` statements and producer bindings are lifted out, the parent
2730/// assembles and `build` makes its kernel, each body compiles once
2731/// against the parent's types and is attached, the tile events reach
2732/// the log, and every cursor extent the program computes from constants
2733/// is resolved on the kernel. Returns the kernel with the parent file
2734/// the traversals were lifted from.
2735fn compile_file_with<K: Built>(
2736    compiler: &mut Compiler,
2737    file: &PolydatFile,
2738    filter: Option<&[String]>,
2739    mut log: Option<&mut super::events::CompileEventLog>,
2740    build: impl FnOnce(
2741        PolydatAssembler,
2742        Option<&mut super::events::CompileEventLog>,
2743    ) -> Result<K, crate::KernelError>,
2744) -> Result<(K, PolydatFile), crate::KernelError> {
2745    use crate::KernelError;
2746    use crate::iteration::comprehension::{Surface, unresolved_names};
2747    let (mut parent_file, for_stmts, producers) = super::traversal::strip_for_forms(
2748        file,
2749        compiler.validation_mode(),
2750        &compiler.source_scope(),
2751        &mut compiler.pending_events,
2752        &|_| true,
2753    )
2754    .map_err(KernelError::Source)?;
2755    // The compiler as it stands before assembly, to assemble again from.
2756    let mut stripped = compiler.fresh_like();
2757    stripped.pending_events = compiler.pending_events.clone();
2758    compiler.producers_seen = producers.clone();
2759    let mut asm = compiler
2760        .assemble_parent(&parent_file, filter)
2761        .map_err(KernelError::Source)?;
2762    // V3 (comprehension_forms.md §5): a producer's comprehension reads
2763    // the names of the scope its wire is bound in, which a traversal over
2764    // it captures when it opens and the assembled program has.
2765    let has = |name: &str| {
2766        asm.output_type(name).is_some()
2767            || asm.input_type(name).is_some()
2768            || asm.output_names().contains(&name)
2769    };
2770    let mut scope_names: Vec<String> = Vec::new();
2771    let mut reads_none = false;
2772    let mut warnings = Vec::new();
2773    for p in &producers {
2774        let reads = unresolved_names(&p.comprehension, Surface::Traversal(&has));
2775        reads_none |= reads.iter().any(|r| !r.bare);
2776        scope_names.extend(
2777            crate::iteration::comprehension::outer_reads(&p.comprehension)
2778                .into_iter()
2779                .filter(|r| !r.bare && has(&r.name))
2780                .map(|r| r.name),
2781        );
2782        warnings.extend(
2783            compiler
2784                .check_statement_names(
2785                    &format!("{} := for {}", p.name, p.source_text),
2786                    p.span,
2787                    reads,
2788                )
2789                .map_err(KernelError::Source)?,
2790        );
2791    }
2792    // A producer that reads a name nothing binds carries on its wire only
2793    // the names the scope has, so its stream reads the others as None: the
2794    // program assembles again, from the compiler as it stood before, with
2795    // those streamers.
2796    if reads_none {
2797        let (restripped, _, _) = super::traversal::strip_for_forms(
2798            file,
2799            compiler.validation_mode(),
2800            &compiler.source_scope(),
2801            &mut Vec::new(),
2802            &|name| scope_names.iter().any(|n| n == name),
2803        )
2804        .map_err(KernelError::Source)?;
2805        parent_file = restripped;
2806        *compiler = stripped;
2807        compiler.producers_seen = producers.clone();
2808        asm = compiler
2809            .assemble_parent(&parent_file, filter)
2810            .map_err(KernelError::Source)?;
2811    }
2812    compiler.pending_events.extend(warnings);
2813    // The tiles typed while assembling belong to this program's log.
2814    if let Some(log) = log.as_deref_mut() {
2815        for e in compiler.pending_events.drain(..) {
2816            log.push(e);
2817        }
2818    }
2819    let mut built = build(asm, log.as_deref_mut())?;
2820    let kernel: &mut dyn crate::Kernel = built.kernel();
2821    if !for_stmts.is_empty() || !producers.is_empty() {
2822        let externs = kernel.externs();
2823        let inputs = kernel.input_names();
2824        let type_of = |name: &str| {
2825            kernel.output_type(name).or_else(|| {
2826                externs
2827                    .iter()
2828                    .find(|(n, _)| n == name)
2829                    .map(|(_, t)| *t)
2830                    .or_else(|| {
2831                        // A coordinate: the one input kind that is not an extern.
2832                        inputs
2833                            .iter()
2834                            .any(|n| n == name)
2835                            .then_some(crate::ast::PortType::U64)
2836                    })
2837            })
2838        };
2839        let traversals = compiler
2840            .compile_traversals(&for_stmts, &producers, &type_of)
2841            .map_err(KernelError::Source)?;
2842        crate::kernel::KernelInternals::set_traversals(kernel, traversals, producers);
2843        // Tiles inside the bodies, typed in the child compilers.
2844        if let Some(log) = log {
2845            for e in compiler.pending_events.drain(..) {
2846                log.push(e);
2847            }
2848        }
2849    }
2850    // A cursor whose range is computed from constants gets its extent
2851    // from the values the build folded, on every engine.
2852    for deferred in &compiler.deferred_extents {
2853        let start = kernel
2854            .folded_value(&deferred.start_output)
2855            .map(|v| v.as_u64());
2856        let end = kernel
2857            .folded_value(&deferred.end_output)
2858            .map(|v| v.as_u64());
2859        if let (Some(s), Some(e)) = (start, end) {
2860            let resolved = e.saturating_sub(s);
2861            let extent = compiler
2862                .cursor_limit
2863                .map(|limit| resolved.min(limit))
2864                .unwrap_or(resolved);
2865            if let Some(schema) = compiler.cursor_schemas.get_mut(deferred.schema_idx) {
2866                schema.extent = Some(extent);
2867            }
2868            kernel.set_cursor_extent(deferred.schema_idx, extent);
2869        }
2870    }
2871    Ok((built, parent_file))
2872}
2873
2874/// What a build hands back to the compile path: the interpreter's
2875/// concrete kernel or any engine's boxed one, each reachable as the one
2876/// trait the lowering drives.
2877trait Built {
2878    fn kernel(&mut self) -> &mut dyn crate::Kernel;
2879}
2880
2881impl Built for PolydatKernel {
2882    fn kernel(&mut self) -> &mut dyn crate::Kernel {
2883        self
2884    }
2885}
2886
2887impl Built for Box<dyn crate::Kernel> {
2888    fn kernel(&mut self) -> &mut dyn crate::Kernel {
2889        self.as_mut()
2890    }
2891}
2892
2893/// The kernel of a parsed file on `engine`: [`compile_file_with`] with
2894/// the engine's build, and the interpreter's concrete kernel boxed when
2895/// the engine is the interpreter.
2896pub(super) fn compile_file_on_engine(
2897    compiler: &mut Compiler,
2898    file: &PolydatFile,
2899    filter: Option<&[String]>,
2900    engine: crate::Engine,
2901    log: Option<&mut super::events::CompileEventLog>,
2902) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2903    if let crate::Engine::Interpreter(cones) = engine {
2904        return compiler
2905            .compile_interpreter(file, filter, log, cones)
2906            .map(|k| Box::new(k) as Box<dyn crate::Kernel>);
2907    }
2908    let (kernel, _) = compile_file_with(compiler, file, filter, log, |asm, log| {
2909        asm.compile_engine_with_log(engine, log)
2910    })?;
2911    Ok(kernel)
2912}
2913// ── Former names of the interpreter-typed entry points ──────────────
2914//
2915// These returned the interpreter's concrete kernel under names that did
2916// not say so, which read as though they were the general way to compile
2917// under options. They are the exception, not the rule: a kernel is used
2918// through the `Kernel` trait, and the concrete type is for observing the
2919// interpreter's own internals in testing and diagnostics (engines.md
2920// §3.6). The names now say that; these keep the old ones working.
2921
2922#[cfg(test)]
2923mod tests {
2924    use super::*;
2925
2926    /// The interpreter kernel under `strict` alone.
2927    fn strict(src: &str, strict: bool) -> Result<PolydatKernel, crate::KernelError> {
2928        let options = CompileOptions {
2929            strict,
2930            ..CompileOptions::default()
2931        };
2932        compile_polydat_interpreter_with_options(src, &options, None)
2933    }
2934
2935    #[test]
2936    fn array_literal_binding_compiles_as_string() {
2937        // A list-valued binding (`const xs := [1, 2, 3]`) is a sweep
2938        // axis / interpolation value, not a scalar wire. polydat has no
2939        // const-vector node, so it binds to a `ConstStr` holding the
2940        // list's literal text rather than failing the compile — which
2941        // is what lets list-valued workload params (`limit_values:
2942        // [25]`) load.
2943        let result = compile_polydat_interpreter(
2944            "input cycle: u64\nconst eh_values := [1, 2, 3]\nout := cycle",
2945        );
2946        assert!(
2947            result.is_ok(),
2948            "array-literal binding should compile (binds as a string const), got: {:?}",
2949            result.err(),
2950        );
2951        // The resolved value is the comma-joined, bracket-free form a
2952        // sweep-axis param carries (so a `WorkloadParamList` source
2953        // splits it on `, ` exactly like a string-valued sweep param).
2954        let kernel = result.unwrap();
2955        match kernel.get_constant("eh_values") {
2956            Some(crate::ast::Value::Str(s)) => assert_eq!(s.as_ref(), "1, 2, 3"),
2957            other => panic!("expected eh_values = Str(\"1, 2, 3\"), got {other:?}"),
2958        }
2959    }
2960
2961    #[test]
2962    fn array_literal_in_argument_position_is_refused() {
2963        // The other half of the same rule: a list literal is a
2964        // binding-position form and has no meaning as a call argument
2965        // (polydat_grammar.md §18.1 T-ArrayLit). Lowered to a const
2966        // argument, nothing would read it, and the call would reach the
2967        // runtime with one wire input missing and panic there.
2968        let err = compile_polydat_interpreter("input cycle: u64\nout := printf(\"{}\", [1, 2])")
2969            .expect_err("a list literal in argument position is a compile error");
2970        let text = err.to_string();
2971        assert!(
2972            text.contains("binding-position form") && text.contains("printf"),
2973            "the error should name the form and the call: {text}",
2974        );
2975        // Bound first, the same list works, which is what the message
2976        // tells the author to do.
2977        let ok =
2978            compile_polydat_interpreter("input cycle: u64\nw := [1, 2]\nout := printf(\"{}\", w)");
2979        assert!(ok.is_ok(), "{:?}", ok.err());
2980    }
2981
2982    #[test]
2983    fn embedding_error_display_includes_source_text() {
2984        let e = EmbeddingError::LifecycleMismatch {
2985            source: "hash(cycle)".to_string(),
2986            dynamic_inputs: vec!["cycle".to_string()],
2987        };
2988        let s = format!("{e}");
2989        assert!(
2990            s.contains("hash(cycle)"),
2991            "display should include source: {s}"
2992        );
2993        assert!(
2994            s.contains("cycle"),
2995            "display should mention dynamic input: {s}"
2996        );
2997    }
2998
2999    #[test]
3000    fn embedding_error_from_string_shim() {
3001        let e = EmbeddingError::UnresolvedPlaceholder {
3002            name: "k".to_string(),
3003            source: "{k} > 5".to_string(),
3004        };
3005        let s: String = e.clone().into();
3006        assert_eq!(s, format!("{e}"));
3007    }
3008
3009    #[test]
3010    fn embedding_error_all_variants_display() {
3011        // Smoke test: every variant constructs and displays without panicking.
3012        let variants: Vec<EmbeddingError> = vec![
3013            EmbeddingError::Parse {
3014                source: "x +".into(),
3015                message: "unexpected EOF".into(),
3016                position: Some(3),
3017            },
3018            EmbeddingError::UnresolvedPlaceholder {
3019                name: "k".into(),
3020                source: "{k}".into(),
3021            },
3022            EmbeddingError::LifecycleMismatch {
3023                source: "hash(cycle)".into(),
3024                dynamic_inputs: vec!["cycle".into()],
3025            },
3026            EmbeddingError::UnknownNode {
3027                name: "frobnicate".into(),
3028                source: "frobnicate(x)".into(),
3029                suggestion: Some("fabricate".into()),
3030            },
3031            EmbeddingError::TypeMismatch {
3032                from_node: "n1".into(),
3033                from_type: crate::ast::PortType::U64,
3034                to_node: "n2".into(),
3035                to_type: crate::ast::PortType::Str,
3036                source: "n1 -> n2".into(),
3037            },
3038            EmbeddingError::NodeEvalPanic {
3039                node_name: "div".into(),
3040                message: "div by zero".into(),
3041                source: "div(a, b)".into(),
3042            },
3043            EmbeddingError::NonePropagated {
3044                accessor: "as_bool",
3045                source: "{missing}".into(),
3046            },
3047        ];
3048        for v in variants {
3049            let _ = format!("{v}");
3050        }
3051    }
3052
3053    #[test]
3054    fn typed_surface_string() {
3055        let v: String = eval_const_expr_typed("\"hello\"").unwrap();
3056        assert_eq!(v, "hello");
3057    }
3058
3059    #[test]
3060    fn typed_surface_type_mismatch() {
3061        // expression yields U64; host requests f64 — widening allowed
3062        let v: f64 = eval_const_expr_typed("42").unwrap();
3063        assert_eq!(v, 42.0);
3064        // expression yields U64; host requests bool — interpreted as bool (nonzero)
3065        let v: bool = eval_const_expr_typed("1").unwrap();
3066        assert!(v);
3067        let v: bool = eval_const_expr_typed("0").unwrap();
3068        assert!(!v);
3069    }
3070
3071    #[test]
3072    fn typed_surface_return_path_adapter() {
3073        // γ-6: expression produces U64; host requests String.
3074        // The catalog's U64ToString adapter heals the return-path.
3075        let v: String = eval_const_expr_typed("42").unwrap();
3076        assert_eq!(v, "42");
3077
3078        // Expression produces F64; host requests String via catalog
3079        // F64ToString. (Note: f64's Display is locale-independent
3080        // but format may add trailing zeros.)
3081        let v: String = eval_const_expr_typed("3.14").unwrap();
3082        assert!(v.starts_with("3.14"), "got {v}");
3083    }
3084
3085    #[test]
3086    fn typed_surface_return_path_no_adapter_errors() {
3087        // Bytes → Bool isn't in the catalog. Confirm the typed
3088        // error fires when the catalog can't heal.
3089        // (Need an expression producing Bytes; use a string-
3090        // literal-to-bytes conversion via bytes_of or similar
3091        // if available; otherwise use a roundtrip that fails.)
3092        //
3093        // Skipping concrete bytes producer for this test —
3094        // the contract is exercised by the negative path in
3095        // typed_surface_type_mismatch already.
3096    }
3097
3098    #[test]
3099    fn typed_strict_rejects_lossy_conversion() {
3100        // U64 → Bool is in the catalog (γ-6 added it) but
3101        // lossy. Strict mode must reject.
3102        let result: Result<bool, _> = eval_const_expr_typed_strict("42");
3103        match result {
3104            Err(EmbeddingError::TypeMismatch {
3105                from_type, to_type, ..
3106            }) => {
3107                assert!(matches!(from_type, crate::ast::PortType::U64));
3108                assert!(matches!(to_type, crate::ast::PortType::Bool));
3109            }
3110            other => panic!("expected TypeMismatch, got {other:?}"),
3111        }
3112    }
3113
3114    #[test]
3115    fn typed_strict_accepts_lossless_conversion() {
3116        // U64 → String via display — lossless.
3117        let v: String = eval_const_expr_typed_strict("42").unwrap();
3118        assert_eq!(v, "42");
3119
3120        // Same type, no adapter.
3121        let v: f64 = eval_const_expr_typed_strict("42.0").unwrap();
3122        assert_eq!(v, 42.0);
3123    }
3124
3125    /// Strict mode answers about the types, not about the one value
3126    /// in hand: `U64 → F64` is refused because `u64` has 64 magnitude
3127    /// bits and `f64`'s significand holds 53, so values above `2^53`
3128    /// round. A host that wants the number as an `f64` writes it as
3129    /// one. The type-level answer is the same for every input, which
3130    /// a value-level one would not be.
3131    #[test]
3132    fn typed_strict_refuses_a_widening_that_rounds() {
3133        let r: Result<f64, _> = eval_const_expr_typed_strict("42");
3134        assert!(
3135            matches!(r, Err(EmbeddingError::TypeMismatch { .. })),
3136            "{r:?}"
3137        );
3138        assert!(!is_lossless_adapter(
3139            crate::ast::PortType::U64,
3140            crate::ast::PortType::F64
3141        ));
3142        assert!(!is_lossless_adapter(
3143            crate::ast::PortType::I64,
3144            crate::ast::PortType::F64
3145        ));
3146        // The narrow integers do fit, which the old eleven-pair
3147        // table did not say.
3148        for from in [
3149            crate::ast::PortType::U8,
3150            crate::ast::PortType::U16,
3151            crate::ast::PortType::U32,
3152        ] {
3153            assert!(
3154                is_lossless_adapter(from, crate::ast::PortType::U64),
3155                "{from:?} → U64"
3156            );
3157            assert!(
3158                is_lossless_adapter(from, crate::ast::PortType::F64),
3159                "{from:?} → F64"
3160            );
3161        }
3162        // Signed never fits unsigned, however wide.
3163        assert!(!is_lossless_adapter(
3164            crate::ast::PortType::I8,
3165            crate::ast::PortType::U128
3166        ));
3167    }
3168
3169    #[test]
3170    fn shared_computed_start_over_a_coordinate_is_refused() {
3171        // A computed starting value is evaluated once, at
3172        // initialization, so it may not read a coordinate.
3173        let src = r#"
3174            input cycle: u64
3175            shared rolling := hash(cycle)
3176        "#;
3177        let err = compile_polydat_interpreter(src)
3178            .expect_err("a starting value over a coordinate must error");
3179        assert!(
3180            err.to_string().contains("shared 'rolling'")
3181                && err.to_string().contains("coordinate 'cycle'"),
3182            "error: {err}"
3183        );
3184    }
3185
3186    #[test]
3187    fn shared_computed_start_is_seeded_at_init() {
3188        let src = r#"
3189            input cycle: u64
3190            extern base: u64 = 20
3191            shared rolling := u64_add(base, base)
3192        "#;
3193        let k = compile_polydat_interpreter(src).expect("a computed start compiles");
3194        assert_eq!(k.lookup("rolling"), Some(crate::ast::Value::U64(40)));
3195    }
3196
3197    #[test]
3198    fn shared_const_is_refused() {
3199        let err = compile_polydat_interpreter("shared const x := 1\n")
3200            .expect_err("`shared const` must error");
3201        assert!(
3202            err.to_string().contains("const") && err.to_string().contains("shared"),
3203            "error: {err}"
3204        );
3205    }
3206
3207    #[test]
3208    fn final_modifier_tracked() {
3209        let src = r#"
3210            input cycle: u64
3211            const dim := 128
3212        "#;
3213        let kernel = compile_polydat_interpreter(src).unwrap();
3214        assert_eq!(
3215            kernel.program().output_modifier("dim"),
3216            crate::dsl::ast::BindingModifier::CONST
3217        );
3218    }
3219
3220    #[test]
3221    fn shared_literal_modifier_tracked() {
3222        let src = r#"
3223            input cycle: u64
3224            shared budget := 100
3225        "#;
3226        let kernel = compile_polydat_interpreter(src).unwrap();
3227        assert_eq!(
3228            kernel.program().output_modifier("budget"),
3229            crate::dsl::ast::BindingModifier::SHARED
3230        );
3231        // Shared cells back the output via a port-passthrough node
3232        // reading the input slot; `lookup` is the cell-aware read.
3233        assert_eq!(kernel.lookup("budget").unwrap().as_u64(), 100);
3234    }
3235
3236    #[test]
3237    fn const_literal_modifier_tracked() {
3238        let src = r#"
3239            input cycle: u64
3240            const max_dim := 256
3241        "#;
3242        let kernel = compile_polydat_interpreter(src).unwrap();
3243        assert_eq!(
3244            kernel.program().output_modifier("max_dim"),
3245            crate::dsl::ast::BindingModifier::CONST
3246        );
3247        assert_eq!(kernel.get_constant("max_dim").unwrap().as_u64(), 256);
3248    }
3249
3250    #[test]
3251    fn compile_string_constant() {
3252        let src = r#"
3253            input cycle: u64
3254            label := "hello world"
3255        "#;
3256        let mut kernel = compile_polydat_interpreter(src).unwrap();
3257        kernel.set_inputs(&[0]);
3258        assert_eq!(kernel.pull_ref("label").as_str(), "hello world");
3259    }
3260
3261    #[test]
3262    fn compile_int_constant() {
3263        let src = r#"
3264            input cycle: u64
3265            base := 1710000000000
3266        "#;
3267        let mut kernel = compile_polydat_interpreter(src).unwrap();
3268        kernel.set_inputs(&[0]);
3269        assert_eq!(kernel.pull_ref("base").as_u64(), 1_710_000_000_000);
3270    }
3271
3272    // --- Diagnostic tests ---
3273
3274    #[test]
3275    fn error_unknown_function() {
3276        let src = "input cycle: u64\nresult := foobar(cycle)";
3277        let (_result, report) = compile_polydat_checked(src);
3278        assert!(report.has_errors());
3279        let errors = report.errors();
3280        assert!(
3281            errors
3282                .iter()
3283                .any(|e| e.message.contains("unknown function"))
3284        );
3285        assert!(errors.iter().any(|e| e.message.contains("foobar")));
3286    }
3287
3288    #[test]
3289    fn explicit_coordinates_rejects_unbound() {
3290        // With explicit coordinates, unbound references are errors
3291        let src = "input cycle: u64\nh := hash(unknown)";
3292        let (_, report) = compile_polydat_checked(src);
3293        assert!(report.has_errors());
3294        assert!(
3295            report
3296                .errors()
3297                .iter()
3298                .any(|e| e.message.contains("undefined") && e.message.contains("unknown"))
3299        );
3300    }
3301
3302    #[test]
3303    fn warning_forward_reference() {
3304        let src = r#"
3305            input cycle: u64
3306            result := mod(h, 100)
3307            h := hash(cycle)
3308        "#;
3309        let (_, report) = compile_polydat_checked(src);
3310        let warnings = report.warnings();
3311        assert!(
3312            warnings
3313                .iter()
3314                .any(|w| w.message.contains("forward reference")),
3315            "should warn about forward ref, got: {:?}",
3316            warnings
3317        );
3318    }
3319
3320    #[test]
3321    fn error_undefined_wire() {
3322        let src = r#"
3323            input cycle: u64
3324            result := hash(nonexistent)
3325        "#;
3326        let (_, report) = compile_polydat_checked(src);
3327        assert!(report.has_errors());
3328        assert!(
3329            report
3330                .errors()
3331                .iter()
3332                .any(|e| e.message.contains("undefined") && e.message.contains("nonexistent"))
3333        );
3334    }
3335
3336    #[test]
3337    fn error_report_includes_source_line() {
3338        let src = "input cycle: u64\nresult := unknown_func(cycle)";
3339        let (_, report) = compile_polydat_checked(src);
3340        let s = report.to_string();
3341        assert!(
3342            s.contains("unknown_func"),
3343            "report should include source context"
3344        );
3345    }
3346
3347    // --- Strict mode tests ---
3348
3349    #[test]
3350    fn strict_requires_explicit_inputs() {
3351        // Without inputs declaration, strict mode should error
3352        let src = "h := hash(cycle)";
3353        let result = strict(src, true);
3354        assert!(result.is_err());
3355        let err = result.unwrap_err();
3356        assert!(
3357            err.to_string().contains("strict mode"),
3358            "expected strict error, got: {err}"
3359        );
3360        assert!(
3361            err.to_string().contains("inputs"),
3362            "expected inputs mention, got: {err}"
3363        );
3364    }
3365
3366    // --- Dead code elimination tests ---
3367
3368    // --- Strict mode comprehensive tests ---
3369
3370    // --- eval_const_expr tests ---
3371
3372    #[test]
3373    fn eval_const_expr_fails_on_inputs() {
3374        // 'cycle' is a runtime input — should fail as const expr
3375        let r = eval_const_expr("hash(cycle)");
3376        assert!(r.is_err(), "hash(cycle) should fail as a const expression");
3377    }
3378
3379    // ─────────────────────────────────────────────────────────────
3380    // The const contract (evaluation_model.md, "Const Binding
3381    // Contract"): a literal const folds at build; any other const is
3382    // evaluated when its kernel is initialized. A const that reads a
3383    // coordinate is a compile error.
3384    // ─────────────────────────────────────────────────────────────
3385
3386    #[test]
3387    fn init_binding_compile_const_folded() {
3388        // Pure init: literal arg, no externs. Folds at compile
3389        // time; the compiled program's output_map points at a
3390        // ConstU64 leaf.
3391        let src = "const dim := 128\n";
3392        let kernel = compile_polydat_interpreter(src).expect("init compile-const");
3393        let prog = kernel.program();
3394        assert!(prog.const_outputs().contains(&"dim"));
3395        let &(node_idx, _) = prog.output_map_lookup("dim").expect("dim in output map");
3396        // After fold, the node has empty wiring (leaf const).
3397        assert!(
3398            prog.wiring[node_idx].is_empty(),
3399            "compile-const init binding 'dim' must fold to a leaf const node"
3400        );
3401    }
3402
3403    #[test]
3404    fn a_const_over_an_extern_is_evaluated_at_init() {
3405        // A const over an extern compiles and is evaluated when the
3406        // kernel is initialized, from the extern's value then.
3407        let src = "extern profile: str = \"p1\"\n\
3408                   const label := \"label_{profile}\"\n";
3409        let mut k = compile_polydat_interpreter(src).expect("a const may read an extern");
3410        assert_eq!(k.pull_ref("label").as_str(), "label_p1");
3411    }
3412
3413    #[test]
3414    fn a_const_over_a_volatile_source_captures_it_at_init() {
3415        // A const over a nondeterministic source is evaluated once, when
3416        // the kernel is initialized, and holds that value until `init`
3417        // runs again; every other read of the source re-reads it.
3418        let src = "const first := counter()\nnow := counter()\n";
3419        let mut k = compile_polydat_interpreter(src).expect("a const may capture a volatile value");
3420        let captured = k.pull_ref("first").as_u64();
3421        let _ = k.pull_ref("now");
3422        let _ = k.pull_ref("now");
3423        assert_eq!(
3424            k.pull_ref("first").as_u64(),
3425            captured,
3426            "reads do not re-evaluate a const"
3427        );
3428        crate::kernel::Kernel::init(&mut k).expect("re-initialize");
3429        assert_ne!(
3430            k.pull_ref("first").as_u64(),
3431            captured,
3432            "init evaluates the const again"
3433        );
3434    }
3435
3436    #[test]
3437    fn init_outputs_threaded_into_program() {
3438        // Sanity: the compiler records every `init`-declared name
3439        // on the program's const outputs so the executor can walk
3440        // them at scope activation.
3441        let src = "const a := 1\n\
3442                   const b := 2\n\
3443                   c := 3\n";
3444        let kernel = compile_polydat_interpreter(src).unwrap();
3445        let init_set = kernel.program().const_outputs();
3446        assert!(init_set.contains(&"a"), "const 'a' should be tracked");
3447        assert!(init_set.contains(&"b"), "const 'b' should be tracked");
3448        assert!(
3449            !init_set.contains(&"c"),
3450            "non-const 'c' must not be tracked"
3451        );
3452    }
3453
3454    /// Auto-extern slots inferred from RHS shape land at the
3455    /// boundary with their actual type (Str / U64 / F64 / Bool)
3456    /// rather than the `PortType::Ext` catchall, so workloads that
3457    /// use `set:` blocks with iter-var interpolation meet no
3458    /// `U64 → Ext` boundary-adapter miss.
3459    ///
3460    /// Test path: declare an iteration extern explicitly with
3461    /// `extern N: str` (no default → `IterationExtern` kind,
3462    /// effectively-const at scope-init); reference it from a
3463    /// const RHS. The const target then needs an auto-extern
3464    /// slot (RHS has a ref), and the inferrer picks the
3465    /// referenced input's type.
3466    #[test]
3467    fn auto_extern_slot_inherits_string_template_type() {
3468        let src = r#"
3469            extern some_outer_var: str
3470            const x := "{some_outer_var}"
3471        "#;
3472        let kernel = compile_polydat_interpreter(src).expect("compile");
3473        assert_eq!(
3474            kernel.program().input_port_type("x"),
3475            Some(crate::ast::PortType::Str),
3476            "string-template auto-extern MUST be Str, not Ext",
3477        );
3478    }
3479
3480    /// Identifier reference auto-extern inherits the referenced
3481    /// input's type. `const y := other_str_input` → y is Str.
3482    #[test]
3483    fn auto_extern_slot_inherits_ident_reference_type() {
3484        let src = r#"
3485            extern other: str
3486            const y := other
3487        "#;
3488        let kernel = compile_polydat_interpreter(src).expect("compile");
3489        assert_eq!(
3490            kernel.program().input_port_type("y"),
3491            Some(crate::ast::PortType::Str),
3492            "ident-RHS auto-extern MUST inherit referenced input's type",
3493        );
3494    }
3495
3496    /// `dataset_prebuffer(...)` returns `Value::Handle` — the
3497    /// auto-extern slot for `const prebuffered := dataset_prebuffer(...)`
3498    /// MUST be `PortType::Handle`, not the `Ext` catchall.
3499    /// (`dataset_prebuffer` is a vectordata node, so the test only
3500    /// exists when that feature registers it.)
3501    #[cfg(feature = "vectordata")]
3502    #[test]
3503    fn auto_extern_slot_for_dataset_prebuffer_is_handle() {
3504        let src = r#"
3505            extern source_uri: str
3506            const prebuffered := dataset_prebuffer(source_uri)
3507        "#;
3508        let kernel = compile_polydat_interpreter(src).expect("compile");
3509        assert_eq!(
3510            kernel.program().input_port_type("prebuffered"),
3511            Some(crate::ast::PortType::Handle),
3512            "dataset_prebuffer auto-extern MUST be Handle, not Ext",
3513        );
3514    }
3515}