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 input declared without a type is omitted,
1269/// leaving the assembler's `U64` default in force; the parser refuses a
1270/// type name that is not a keyword, so only an AST built by hand can
1271/// carry one here, and it is omitted the same way.
1272fn declared_input_types(
1273    file: &PolydatFile,
1274) -> std::collections::HashMap<String, crate::ast::PortType> {
1275    let mut types = std::collections::HashMap::new();
1276    for stmt in &file.statements {
1277        if let Statement::InputDecl(d) = stmt
1278            && let Some(ty) = &d.ty
1279            && let Some(pt) = crate::ast::PortType::from_keyword(ty)
1280        {
1281            types.insert(d.name.clone(), pt);
1282        }
1283    }
1284    types
1285}
1286
1287/// Extract a string literal from an optional positional argument.
1288/// Re-exported for cursor-sugar handlers in node modules that
1289/// validate string-literal-only constructor args.
1290pub fn positional_str_lit(arg: Option<&crate::dsl::ast::Arg>) -> Option<String> {
1291    match arg? {
1292        crate::dsl::ast::Arg::Positional(crate::dsl::ast::Expr::StringLit(s, _)) => Some(s.clone()),
1293        _ => None,
1294    }
1295}
1296
1297pub(super) struct Compiler {
1298    pub(super) input_names: Vec<String>,
1299    /// Track all named outputs so we can expose them.
1300    pub(super) all_names: Vec<String>,
1301    /// Auto-generated node counter for desugared intermediates.
1302    pub(super) anon_counter: usize,
1303    /// Directory for module resolution (search for .polydat files).
1304    pub(super) source_dir: Option<PathBuf>,
1305    /// Additional library directories for module resolution.
1306    ///
1307    /// Searched after `source_dir` but before the embedded stdlib.
1308    /// Populated from `CompileOptions::lib_paths` (the binary's
1309    /// `--lib`).
1310    pub(super) polydat_lib_paths: Vec<PathBuf>,
1311    /// Cache of already-resolved module ASTs: module_name → (inputs, statements).
1312    pub(super) module_cache: std::collections::HashMap<String, ResolvedModule>,
1313    /// When true, enforce strict validation.
1314    pub(super) strict: bool,
1315    /// Original source text, attached to compiled programs for diagnostics.
1316    source_text: String,
1317    /// Source schemas collected during compilation.
1318    pub(super) cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
1319    /// Deferred cursor extent resolutions: each entry maps a cursor
1320    /// schema index to the aux output names that, once folded, give
1321    /// the range's start and end values. These are resolved after the
1322    /// kernel compiles by reading `get_constant()` for each name.
1323    pub(super) deferred_extents: Vec<DeferredExtent>,
1324    /// Optional limit applied to all cursors (from `limit` activity param).
1325    pub(super) cursor_limit: Option<u64>,
1326    /// What the assembler does with inputs whose type was inferred.
1327    pub(super) input_variance: InputVariance,
1328    /// Externs whose type the caller inferred (`CompileOptions::inferred_externs`).
1329    pub(super) inferred_externs: Vec<String>,
1330    /// Diagnostic context label.
1331    context_label: String,
1332    /// Module-level pragmas extracted from the source. Drive the
1333    /// assembler's `strict_types` / `strict_values` flags
1334    /// (polydat_grammar.md §14, graph_compiler.md §2).
1335    pub(super) pragmas: super::pragmas::PragmaSet,
1336    /// LHS binding name currently being compiled, if any. Used as a
1337    /// prefix for auto-generated anonymous node names so type-mismatch
1338    /// errors point at the user-level binding (`overscan__anon_3`)
1339    /// instead of an opaque counter (`__anon_14`).
1340    pub(super) current_binding: Option<String>,
1341    /// The bindings under construction, outermost first: what every
1342    /// node factory receives as its build context's binding chain.
1343    pub(super) binding_chain: Vec<String>,
1344    /// The resource scope of the tree being compiled: the root's,
1345    /// handed to every body compiler and every node factory.
1346    pub(super) resources: crate::resource::ResourceScope,
1347    /// Tiles lowered so far in this compile, in order, so later tiles
1348    /// can splice earlier ones (polytile.md §5.5).
1349    pub(super) tiles: Vec<super::ast::TileDef>,
1350    /// Producer bindings seen so far, so tile projections over a
1351    /// producer can type their elements.
1352    pub(super) producers_seen: Vec<super::traversal::Producer>,
1353    /// Events raised while lowering, handed to the compile event log:
1354    /// one `TileHoleTyped` per hole (polytile.md §4.4), so `explain tiles`
1355    /// can show how each hole was typed and encoded, one
1356    /// `ComprehensionWarning` per degenerate composition (§5.8), and the
1357    /// steps of this compile that report themselves (a binding resolved,
1358    /// a module inlined, an output declared), merged into the log after
1359    /// the parent assembles.
1360    pub(super) pending_events: Vec<super::events::CompileEvent>,
1361    /// The compile ledger of the tree being compiled: the root's, handed
1362    /// to every body compiler and to the assembler of every program.
1363    pub(super) ledger: std::sync::Arc<crate::kernel::CompileLedger>,
1364    /// The program is a template whose inputs a binder supplies — a
1365    /// `for` body, a module image, a tile's projection body — so its
1366    /// build is not initialized: each kernel bound from it is.
1367    pub(crate) template: bool,
1368}
1369
1370/// Records a cursor whose `range(...)` bounds reference const
1371/// expressions (e.g., `vector_count("example:default")`) rather than
1372/// integer literals. The expressions are compiled as auxiliary outputs
1373/// and the extent is resolved after kernel compilation by querying the
1374/// constant values.
1375pub(super) struct DeferredExtent {
1376    /// Index into `cursor_schemas` whose extent needs resolution.
1377    pub schema_idx: usize,
1378    /// Name of the aux output that, when folded, gives the start value.
1379    pub start_output: String,
1380    /// Name of the aux output that, when folded, gives the end value.
1381    pub end_output: String,
1382}
1383
1384impl Compiler {
1385    /// The comprehension validation mode of this compile
1386    /// (comprehension_forms.md §5.8): a strict compile refuses a
1387    /// degenerate composition, a lax one warns about it.
1388    pub(super) fn validation_mode(&self) -> crate::iteration::comprehension::Mode {
1389        if self.strict {
1390            crate::iteration::comprehension::Mode::Strict
1391        } else {
1392            crate::iteration::comprehension::Mode::Permissive
1393        }
1394    }
1395
1396    /// V3 at a comprehension statement written in this compiler's scope
1397    /// (comprehension_forms.md §5): `reads` are the names its
1398    /// comprehension reads that nothing binds. Under `pragma strict` in
1399    /// this scope they are the statement's error. Outside it the
1400    /// statement compiles: the names are recorded on the tree's ledger
1401    /// ([`UnresolvedNameWarning`](crate::kernel::UnresolvedNameWarning)),
1402    /// the returned event carries them to the compile event log, and each
1403    /// reads None when the comprehension is evaluated.
1404    pub(super) fn check_statement_names(
1405        &self,
1406        statement: &str,
1407        span: super::lexer::Span,
1408        reads: Vec<crate::iteration::comprehension::NameRead>,
1409    ) -> Result<Option<super::events::CompileEvent>, String> {
1410        if reads.is_empty() {
1411            return Ok(None);
1412        }
1413        if self.pragmas.strict_names() {
1414            return Err(format!(
1415                "`{statement}` at line {}, col {}: {}",
1416                span.line,
1417                span.col,
1418                crate::iteration::comprehension::ValidationError::V3UnresolvedNames { reads }
1419            ));
1420        }
1421        let warning = crate::kernel::UnresolvedNameWarning {
1422            context: self.context_label.clone(),
1423            statement: statement.to_string(),
1424            line: span.line,
1425            col: span.col,
1426            reads,
1427        };
1428        let event = super::events::CompileEvent::Warning {
1429            message: warning.to_string(),
1430        };
1431        self.ledger.record_unresolved_names(warning);
1432        Ok(Some(event))
1433    }
1434
1435    /// A compiler with this one's settings and nothing compiled: the
1436    /// state a compile of this scope starts from.
1437    pub(super) fn fresh_like(&self) -> Compiler {
1438        let mut fresh = Compiler::with_lib_paths(
1439            self.source_dir.clone(),
1440            self.polydat_lib_paths.clone(),
1441            self.strict,
1442        );
1443        fresh.module_cache = self.module_cache.clone();
1444        fresh.source_text = self.source_text.clone();
1445        fresh.context_label = self.context_label.clone();
1446        fresh.cursor_limit = self.cursor_limit;
1447        fresh.input_variance = self.input_variance;
1448        fresh.inferred_externs = self.inferred_externs.clone();
1449        fresh.pragmas = self.pragmas.clone();
1450        fresh.resources = self.resources.clone();
1451        fresh.ledger = self.ledger.clone();
1452        fresh.template = self.template;
1453        fresh
1454    }
1455
1456    /// The scope a context-free source evaluates in during this
1457    /// compile (comprehension_forms.md §10.7.0): no name resolves, and
1458    /// what has to compile is charged to the program tree's ledger.
1459    pub(super) fn source_scope(&self) -> crate::kernel::interp::NoScope {
1460        crate::kernel::interp::NoScope::charged_to(self.ledger.clone())
1461    }
1462
1463    /// The build context a node factory receives at this point of the
1464    /// compile: the bindings under construction and the tree's
1465    /// resource scope.
1466    pub(super) fn build_context(&self) -> super::factory::BuildContext {
1467        super::factory::BuildContext::new(self.binding_chain.clone(), self.resources.clone())
1468    }
1469
1470    pub(super) fn with_lib_paths(
1471        source_dir: Option<PathBuf>,
1472        polydat_lib_paths: Vec<PathBuf>,
1473        strict: bool,
1474    ) -> Self {
1475        Self {
1476            input_names: Vec::new(),
1477            all_names: Vec::new(),
1478            anon_counter: 0,
1479            source_dir,
1480            polydat_lib_paths,
1481            module_cache: std::collections::HashMap::new(),
1482            strict,
1483            source_text: String::new(),
1484            context_label: "(polydat)".into(),
1485            cursor_schemas: Vec::new(),
1486            deferred_extents: Vec::new(),
1487            cursor_limit: None,
1488            input_variance: InputVariance::Fixed,
1489            inferred_externs: Vec::new(),
1490            pragmas: super::pragmas::PragmaSet::default(),
1491            current_binding: None,
1492            binding_chain: Vec::new(),
1493            resources: crate::resource::ResourceScope::new(),
1494            tiles: Vec::new(),
1495            producers_seen: Vec::new(),
1496            pending_events: Vec::new(),
1497            ledger: crate::kernel::CompileLedger::new(),
1498            template: false,
1499        }
1500    }
1501
1502    /// Process a source declaration: create input ports for projections,
1503    /// passthrough nodes, and record the schema.
1504    fn process_cursor(
1505        &mut self,
1506        asm: &mut PolydatAssembler,
1507        decl: &crate::dsl::ast::CursorDecl,
1508    ) -> Result<(), String> {
1509        let source_name = &decl.name;
1510
1511        // Cursor-sugar dispatch: any node module can register a
1512        // handler that recognizes a non-`range` constructor (e.g.
1513        // `vectordata_base("ds", "label_00")`) and rewrites it into
1514        // a synthetic `range(...)` plus a list of aux bindings to
1515        // emit after input ports are wired. The core stays
1516        // generic — nothing here knows that vectordata exists.
1517        // See `dsl::cursor_sugar` for the registry mechanism.
1518        let sugar = crate::dsl::cursor_sugar::dispatch(source_name, &decl.constructor)?;
1519        let effective_constructor = match &sugar {
1520            Some(s) => s.effective_constructor.clone(),
1521            None => decl.constructor.clone(),
1522        };
1523
1524        // All sources get an "ordinal" projection.
1525        let mut projections = vec![("ordinal".to_string(), crate::ast::PortType::U64)];
1526
1527        // Determine extent from constructor args. Three cases per arg:
1528        //   1. Integer literal → use directly
1529        //   2. Other const-foldable expression (e.g. `vector_count("...")`)
1530        //      → compile as an aux output and resolve after kernel compiles
1531        //   3. Arg references runtime state → no extent available
1532        //
1533        // Immediate-literal cases produce a concrete extent here.
1534        // Deferred cases push a DeferredExtent record; the outer compile
1535        // routine reads the folded values after compilation and updates
1536        // the schema's extent in place.
1537        let mut deferred: Option<(Option<u64>, String, Option<u64>, String)> = None;
1538        let mut cursor_kind_for_decl: crate::iteration::source::CursorKind =
1539            crate::iteration::source::CursorKind::Range;
1540        let extent = match &effective_constructor {
1541            // ── until_*(...) — extending cursors ────────────────
1542            // Recognise every cursor function whose constructor
1543            // declares an extending policy. The shape of each is:
1544            //   until_FAMILY(base, ...policy_args[, delta])
1545            // where `base` is the initial extent / pass size and
1546            // policy_args carry the family's stop-condition
1547            // parameters. An optional final `delta` overrides the
1548            // extension step size (defaults to `base`).
1549            //
1550            // Recognised families:
1551            //   until_elapsed(base, min_ms[, delta])
1552            //   until_passes(base, min_passes[, delta])
1553            //   until_count(base, min_count[, delta])
1554            //   until_elapsed_and_passes(base, min_ms, min_passes[, delta])
1555            //   until_elapsed_or_passes(base, min_ms, min_passes[, delta])
1556            //
1557            // Common shape: emit `base` as the cursor's `end` aux
1558            // output, `start` as a literal 0, and each policy arg
1559            // as a named aux output the runtime pulls at phase
1560            // setup. The CursorKind variant carries the output
1561            // names so the executor knows how to build the policy.
1562            crate::dsl::ast::Expr::Call(call)
1563                if matches!(
1564                    call.func.as_str(),
1565                    "until_elapsed"
1566                        | "until_passes"
1567                        | "until_count"
1568                        | "until_elapsed_and_passes"
1569                        | "until_elapsed_or_passes"
1570                ) =>
1571            {
1572                let family = call.func.as_str();
1573                let expected = match family {
1574                    "until_elapsed" | "until_passes" | "until_count" => (2usize, 3usize),
1575                    "until_elapsed_and_passes" | "until_elapsed_or_passes" => (3, 4),
1576                    _ => unreachable!(),
1577                };
1578                let n = call.args.len();
1579                if n < expected.0 || n > expected.1 {
1580                    return Err(format!(
1581                        "cursor '{source_name}': `{family}` takes {}-{} args, got {n}",
1582                        expected.0, expected.1,
1583                    ));
1584                }
1585                // Common: base, start, end aux outputs.
1586                let base_literal = positional_int_lit(&call.args[0]);
1587                let base_name = format!("__cursor_extent_{source_name}_end");
1588                let start_name = format!("__cursor_extent_{source_name}_start");
1589                let _ = self.compile_binding(
1590                    asm,
1591                    std::slice::from_ref(&start_name),
1592                    &crate::dsl::ast::Expr::IntLit(0, decl.span),
1593                );
1594                if let crate::dsl::ast::Arg::Positional(expr) = &call.args[0] {
1595                    self.compile_binding(asm, std::slice::from_ref(&base_name), expr)
1596                        .map_err(|e| {
1597                            format!("cursor '{source_name}': failed to compile {family} base: {e}")
1598                        })?;
1599                }
1600                // Helper closure: compile a positional arg as a
1601                // named aux output. Returns the name on success.
1602                let mut compile_aux = |idx: usize, suffix: &str| -> Result<String, String> {
1603                    let out_name = format!("__cursor_{suffix}_{source_name}");
1604                    if let crate::dsl::ast::Arg::Positional(expr) = &call.args[idx] {
1605                        self.compile_binding(asm, std::slice::from_ref(&out_name), expr)
1606                            .map_err(|e| {
1607                                format!(
1608                                    "cursor '{source_name}': failed to compile \
1609                                 {family} arg {idx}: {e}"
1610                                )
1611                            })?;
1612                    }
1613                    Ok(out_name)
1614                };
1615                // Family-specific arg layout.
1616                cursor_kind_for_decl = match family {
1617                    "until_elapsed" => {
1618                        let min_ms_name = compile_aux(1, "min_ms")?;
1619                        let delta_output = if n == 3 {
1620                            Some(compile_aux(2, "delta")?)
1621                        } else {
1622                            None
1623                        };
1624                        crate::iteration::source::CursorKind::ExtendingTimed {
1625                            min_ms_output: min_ms_name,
1626                            delta_output,
1627                        }
1628                    }
1629                    "until_passes" => {
1630                        let min_passes_name = compile_aux(1, "min_passes")?;
1631                        let delta_output = if n == 3 {
1632                            Some(compile_aux(2, "delta")?)
1633                        } else {
1634                            None
1635                        };
1636                        crate::iteration::source::CursorKind::ExtendingPasses {
1637                            min_passes_output: min_passes_name,
1638                            delta_output,
1639                        }
1640                    }
1641                    "until_count" => {
1642                        let min_count_name = compile_aux(1, "min_count")?;
1643                        let delta_output = if n == 3 {
1644                            Some(compile_aux(2, "delta")?)
1645                        } else {
1646                            None
1647                        };
1648                        crate::iteration::source::CursorKind::ExtendingCount {
1649                            min_count_output: min_count_name,
1650                            delta_output,
1651                        }
1652                    }
1653                    "until_elapsed_and_passes" => {
1654                        let min_ms_name = compile_aux(1, "min_ms")?;
1655                        let min_passes_name = compile_aux(2, "min_passes")?;
1656                        let delta_output = if n == 4 {
1657                            Some(compile_aux(3, "delta")?)
1658                        } else {
1659                            None
1660                        };
1661                        crate::iteration::source::CursorKind::ExtendingElapsedAndPasses {
1662                            min_ms_output: min_ms_name,
1663                            min_passes_output: min_passes_name,
1664                            delta_output,
1665                        }
1666                    }
1667                    "until_elapsed_or_passes" => {
1668                        let min_ms_name = compile_aux(1, "min_ms")?;
1669                        let min_passes_name = compile_aux(2, "min_passes")?;
1670                        let delta_output = if n == 4 {
1671                            Some(compile_aux(3, "delta")?)
1672                        } else {
1673                            None
1674                        };
1675                        crate::iteration::source::CursorKind::ExtendingElapsedOrPasses {
1676                            min_ms_output: min_ms_name,
1677                            min_passes_output: min_passes_name,
1678                            delta_output,
1679                        }
1680                    }
1681                    _ => unreachable!(),
1682                };
1683                deferred = Some((Some(0), start_name, base_literal, base_name));
1684                base_literal
1685            }
1686            crate::dsl::ast::Expr::Call(call) if call.func == "range" && call.args.len() >= 2 => {
1687                let start_literal = positional_int_lit(&call.args[0]);
1688                let end_literal = positional_int_lit(&call.args[1]);
1689
1690                match (start_literal, end_literal) {
1691                    // Both literal — compute directly. We also emit
1692                    // the start/end as named final bindings so the
1693                    // comprehension `all(<cursor>)` form (expression_engine.md §3.3)
1694                    // can resolve them uniformly with the deferred
1695                    // (non-literal) case below.
1696                    (Some(s), Some(e)) => {
1697                        let start_name = format!("__cursor_extent_{source_name}_start");
1698                        let end_name = format!("__cursor_extent_{source_name}_end");
1699                        let s_lit = crate::dsl::ast::Expr::IntLit(s, decl.span);
1700                        let e_lit = crate::dsl::ast::Expr::IntLit(e, decl.span);
1701                        let _ = self.compile_binding(asm, &[start_name], &s_lit);
1702                        let _ = self.compile_binding(asm, &[end_name], &e_lit);
1703                        Some(e.saturating_sub(s))
1704                    }
1705                    // At least one non-literal — compile as aux outputs.
1706                    _ => {
1707                        let start_name = format!("__cursor_extent_{source_name}_start");
1708                        let end_name = format!("__cursor_extent_{source_name}_end");
1709                        // Compile each arg as a named auxiliary output. Errors
1710                        // are returned so the user sees them — silently
1711                        // dropping them would leave extent=None and produce
1712                        // a phase that runs zero cycles with no explanation.
1713                        if let crate::dsl::ast::Arg::Positional(expr) = &call.args[0] {
1714                            self.compile_binding(asm, std::slice::from_ref(&start_name), expr)
1715                                .map_err(|e| {
1716                                    format!(
1717                                        "cursor '{source_name}': failed to compile range start: {e}"
1718                                    )
1719                                })?;
1720                        }
1721                        if let crate::dsl::ast::Arg::Positional(expr) = &call.args[1] {
1722                            self.compile_binding(asm, std::slice::from_ref(&end_name), expr)
1723                                .map_err(|e| {
1724                                    format!(
1725                                        "cursor '{source_name}': failed to compile range end: {e}"
1726                                    )
1727                                })?;
1728                        }
1729                        deferred = Some((start_literal, start_name, end_literal, end_name));
1730                        None
1731                    }
1732                }
1733            }
1734            _ => None,
1735        };
1736
1737        // Create input ports and passthrough nodes for each projection.
1738        for (field_name, port_type) in &projections {
1739            let input_name = format!("{source_name}__{field_name}");
1740            let default_value = match port_type {
1741                crate::ast::PortType::U64 => crate::ast::Value::U64(0),
1742                crate::ast::PortType::F64 => crate::ast::Value::F64(0.0),
1743                _ => crate::ast::Value::None,
1744            };
1745
1746            // Cursor projection slots are written by cursor advance
1747            // every cycle — dynamic for init-contract purposes.
1748            asm.add_input(
1749                &input_name,
1750                default_value,
1751                *port_type,
1752                crate::kernel::InputKind::ExternalWrite,
1753            );
1754            self.input_names.push(input_name.clone());
1755
1756            let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
1757                &input_name,
1758                *port_type,
1759            ));
1760            let node_name = format!("{source_name}__{field_name}");
1761            asm.add_node(&node_name, passthrough, vec![WireRef::input(&input_name)]);
1762            asm.add_output(&node_name, WireRef::node(&node_name));
1763        }
1764
1765        // Apply any aux bindings the sugar handler asked for.
1766        // Bindings whose `projection` is `Some` are also published
1767        // as cursor projections — both pinned on the schema and
1768        // exposed as kernel outputs the runtime can read.
1769        if let Some(sugar) = sugar {
1770            for aux in sugar.aux_bindings {
1771                self.compile_binding(asm, std::slice::from_ref(&aux.name), &aux.value)
1772                    .map_err(|e| {
1773                        format!(
1774                            "cursor '{source_name}': failed to compile aux binding '{}': {e}",
1775                            aux.name,
1776                        )
1777                    })?;
1778                if let Some((field, port_type)) = aux.projection {
1779                    projections.push((field, port_type));
1780                    asm.add_output(&aux.name, WireRef::node(&aux.name));
1781                }
1782            }
1783        }
1784
1785        // If a limit is set, insert a limit() node that shadows the cursor wire.
1786        // The limit node is a visible, documented passthrough that clamps extent.
1787        let effective_extent = if let Some(limit_val) = self.cursor_limit {
1788            let limit_node_name = format!("{source_name}__limit");
1789            let ordinal_wire = format!("{source_name}__ordinal");
1790            asm.add_node(
1791                &limit_node_name,
1792                Box::new(crate::library::context::Limit::new(limit_val)),
1793                vec![WireRef::node(&ordinal_wire)],
1794            );
1795            // Shadow the ordinal output with the limited version
1796            asm.add_output(&ordinal_wire, WireRef::node(&limit_node_name));
1797
1798            // Clamp extent
1799            extent.map(|e| e.min(limit_val)).or(Some(limit_val))
1800        } else {
1801            extent
1802        };
1803
1804        let schema_idx = self.cursor_schemas.len();
1805        let extent_outputs = deferred
1806            .as_ref()
1807            .map(|(_, start, _, end)| (start.clone(), end.clone()));
1808
1809        // If the cursor decl carries an `over <expr>` clause
1810        // (cursor_partitions.md §7.2), set up two pieces of plumbing:
1811        //
1812        // 1. An auxiliary output `<source>__over_raw` carrying
1813        //    the raw expression value (typically a string spec
1814        //    or a workload-param-typed value). The executor
1815        //    pulls this at phase setup to determine the
1816        //    narrowing range.
1817        //
1818        // 2. An input slot + passthrough output `<source>__cursor`
1819        //    of type `Ext` — this is the field-access wire that
1820        //    workload authors reference as `<source>.cursor`. At
1821        //    phase setup the executor resolves the raw value to
1822        //    a concrete `Partition` and writes it into this slot,
1823        //    so downstream nodes (`mod_in`, `cardinality`, etc.)
1824        //    can consume it as a `Partition`-typed wire.
1825        let mut partitions: Option<Vec<crate::iteration::cursor_partition::Partition>> = None;
1826        let partition_output = if let Some(over_expr) = decl.over.as_ref() {
1827            let raw_name = format!("__cursor_{source_name}_over_raw");
1828            self.compile_binding(asm, std::slice::from_ref(&raw_name), over_expr)
1829                .map_err(|e| {
1830                    format!("cursor '{source_name}': failed to compile `over` expression: {e}")
1831                })?;
1832            // The wire is a spec string or a partition-typed external
1833            // (for_traversal.md §5, §7): any other type is refused here,
1834            // not at the first activation.
1835            if let Some(ty) = asm.output_type(&raw_name)
1836                && !matches!(ty, crate::ast::PortType::Str | crate::ast::PortType::Ext)
1837            {
1838                return Err(format!(
1839                    "cursor '{source_name}': `over` names a {ty:?} wire; expected a spec string or a partition-typed value"
1840                ));
1841            }
1842            // A literal spec over a known extent resolves now
1843            // (engines.md §3.5): the schema carries the
1844            // partitions for the host, and a clause that denotes
1845            // exactly one partition seeds the cursor's slots, so the
1846            // program runs on every engine with no host call. A clause
1847            // that denotes several leaves the choice to the host or
1848            // the traversal runtime.
1849            if let (crate::dsl::ast::Expr::StringLit(spec, _), Some(extent)) =
1850                (over_expr, effective_extent)
1851            {
1852                let open = !matches!(
1853                    cursor_kind_for_decl,
1854                    crate::iteration::source::CursorKind::Range
1855                );
1856                let parts = crate::iteration::cursor_partition::resolve_over(
1857                    &crate::ast::Value::Str(spec.as_str().into()),
1858                    extent,
1859                    open,
1860                )
1861                .map_err(|e| format!("cursor '{source_name}': `over \"{spec}\"`: {e}"))?;
1862                partitions = Some(parts);
1863            }
1864            let seeded: Option<crate::iteration::cursor_partition::Partition> =
1865                partitions.as_ref().filter(|p| p.len() == 1).map(|p| p[0]);
1866            // Allocate the resolved-Partition input slot. Its default
1867            // is the one partition the clause denotes, or `Value::None`
1868            // until the host or the traversal runtime narrows it.
1869            let cursor_input_name = format!("{source_name}__cursor");
1870            asm.add_input(
1871                &cursor_input_name,
1872                seeded.map_or(crate::ast::Value::None, crate::ast::Value::from_partition),
1873                crate::ast::PortType::Ext,
1874                crate::kernel::InputKind::ExternalWrite,
1875            );
1876            self.input_names.push(cursor_input_name.clone());
1877            let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
1878                &cursor_input_name,
1879                crate::ast::PortType::Ext,
1880            ));
1881            asm.add_node(
1882                &cursor_input_name,
1883                passthrough,
1884                vec![WireRef::input(&cursor_input_name)],
1885            );
1886            asm.add_output(&cursor_input_name, WireRef::node(&cursor_input_name));
1887            // Cursor metadata wires (cursor_partitions.md §7.2): scalar projections
1888            // of the resolved partition, as plain typed slots —
1889            // `<source>.cursor.idx` and friends parse as chained
1890            // field access and flatten onto these wires. The
1891            // executor writes them alongside the Ext slot at
1892            // phase setup; defaults here cover the no-narrowing
1893            // case (idx 0, count 1, full-extent pcts; the
1894            // ordinal pair is patched by the executor once the
1895            // cursor's extent is known).
1896            use crate::ast::{PortType, Value};
1897            let scalar_slots: [(&str, Value, PortType); 6] = match seeded {
1898                Some(p) => [
1899                    ("idx", Value::U64(p.idx), PortType::U64),
1900                    ("partition_count", Value::U64(p.count.max(1)), PortType::U64),
1901                    ("start_pct", Value::F64(p.start_pct), PortType::F64),
1902                    ("end_pct", Value::F64(p.end_pct), PortType::F64),
1903                    ("start_ordinal", Value::U64(p.start_ord), PortType::U64),
1904                    ("end_ordinal", Value::U64(p.end_ord), PortType::U64),
1905                ],
1906                None => [
1907                    ("idx", Value::U64(0), PortType::U64),
1908                    ("partition_count", Value::U64(1), PortType::U64),
1909                    ("start_pct", Value::F64(0.0), PortType::F64),
1910                    ("end_pct", Value::F64(100.0), PortType::F64),
1911                    ("start_ordinal", Value::U64(0), PortType::U64),
1912                    ("end_ordinal", Value::U64(0), PortType::U64),
1913                ],
1914            };
1915            for (field, default, port_type) in scalar_slots {
1916                let slot = format!("{cursor_input_name}__{field}");
1917                asm.add_input(
1918                    &slot,
1919                    default,
1920                    port_type,
1921                    crate::kernel::InputKind::ExternalWrite,
1922                );
1923                self.input_names.push(slot.clone());
1924                let pass = Box::new(crate::library::identity::PortPassthrough::new(
1925                    &slot, port_type,
1926                ));
1927                asm.add_node(&slot, pass, vec![WireRef::input(&slot)]);
1928                asm.add_output(&slot, WireRef::node(&slot));
1929            }
1930            Some(raw_name)
1931        } else {
1932            None
1933        };
1934
1935        self.cursor_schemas
1936            .push(crate::iteration::source::SourceSchema {
1937                name: source_name.clone(),
1938                projections,
1939                extent: effective_extent,
1940                extent_outputs,
1941                extent_limit: self.cursor_limit,
1942                cursor_kind: cursor_kind_for_decl.clone(),
1943                partition_output,
1944                partitions,
1945            });
1946
1947        // Record deferred extent resolution if the range bounds are not
1948        // both literals. Post-compile, the outer compile routine will
1949        // query the aux outputs' folded constants and update this
1950        // schema's extent in place.
1951        if let Some((_start_lit, start_output, _end_lit, end_output)) = deferred {
1952            self.deferred_extents.push(DeferredExtent {
1953                schema_idx,
1954                start_output,
1955                end_output,
1956            });
1957        }
1958        Ok(())
1959    }
1960
1961    /// The interpreter's kernel of `file` as its concrete type: the one
1962    /// compile path with the interpreter's build, keeping the outputs in
1963    /// `filter` (every output when `None`) and recording events in `log`.
1964    /// The parent's AST is retained as program metadata for the subscope
1965    /// synthesizer.
1966    pub(super) fn compile_interpreter(
1967        &mut self,
1968        file: &PolydatFile,
1969        filter: Option<&[String]>,
1970        log: Option<&mut super::events::CompileEventLog>,
1971        cones: crate::JitMode,
1972    ) -> Result<PolydatKernel, crate::KernelError> {
1973        let (mut kernel, parent) = compile_file_with(self, file, filter, log, |mut asm, log| {
1974            asm.set_jit_mode(cones);
1975            asm.compile_with_log(log).map_err(crate::KernelError::from)
1976        })?;
1977        kernel.set_ast(std::sync::Arc::new(parent));
1978        Ok(kernel)
1979    }
1980
1981    /// The output type of a generator expression used as a comprehension
1982    /// source (for_traversal.md §3.3): compile `__probe := <expr>` on its own and
1983    /// read the port type. Shared by `for` bodies and tile projections.
1984    pub(super) fn probe_element_type(&self, expr: &str) -> Result<crate::ast::PortType, String> {
1985        let src = format!("input cycle: u64\n__probe := {expr}\n");
1986        let tokens = lexer::lex(&src)?;
1987        let ast = parser::parse(tokens)?;
1988        let mut probe_compiler = Compiler::with_lib_paths(
1989            self.source_dir.clone(),
1990            self.polydat_lib_paths.clone(),
1991            false,
1992        );
1993        probe_compiler.source_text = src.clone();
1994        probe_compiler.context_label = format!("{} (element probe)", self.context_label);
1995        probe_compiler.resources = self.resources.clone();
1996        probe_compiler.module_cache = self.module_cache.clone();
1997        // Assembly answers this: the assembler knows an output's
1998        // declared port type as soon as the node is registered, so the
1999        // probe builds no kernel.
2000        let asm = probe_compiler.assemble_parent(&ast, None)?;
2001        asm.output_type("__probe")
2002            .ok_or_else(|| "probe produced no output".to_string())
2003    }
2004
2005    /// Lower each `for` statement's body to a child program, typed from
2006    /// its comprehension and the parent's manifest (for_traversal.md §3.3, §4).
2007    fn compile_traversals(
2008        &mut self,
2009        for_stmts: &[super::ast::ForStmt],
2010        producers: &[super::traversal::Producer],
2011        type_of: &dyn Fn(&str) -> Option<crate::ast::PortType>,
2012    ) -> Result<Vec<super::traversal::Traversal>, String> {
2013        use super::traversal::{
2014            Traversal, child_file, element_types, resolve_source_with, warning_events,
2015        };
2016        let mut out = Vec::with_capacity(for_stmts.len());
2017        for f in for_stmts {
2018            let (comprehension, warnings) = resolve_source_with(
2019                &f.source,
2020                producers,
2021                self.validation_mode(),
2022                &self.source_scope(),
2023            )?;
2024            self.pending_events
2025                .extend(warning_events(&f.source, &warnings));
2026            // V3 (comprehension_forms.md §5): the traversal supplies the
2027            // names of the scope it opens in, this program's.
2028            let reads = crate::iteration::comprehension::unresolved_names(
2029                &comprehension,
2030                crate::iteration::comprehension::Surface::Traversal(&|n| type_of(n).is_some()),
2031            );
2032            let warnings =
2033                self.check_statement_names(&format!("for {}", f.source.to_text()), f.span, reads)?;
2034            self.pending_events.extend(warnings);
2035            let mut probe = |expr: &str| self.probe_element_type(expr);
2036            let elements = element_types(&comprehension, &mut probe).map_err(|e| {
2037                format!(
2038                    "`for {}` at line {}, col {}: {e}",
2039                    f.source.to_text(),
2040                    f.span.line,
2041                    f.span.col
2042                )
2043            })?;
2044            let (child, cascade) = child_file(f, &comprehension, &elements, type_of)?;
2045            let mut child_compiler = Compiler::with_lib_paths(
2046                self.source_dir.clone(),
2047                self.polydat_lib_paths.clone(),
2048                self.strict,
2049            );
2050            // The body sees every module the parent resolved, its own
2051            // definitions included, wherever it compiles.
2052            child_compiler.module_cache = self.module_cache.clone();
2053            // The body's program is one of the tree's.
2054            child_compiler.ledger = self.ledger.clone();
2055            child_compiler.resources = self.resources.clone();
2056            child_compiler.source_text = super::pprint::pp_file(&child);
2057            child_compiler.context_label = format!(
2058                "{} :: for {} (line {}, col {})",
2059                self.context_label,
2060                f.source.to_text(),
2061                f.span.line,
2062                f.span.col
2063            );
2064            child_compiler.cursor_limit = self.cursor_limit;
2065            // The body is a pragma scope (polydat_grammar.md §14): it
2066            // compiles under this program's set plus its own pragmas.
2067            child_compiler.pragmas = self.pragmas.nested(&f.body);
2068            for pragma in super::pragmas::declared_in(&f.body) {
2069                self.pending_events.push(pragma_event(&pragma));
2070            }
2071            let child_kernel = child_compiler
2072                .compile_interpreter(&child, None, None, crate::JitMode::Auto)
2073                .map_err(|e| {
2074                    format!(
2075                        "`for {}` at line {}, col {}: body failed to compile: {e}",
2076                        f.source.to_text(),
2077                        f.span.line,
2078                        f.span.col
2079                    )
2080                })?;
2081            self.pending_events
2082                .append(&mut child_compiler.pending_events);
2083            let body = super::traversal::BodySource {
2084                file: child,
2085                source_text: child_compiler.source_text.clone(),
2086                source_dir: self.source_dir.clone(),
2087                lib_paths: self.polydat_lib_paths.clone(),
2088                strict: self.strict,
2089                context_label: child_compiler.context_label.clone(),
2090                cursor_limit: self.cursor_limit,
2091                pragmas: child_compiler.pragmas.clone(),
2092                modules: self.module_cache.clone(),
2093                programs: std::sync::Mutex::new(std::collections::HashMap::new()),
2094                ledger: self.ledger.clone(),
2095                resources: self.resources.clone(),
2096            };
2097            out.push(Traversal {
2098                span: f.span,
2099                source_text: f.source.to_text(),
2100                comprehension,
2101                elements,
2102                cascade,
2103                program: child_kernel.into_program(),
2104                body: std::sync::Arc::new(body),
2105            });
2106        }
2107        Ok(out)
2108    }
2109
2110    /// A body of this program's, from its lowered source: the
2111    /// settings this compiler carries, so the body compiles the way
2112    /// the program around it does — its source directory and library
2113    /// paths, its strict flag, its pragmas, the modules it has
2114    /// resolved, and the tree's compile ledger.
2115    ///
2116    /// A `for` body gets these because `compile_traversals` builds its
2117    /// `BodySource` in this compiler, and a tile's projection body gets
2118    /// them through this function.
2119    pub(super) fn body_source_for(
2120        &self,
2121        source: &str,
2122        context_label: &str,
2123    ) -> Result<super::traversal::BodySource, String> {
2124        let file = super::lexer::lex(source).and_then(super::parser::parse)?;
2125        let pragmas = self.pragmas.nested(&file.statements);
2126        Ok(super::traversal::BodySource::from_parts(
2127            file,
2128            source.to_string(),
2129            self.source_dir.clone(),
2130            self.polydat_lib_paths.clone(),
2131            self.strict,
2132            format!("{} :: {context_label}", self.context_label),
2133            self.cursor_limit,
2134            pragmas,
2135            self.module_cache.clone(),
2136            self.ledger.clone(),
2137            self.resources.clone(),
2138        ))
2139    }
2140
2141    /// Compile a traversal body on `engine` (engines.md §3.6): the same child file and
2142    /// compiler settings the parent used for the interpreter's program,
2143    /// through the assembler, its own `for` statements and producers
2144    /// included.
2145    pub(super) fn compile_body_on(
2146        body: &super::traversal::BodySource,
2147        engine: crate::Engine,
2148    ) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2149        let _data_base = body.source_dir.as_deref().map(DataBaseDirGuard::set);
2150        let mut compiler =
2151            Compiler::with_lib_paths(body.source_dir.clone(), body.lib_paths.clone(), body.strict);
2152        compiler.source_text = body.source_text.clone();
2153        compiler.context_label = body.context_label.clone();
2154        compiler.cursor_limit = body.cursor_limit;
2155        compiler.pragmas = body.pragmas.clone();
2156        compiler.module_cache = body.modules.clone();
2157        compiler.ledger = body.ledger.clone();
2158        compiler.resources = body.resources.clone();
2159        compiler.template = true;
2160        compile_file_on_engine(&mut compiler, &body.file, None, engine, None)
2161    }
2162
2163    /// Assemble the parent program: inputs and their passthroughs,
2164    /// externs, bindings, cursors, tiles, and the output set. Every
2165    /// entry point builds its assembler here, so a kernel and an
2166    /// assembler from the same source are the same graph.
2167    fn assemble_parent(
2168        &mut self,
2169        file: &PolydatFile,
2170        required_outputs: Option<&[String]>,
2171    ) -> Result<PolydatAssembler, String> {
2172        self.register_local_modules(file);
2173        // First pass: collect explicit `input` declarations, dedup by name.
2174        for stmt in &file.statements {
2175            if let Statement::InputDecl(d) = stmt
2176                && !self.input_names.iter().any(|n| n == &d.name)
2177            {
2178                self.input_names.push(d.name.clone());
2179            }
2180        }
2181
2182        // Input declaration check: error in strict mode (modules, .polydat files)
2183        if self.input_names.is_empty() && self.strict {
2184            return Err(
2185                "strict mode: no `input` declaration — add `input <name>: <type>` \
2186                 (or the tuple form `input (a: u64, b: f64)`) to declare graph \
2187                 inputs explicitly"
2188                    .into(),
2189            );
2190        }
2191
2192        // If no explicit inputs, infer from unbound references
2193        if self.input_names.is_empty() {
2194            let defined: HashSet<String> = file
2195                .statements
2196                .iter()
2197                .flat_map(|stmt| match stmt {
2198                    Statement::Binding(b) => b.targets.clone(),
2199                    Statement::ModuleDef(m) => vec![m.name.clone()],
2200                    Statement::ExternPort(p) => vec![p.name.clone()],
2201                    Statement::InputDecl(_) => vec![],
2202                    Statement::Cursor(_) => vec![],
2203                    Statement::Pragma { .. } => vec![],
2204                    Statement::For(_) => vec![],
2205                    Statement::Tile(t) => vec![t.name.clone()],
2206                })
2207                .collect();
2208
2209            let mut referenced: HashSet<String> = HashSet::new();
2210            for stmt in &file.statements {
2211                let expr = match stmt {
2212                    Statement::InputDecl(_)
2213                    | Statement::ModuleDef(_)
2214                    | Statement::ExternPort(_)
2215                    | Statement::Cursor(_)
2216                    | Statement::Pragma { .. }
2217                    | Statement::For(_)
2218                    | Statement::Tile(_) => continue,
2219                    Statement::Binding(b) => &b.value,
2220                };
2221                collect_references(expr, &mut referenced);
2222            }
2223
2224            let mut inferred: Vec<String> = referenced
2225                .into_iter()
2226                .filter(|name| !defined.contains(name))
2227                .collect();
2228            inferred.sort();
2229            self.input_names = inferred;
2230        }
2231
2232        // Zero inferred inputs means all bindings are constants — valid.
2233
2234        let mut asm = PolydatAssembler::new(self.input_names.clone());
2235        asm.ledger = self.ledger.clone();
2236        asm.resources = self.resources.clone();
2237        asm.template = self.template;
2238        for (name, ty) in declared_input_types(file) {
2239            asm.set_input_type(&name, ty);
2240        }
2241
2242        // Auto-expose every declared input as a passthrough output
2243        // (parity with `extern`). See `compile()` for the same wiring.
2244        for input_name in self.input_names.clone() {
2245            // Mirror the input's (now correctly-typed) slot so the
2246            // auto-exposed output carries the declared type, not U64.
2247            let port_type = asm
2248                .input_type(&input_name)
2249                .unwrap_or(crate::ast::PortType::U64);
2250            let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
2251                &input_name,
2252                port_type,
2253            ));
2254            let passthrough_name = format!("__port_{input_name}");
2255            asm.add_node(
2256                &passthrough_name,
2257                passthrough,
2258                vec![WireRef::input(&input_name)],
2259            );
2260            asm.add_output(&input_name, WireRef::node(&passthrough_name));
2261        }
2262
2263        // Second pass: process all bindings into the assembler
2264        for stmt in &file.statements {
2265            match stmt {
2266                Statement::InputDecl(_) => {}
2267                Statement::Binding(b) => {
2268                    // `shared X := <expr>` compiles to an input slot +
2269                    // passthrough output, so the binder can wire a
2270                    // `SharedCell` for cross-scope mutability
2271                    // (scope_model.md §6). A literal
2272                    // is the slot's default; any other expression
2273                    // compiles as the output `__init_X`, which the
2274                    // declaring kernel's initialization evaluates once
2275                    // and writes through the register. Tuple-target
2276                    // shared bindings are rejected: a register holds
2277                    // one value.
2278                    if b.modifier == BindingModifier::SHARED {
2279                        if b.targets.len() != 1 {
2280                            return Err(format!(
2281                                "shared binding must be single-target, not tuple unpack \
2282                                 ({}). Declare each target separately if a shared cell \
2283                                 is intended.",
2284                                b.targets.join(", "),
2285                            ));
2286                        }
2287                        let name = &b.targets[0];
2288                        let (init_value, port_type) = match try_fold_shared_init(&b.value) {
2289                            Some((init_value, port_type)) => apply_shared_type_annotation(
2290                                name,
2291                                b.type_annotation.as_ref(),
2292                                init_value,
2293                                port_type,
2294                            )?,
2295                            None => {
2296                                let source = format!("__init_{name}");
2297                                self.compile_binding(
2298                                    &mut asm,
2299                                    std::slice::from_ref(&source),
2300                                    &b.value,
2301                                )?;
2302                                let Some(computed) = asm.output_type(&source) else {
2303                                    return Err(format!(
2304                                        "internal error: the starting value of shared '{name}' \
2305                                         was just compiled, so the assembler should carry its \
2306                                         type"
2307                                    ));
2308                                };
2309                                let port_type = match b.type_annotation.as_ref() {
2310                                    None => computed,
2311                                    Some(t) => {
2312                                        let annotated = crate::ast::PortType::from_keyword(t)
2313                                            .ok_or_else(|| {
2314                                                format!(
2315                                                    "shared binding '{name}': unknown type \
2316                                                     `{t}` in annotation"
2317                                                )
2318                                            })?;
2319                                        if annotated != computed {
2320                                            return Err(format!(
2321                                                "shared binding '{name}: {t}': the starting \
2322                                                 value is {computed:?}, which doesn't match the \
2323                                                 annotated type. A cell keeps ONE type for \
2324                                                 life — convert the starting value to {t}."
2325                                            ));
2326                                        }
2327                                        annotated
2328                                    }
2329                                };
2330                                asm.add_output(&source, WireRef::node(&source));
2331                                // One reading, at initialization, as a
2332                                // const takes it.
2333                                asm.set_output_modifier(&source, BindingModifier::CONST);
2334                                asm.mark_shared_start(name, &source);
2335                                (crate::ast::Value::None, port_type)
2336                            }
2337                        };
2338                        asm.add_input(
2339                            name,
2340                            init_value,
2341                            port_type,
2342                            crate::kernel::InputKind::ExternalWrite,
2343                        );
2344                        self.input_names.push(name.clone());
2345                        let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
2346                            name, port_type,
2347                        ));
2348                        let passthrough_name = format!("__port_{name}");
2349                        asm.add_node(&passthrough_name, passthrough, vec![WireRef::input(name)]);
2350                        asm.add_output(name, WireRef::node(&passthrough_name));
2351                        asm.set_output_modifier(name, BindingModifier::SHARED);
2352                        continue;
2353                    }
2354                    self.compile_binding(&mut asm, &b.targets, &b.value)?;
2355                    // Every target that now names a node reports what it
2356                    // resolved to: a call, an operator, or a literal alike.
2357                    for target in &b.targets {
2358                        if let Some(node_type) = asm.node_type_of(target) {
2359                            self.pending_events.push(
2360                                super::events::CompileEvent::BindingResolved {
2361                                    name: target.clone(),
2362                                    node_type,
2363                                },
2364                            );
2365                        }
2366                    }
2367                    if b.modifier != BindingModifier::NONE {
2368                        for target in &b.targets {
2369                            asm.set_output_modifier(target, b.modifier);
2370                        }
2371                    }
2372                    // A const is marked, and the assembler decides how it
2373                    // is fixed: a value known at build folds there, and any
2374                    // other is captured when the kernel is initialized.
2375                    if b.modifier.is_const() {
2376                        for target in &b.targets {
2377                            asm.mark_const_output(target);
2378                        }
2379                    }
2380                }
2381                Statement::ModuleDef(_) => {}
2382                Statement::ExternPort(port) => {
2383                    // Mirror `compile()`: same kind classification —
2384                    // a default expression marks this as a capture
2385                    // port (dynamic); no default marks it as an
2386                    // iteration extern (effectively-const at
2387                    // scope-init time).
2388                    let port_type = crate::ast::PortType::from_keyword(port.typ.as_str())
2389                        .ok_or_else(|| {
2390                            format!(
2391                                "extern '{}': unknown polydat type keyword '{}'. \
2392                             Canonical keywords are emitted by PortType::to_keyword \
2393                             (one per PortType variant).",
2394                                port.name, port.typ,
2395                            )
2396                        })?;
2397                    let (default_value, kind) = match &port.default {
2398                        Some(expr) => {
2399                            let v = evaluate_default_expr(expr, port_type)
2400                                .map_err(|e| format!("extern '{}' default: {e}", port.name,))?;
2401                            (v, crate::kernel::InputKind::ExternalWrite)
2402                        }
2403                        None => (
2404                            crate::ast::Value::None,
2405                            crate::kernel::InputKind::IterationExtern,
2406                        ),
2407                    };
2408                    asm.add_input(&port.name, default_value, port_type, kind);
2409                    if self.inferred_externs.contains(&port.name) {
2410                        asm.set_input_origin(&port.name, crate::kernel::TypeOrigin::Inferred);
2411                    }
2412                    self.input_names.push(port.name.clone());
2413                    let passthrough = Box::new(crate::library::identity::PortPassthrough::new(
2414                        &port.name, port_type,
2415                    ));
2416                    let passthrough_name = format!("__port_{}", port.name);
2417                    asm.add_node(
2418                        &passthrough_name,
2419                        passthrough,
2420                        vec![crate::compile::assembly::WireRef::input(&port.name)],
2421                    );
2422                    asm.add_output(
2423                        &port.name,
2424                        crate::compile::assembly::WireRef::node(&passthrough_name),
2425                    );
2426                }
2427                Statement::Cursor(decl) => {
2428                    self.process_cursor(&mut asm, decl)?;
2429                }
2430                Statement::Pragma { .. } => {}
2431                Statement::For(f) => {
2432                    return Err(format!(
2433                        "`for {}` at line {}, col {}: {}",
2434                        f.source.to_text(),
2435                        f.span.line,
2436                        f.span.col,
2437                        "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)"
2438                    ));
2439                }
2440                Statement::Tile(t) => {
2441                    self.compile_tile(&mut asm, t)?;
2442                }
2443            }
2444        }
2445
2446        // Unused binding check: defer to kernel-level check in fold_init_constants_impl.
2447        // The kernel has the full wiring graph and can accurately determine which
2448        // nodes have no downstream consumers. The compiler can't do this reliably
2449        // because it doesn't track inter-binding wire dependencies.
2450
2451        // Expose outputs: only the required set, or all if no filter.
2452        // Cursor extent aux outputs (`__cursor_extent_*`) must always be
2453        // exposed regardless of the filter — they are queried by the
2454        // post-compile deferred extent resolution and would otherwise be
2455        // pruned by DCE, leaving the cursor extent unresolved.
2456        match required_outputs {
2457            Some(required) => {
2458                // `volatile` bindings (polydat_grammar.md §5) stay
2459                // exposed as outputs even when the caller's
2460                // required list doesn't mention them. The author
2461                // declared the wire as volatile to mark it as
2462                // non-deterministic across invocations — losing
2463                // it from the output set (DCE) would also lose
2464                // the "exclude from program identity" guarantee,
2465                // because the lifecycle classifier would no
2466                // longer find a volatile output pointing at the
2467                // producing node.
2468                let mut required_owned: Vec<String> = required.to_vec();
2469                for stmt in &file.statements {
2470                    if let crate::dsl::ast::Statement::Binding(b) = stmt
2471                        && b.modifier.is_volatile()
2472                    {
2473                        for t in &b.targets {
2474                            if !required_owned.iter().any(|n| n == t) {
2475                                required_owned.push(t.clone());
2476                            }
2477                        }
2478                    }
2479                }
2480                // A const stays an output whatever the caller asked for:
2481                // the assembler captures it from its output, and a binder
2482                // reads it from there.
2483                for stmt in &file.statements {
2484                    if let crate::dsl::ast::Statement::Binding(b) = stmt
2485                        && b.modifier.is_const()
2486                    {
2487                        for t in &b.targets {
2488                            if !required_owned.iter().any(|n| n == t) {
2489                                required_owned.push(t.clone());
2490                            }
2491                        }
2492                    }
2493                }
2494                for name in &required_owned {
2495                    if self.all_names.contains(name) {
2496                        self.pending_events
2497                            .push(super::events::CompileEvent::OutputDeclared {
2498                                name: name.clone(),
2499                            });
2500                    }
2501                    if self.all_names.contains(name) {
2502                        asm.add_output(name, WireRef::node(name));
2503                    }
2504                }
2505                for deferred in &self.deferred_extents {
2506                    if self.all_names.contains(&deferred.start_output) {
2507                        asm.add_output(
2508                            &deferred.start_output,
2509                            WireRef::node(&deferred.start_output),
2510                        );
2511                    }
2512                    if self.all_names.contains(&deferred.end_output) {
2513                        asm.add_output(&deferred.end_output, WireRef::node(&deferred.end_output));
2514                    }
2515                }
2516                // Always preserve `__cursor_extent_*` auxiliary
2517                // outputs — they're consumed by the comprehension
2518                // `all(<cursor>)` form (expression_engine.md §3.3) and
2519                // also by the post-compile deferred-extent
2520                // resolution above. DCE-ing them would leave the
2521                // cursor's extent unresolvable to descendant scopes.
2522                let pruned_aux: Vec<String> = self
2523                    .all_names
2524                    .iter()
2525                    .filter(|n| n.starts_with("__cursor_extent_"))
2526                    .cloned()
2527                    .collect();
2528                for name in pruned_aux {
2529                    asm.add_output(&name, WireRef::node(&name));
2530                }
2531            }
2532            None => {
2533                for name in &self.all_names {
2534                    self.pending_events
2535                        .push(super::events::CompileEvent::OutputDeclared { name: name.clone() });
2536                    asm.add_output(name, WireRef::node(name));
2537                }
2538            }
2539        }
2540
2541        asm.set_context(&self.source_text, &self.context_label);
2542        // The strictness pragmas reach every kernel built from this
2543        // assembler, on every engine and on every entry point.
2544        asm.set_strict_wires(self.pragmas.strict_types(), self.pragmas.strict_values());
2545        asm.set_strict(self.strict);
2546        asm.set_input_variance(self.input_variance);
2547        // The cursors, with their partitions resolved at build, reach
2548        // every kernel built from this assembler (engines.md §3.5).
2549        asm.set_cursor_schemas(self.cursor_schemas.clone());
2550        Ok(asm)
2551    }
2552}
2553
2554// ── The one entry point (engines.md §3.5) ──────────────────
2555
2556/// Compile `source` for `engine`: the interpreter, the closure tier,
2557/// the hybrid kernel, or pure native code. Every engine accepts every
2558/// program the interpreter accepts, or refuses it with a reason
2559/// ([`crate::KernelError::Refused`]); a host drives the result through
2560/// [`crate::Kernel`] without knowing which engine it holds. The
2561/// `compile_polydat_kernel*` and `compile_polydat_checked` entry
2562/// points and `compile_polydat` are this on `Engine::default()`;
2563/// `compile_polydat_interpreter_with_options` and the deprecated forms
2564/// build the interpreter's kernel.
2565pub fn compile_polydat_with(
2566    source: &str,
2567    engine: crate::Engine,
2568) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2569    compile_polydat_with_engine(source, engine, &CompileOptions::default(), None)
2570}
2571
2572/// [`compile_polydat_with`] on [`Engine::default`](crate::Engine::default):
2573/// compiled code, with the JIT where the build has it.
2574pub fn compile_polydat_kernel(source: &str) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2575    compile_polydat_with(source, crate::Engine::default())
2576}
2577
2578/// [`compile_polydat_kernel`] with the kernel path's options (source
2579/// directory, library paths, required outputs, strict typing, the
2580/// error context label, the cursor limit, and the engine preference)
2581/// and the compile event log.
2582///
2583/// This is the entry point the engine preference is read from: it
2584/// builds on `options.engine`, which defaults to the most native form
2585/// the build has, so a host that never sets the field gets compiled
2586/// code without naming one.
2587pub fn compile_polydat_kernel_with_options(
2588    source: &str,
2589    options: &CompileOptions,
2590    log: Option<&mut super::events::CompileEventLog>,
2591) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2592    compile_polydat_with_engine(source, options.engine, options, log)
2593}
2594
2595/// [`compile_polydat_with`] with the kernel path's options (source
2596/// directory, library paths, required outputs, strict typing, the
2597/// error context label, the cursor limit) and the compile event log.
2598/// On the interpreter this is the whole kernel path, traversals
2599/// included; on a compiled engine the assembler entry point followed
2600/// by [`PolydatAssembler::compile_engine_with_log`].
2601///
2602/// The `engine` argument is a per-call override of `options.engine`,
2603/// for a caller that holds one options value and walks the tiers with
2604/// it. A caller that has no such need expresses the preference once, in
2605/// the options, and calls [`compile_polydat_kernel_with_options`].
2606pub fn compile_polydat_with_engine(
2607    source: &str,
2608    engine: crate::Engine,
2609    options: &CompileOptions,
2610    mut log: Option<&mut super::events::CompileEventLog>,
2611) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2612    use crate::KernelError;
2613    let tokens = super::lexer::lex(source).map_err(KernelError::Source)?;
2614    let ast = super::parser::parse(tokens).map_err(KernelError::Source)?;
2615    if let Some(log) = log.as_deref_mut() {
2616        log.push(super::events::CompileEvent::Parsed {
2617            statements: ast.statements.len(),
2618        });
2619    }
2620    compile_ast_with_engine(&ast, source, options, log, engine)
2621}
2622
2623/// [`compile_polydat_with_engine`] from a parsed file: the parent
2624/// compiles on `engine` through the assembler, and each `for` body
2625/// compiles once for the interpreter as the traversal's record and on
2626/// any engine at activation (engines.md §3.6).
2627pub fn compile_ast_with_engine(
2628    ast: &PolydatFile,
2629    source: &str,
2630    options: &CompileOptions,
2631    mut log: Option<&mut super::events::CompileEventLog>,
2632    engine: crate::Engine,
2633) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2634    let mut prepared = Prepared::new(source, ast, options, log.as_deref_mut());
2635    let (compiler, filter) = prepared.parts();
2636    compile_file_on_engine(compiler, ast, filter, engine, log)
2637}
2638
2639/// [`compile_ast_with_engine`] for a template, a module image whose
2640/// inputs a binder supplies: the build is not initialized, each kernel
2641/// bound from it is.
2642pub(crate) fn compile_template_with_engine(
2643    ast: &PolydatFile,
2644    options: &CompileOptions,
2645    engine: crate::Engine,
2646) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2647    let mut prepared = Prepared::new("", ast, options, None);
2648    let (compiler, filter) = prepared.parts();
2649    compiler.template = true;
2650    compile_file_on_engine(compiler, ast, filter, engine, None)
2651}
2652
2653/// Everything an entry point sets up before a program assembles: the
2654/// compiler under its options, the outputs to keep, and the data-file
2655/// base directory for the compile's duration. One prologue for every
2656/// entry point, so the options mean the same thing whichever one
2657/// carries them.
2658struct Prepared {
2659    compiler: Compiler,
2660    required: Vec<String>,
2661    _data_base: Option<DataBaseDirGuard>,
2662}
2663
2664impl Prepared {
2665    fn new(
2666        source: &str,
2667        ast: &PolydatFile,
2668        options: &CompileOptions,
2669        log: Option<&mut super::events::CompileEventLog>,
2670    ) -> Self {
2671        // Relative data-file paths (csv/jsonl nodes) resolve against the
2672        // program's own directory for the duration of this synchronous
2673        // compile; see `library::datafile::set_data_base_dir`.
2674        let _data_base = options.source_dir.as_deref().map(DataBaseDirGuard::set);
2675        // `strict` in the options is `pragma strict` at the program's top
2676        // scope (polydat_grammar.md §14): the host seeds the set the
2677        // program's own pragmas add to. The log records the pragmas the
2678        // source declares.
2679        let pragmas = super::pragmas::PragmaSet::host(options.strict).nested(&ast.statements);
2680        if let Some(log) = log {
2681            record_pragma_events(&super::pragmas::collect_from_ast(ast), log);
2682        }
2683        // The required-outputs list is extended with the const bindings
2684        // only when the caller passed one: an empty list keeps every
2685        // binding, and extending it would flip its meaning.
2686        let required = if options.required_outputs.is_empty() {
2687            Vec::new()
2688        } else {
2689            extend_required_with_const_bindings(&options.required_outputs, ast)
2690        };
2691        let mut compiler = Compiler::with_lib_paths(
2692            options.source_dir.clone(),
2693            options.lib_paths.clone(),
2694            options.strict,
2695        );
2696        compiler.source_text = source.to_string();
2697        // An empty context keeps the compiler's default label, so a
2698        // failure reads the same whichever entry point built the kernel.
2699        if !options.context.is_empty() {
2700            compiler.context_label = options.context.clone();
2701        }
2702        compiler.cursor_limit = options.cursor_limit;
2703        compiler.input_variance = options.input_variance;
2704        compiler.inferred_externs = options.inferred_externs.clone();
2705        compiler.pragmas = pragmas;
2706        if let Some(ledger) = &options.ledger {
2707            compiler.ledger = ledger.clone();
2708        }
2709        if let Some(resources) = &options.resources {
2710            compiler.resources = resources.clone();
2711        }
2712        Prepared {
2713            compiler,
2714            required,
2715            _data_base,
2716        }
2717    }
2718
2719    /// The compiler and the output filter, `None` for every output.
2720    fn parts(&mut self) -> (&mut Compiler, Option<&[String]>) {
2721        let filter = if self.required.is_empty() {
2722            None
2723        } else {
2724            Some(self.required.as_slice())
2725        };
2726        (&mut self.compiler, filter)
2727    }
2728}
2729
2730/// The one path from a parsed file to a kernel, on every engine: the
2731/// `for` statements and producer bindings are lifted out, the parent
2732/// assembles and `build` makes its kernel, each body compiles once
2733/// against the parent's types and is attached, the tile events reach
2734/// the log, and every cursor extent the program computes from constants
2735/// is resolved on the kernel. Returns the kernel with the parent file
2736/// the traversals were lifted from.
2737fn compile_file_with<K: Built>(
2738    compiler: &mut Compiler,
2739    file: &PolydatFile,
2740    filter: Option<&[String]>,
2741    mut log: Option<&mut super::events::CompileEventLog>,
2742    build: impl FnOnce(
2743        PolydatAssembler,
2744        Option<&mut super::events::CompileEventLog>,
2745    ) -> Result<K, crate::KernelError>,
2746) -> Result<(K, PolydatFile), crate::KernelError> {
2747    use crate::KernelError;
2748    use crate::iteration::comprehension::{Surface, unresolved_names};
2749    let (mut parent_file, for_stmts, producers) = super::traversal::strip_for_forms(
2750        file,
2751        compiler.validation_mode(),
2752        &compiler.source_scope(),
2753        &mut compiler.pending_events,
2754        &|_| true,
2755    )
2756    .map_err(KernelError::Source)?;
2757    // The compiler as it stands before assembly, to assemble again from.
2758    let mut stripped = compiler.fresh_like();
2759    stripped.pending_events = compiler.pending_events.clone();
2760    compiler.producers_seen = producers.clone();
2761    let mut asm = compiler
2762        .assemble_parent(&parent_file, filter)
2763        .map_err(KernelError::Source)?;
2764    // V3 (comprehension_forms.md §5): a producer's comprehension reads
2765    // the names of the scope its wire is bound in, which a traversal over
2766    // it captures when it opens and the assembled program has.
2767    let has = |name: &str| {
2768        asm.output_type(name).is_some()
2769            || asm.input_type(name).is_some()
2770            || asm.output_names().contains(&name)
2771    };
2772    let mut scope_names: Vec<String> = Vec::new();
2773    let mut reads_none = false;
2774    let mut warnings = Vec::new();
2775    for p in &producers {
2776        let reads = unresolved_names(&p.comprehension, Surface::Traversal(&has));
2777        reads_none |= reads.iter().any(|r| !r.bare);
2778        scope_names.extend(
2779            crate::iteration::comprehension::outer_reads(&p.comprehension)
2780                .into_iter()
2781                .filter(|r| !r.bare && has(&r.name))
2782                .map(|r| r.name),
2783        );
2784        warnings.extend(
2785            compiler
2786                .check_statement_names(
2787                    &format!("{} := for {}", p.name, p.source_text),
2788                    p.span,
2789                    reads,
2790                )
2791                .map_err(KernelError::Source)?,
2792        );
2793    }
2794    // A producer that reads a name nothing binds carries on its wire only
2795    // the names the scope has, so its stream reads the others as None: the
2796    // program assembles again, from the compiler as it stood before, with
2797    // those streamers.
2798    if reads_none {
2799        let (restripped, _, _) = super::traversal::strip_for_forms(
2800            file,
2801            compiler.validation_mode(),
2802            &compiler.source_scope(),
2803            &mut Vec::new(),
2804            &|name| scope_names.iter().any(|n| n == name),
2805        )
2806        .map_err(KernelError::Source)?;
2807        parent_file = restripped;
2808        *compiler = stripped;
2809        compiler.producers_seen = producers.clone();
2810        asm = compiler
2811            .assemble_parent(&parent_file, filter)
2812            .map_err(KernelError::Source)?;
2813    }
2814    compiler.pending_events.extend(warnings);
2815    // The tiles typed while assembling belong to this program's log.
2816    if let Some(log) = log.as_deref_mut() {
2817        for e in compiler.pending_events.drain(..) {
2818            log.push(e);
2819        }
2820    }
2821    let mut built = build(asm, log.as_deref_mut())?;
2822    let kernel: &mut dyn crate::Kernel = built.kernel();
2823    if !for_stmts.is_empty() || !producers.is_empty() {
2824        let externs = kernel.externs();
2825        let inputs = kernel.input_names();
2826        let type_of = |name: &str| {
2827            kernel.output_type(name).or_else(|| {
2828                externs
2829                    .iter()
2830                    .find(|(n, _)| n == name)
2831                    .map(|(_, t)| *t)
2832                    .or_else(|| {
2833                        // A coordinate: the one input kind that is not an extern.
2834                        inputs
2835                            .iter()
2836                            .any(|n| n == name)
2837                            .then_some(crate::ast::PortType::U64)
2838                    })
2839            })
2840        };
2841        let traversals = compiler
2842            .compile_traversals(&for_stmts, &producers, &type_of)
2843            .map_err(KernelError::Source)?;
2844        crate::kernel::KernelInternals::set_traversals(kernel, traversals, producers);
2845        // Tiles inside the bodies, typed in the child compilers.
2846        if let Some(log) = log {
2847            for e in compiler.pending_events.drain(..) {
2848                log.push(e);
2849            }
2850        }
2851    }
2852    // A cursor whose range is computed from constants gets its extent
2853    // from the values the build folded, on every engine.
2854    for deferred in &compiler.deferred_extents {
2855        let start = kernel
2856            .folded_value(&deferred.start_output)
2857            .map(|v| v.as_u64());
2858        let end = kernel
2859            .folded_value(&deferred.end_output)
2860            .map(|v| v.as_u64());
2861        if let (Some(s), Some(e)) = (start, end) {
2862            let resolved = e.saturating_sub(s);
2863            let extent = compiler
2864                .cursor_limit
2865                .map(|limit| resolved.min(limit))
2866                .unwrap_or(resolved);
2867            if let Some(schema) = compiler.cursor_schemas.get_mut(deferred.schema_idx) {
2868                schema.extent = Some(extent);
2869            }
2870            kernel.set_cursor_extent(deferred.schema_idx, extent);
2871        }
2872    }
2873    Ok((built, parent_file))
2874}
2875
2876/// What a build hands back to the compile path: the interpreter's
2877/// concrete kernel or any engine's boxed one, each reachable as the one
2878/// trait the lowering drives.
2879trait Built {
2880    fn kernel(&mut self) -> &mut dyn crate::Kernel;
2881}
2882
2883impl Built for PolydatKernel {
2884    fn kernel(&mut self) -> &mut dyn crate::Kernel {
2885        self
2886    }
2887}
2888
2889impl Built for Box<dyn crate::Kernel> {
2890    fn kernel(&mut self) -> &mut dyn crate::Kernel {
2891        self.as_mut()
2892    }
2893}
2894
2895/// The kernel of a parsed file on `engine`: [`compile_file_with`] with
2896/// the engine's build, and the interpreter's concrete kernel boxed when
2897/// the engine is the interpreter.
2898pub(super) fn compile_file_on_engine(
2899    compiler: &mut Compiler,
2900    file: &PolydatFile,
2901    filter: Option<&[String]>,
2902    engine: crate::Engine,
2903    log: Option<&mut super::events::CompileEventLog>,
2904) -> Result<Box<dyn crate::Kernel>, crate::KernelError> {
2905    if let crate::Engine::Interpreter(cones) = engine {
2906        return compiler
2907            .compile_interpreter(file, filter, log, cones)
2908            .map(|k| Box::new(k) as Box<dyn crate::Kernel>);
2909    }
2910    let (kernel, _) = compile_file_with(compiler, file, filter, log, |asm, log| {
2911        asm.compile_engine_with_log(engine, log)
2912    })?;
2913    Ok(kernel)
2914}
2915// ── Former names of the interpreter-typed entry points ──────────────
2916//
2917// These returned the interpreter's concrete kernel under names that did
2918// not say so, which read as though they were the general way to compile
2919// under options. They are the exception, not the rule: a kernel is used
2920// through the `Kernel` trait, and the concrete type is for observing the
2921// interpreter's own internals in testing and diagnostics (engines.md
2922// §3.6). The names now say that; these keep the old ones working.
2923
2924#[cfg(test)]
2925mod tests {
2926    use super::*;
2927
2928    /// The interpreter kernel under `strict` alone.
2929    fn strict(src: &str, strict: bool) -> Result<PolydatKernel, crate::KernelError> {
2930        let options = CompileOptions {
2931            strict,
2932            ..CompileOptions::default()
2933        };
2934        compile_polydat_interpreter_with_options(src, &options, None)
2935    }
2936
2937    #[test]
2938    fn array_literal_binding_compiles_as_string() {
2939        // A list-valued binding (`const xs := [1, 2, 3]`) is a sweep
2940        // axis / interpolation value, not a scalar wire. polydat has no
2941        // const-vector node, so it binds to a `ConstStr` holding the
2942        // list's literal text rather than failing the compile — which
2943        // is what lets list-valued workload params (`limit_values:
2944        // [25]`) load.
2945        let result = compile_polydat_interpreter(
2946            "input cycle: u64\nconst eh_values := [1, 2, 3]\nout := cycle",
2947        );
2948        assert!(
2949            result.is_ok(),
2950            "array-literal binding should compile (binds as a string const), got: {:?}",
2951            result.err(),
2952        );
2953        // The resolved value is the comma-joined, bracket-free form a
2954        // sweep-axis param carries (so a `WorkloadParamList` source
2955        // splits it on `, ` exactly like a string-valued sweep param).
2956        let kernel = result.unwrap();
2957        match kernel.get_constant("eh_values") {
2958            Some(crate::ast::Value::Str(s)) => assert_eq!(s.as_ref(), "1, 2, 3"),
2959            other => panic!("expected eh_values = Str(\"1, 2, 3\"), got {other:?}"),
2960        }
2961    }
2962
2963    #[test]
2964    fn array_literal_in_argument_position_is_refused() {
2965        // The other half of the same rule: a list literal is a
2966        // binding-position form and has no meaning as a call argument
2967        // (polydat_grammar.md §18.1 T-ArrayLit). Lowered to a const
2968        // argument, nothing would read it, and the call would reach the
2969        // runtime with one wire input missing and panic there.
2970        let err = compile_polydat_interpreter("input cycle: u64\nout := printf(\"{}\", [1, 2])")
2971            .expect_err("a list literal in argument position is a compile error");
2972        let text = err.to_string();
2973        assert!(
2974            text.contains("binding-position form") && text.contains("printf"),
2975            "the error should name the form and the call: {text}",
2976        );
2977        // Bound first, the same list works, which is what the message
2978        // tells the author to do.
2979        let ok =
2980            compile_polydat_interpreter("input cycle: u64\nw := [1, 2]\nout := printf(\"{}\", w)");
2981        assert!(ok.is_ok(), "{:?}", ok.err());
2982    }
2983
2984    #[test]
2985    fn embedding_error_display_includes_source_text() {
2986        let e = EmbeddingError::LifecycleMismatch {
2987            source: "hash(cycle)".to_string(),
2988            dynamic_inputs: vec!["cycle".to_string()],
2989        };
2990        let s = format!("{e}");
2991        assert!(
2992            s.contains("hash(cycle)"),
2993            "display should include source: {s}"
2994        );
2995        assert!(
2996            s.contains("cycle"),
2997            "display should mention dynamic input: {s}"
2998        );
2999    }
3000
3001    #[test]
3002    fn embedding_error_from_string_shim() {
3003        let e = EmbeddingError::UnresolvedPlaceholder {
3004            name: "k".to_string(),
3005            source: "{k} > 5".to_string(),
3006        };
3007        let s: String = e.clone().into();
3008        assert_eq!(s, format!("{e}"));
3009    }
3010
3011    #[test]
3012    fn embedding_error_all_variants_display() {
3013        // Smoke test: every variant constructs and displays without panicking.
3014        let variants: Vec<EmbeddingError> = vec![
3015            EmbeddingError::Parse {
3016                source: "x +".into(),
3017                message: "unexpected EOF".into(),
3018                position: Some(3),
3019            },
3020            EmbeddingError::UnresolvedPlaceholder {
3021                name: "k".into(),
3022                source: "{k}".into(),
3023            },
3024            EmbeddingError::LifecycleMismatch {
3025                source: "hash(cycle)".into(),
3026                dynamic_inputs: vec!["cycle".into()],
3027            },
3028            EmbeddingError::UnknownNode {
3029                name: "frobnicate".into(),
3030                source: "frobnicate(x)".into(),
3031                suggestion: Some("fabricate".into()),
3032            },
3033            EmbeddingError::TypeMismatch {
3034                from_node: "n1".into(),
3035                from_type: crate::ast::PortType::U64,
3036                to_node: "n2".into(),
3037                to_type: crate::ast::PortType::Str,
3038                source: "n1 -> n2".into(),
3039            },
3040            EmbeddingError::NodeEvalPanic {
3041                node_name: "div".into(),
3042                message: "div by zero".into(),
3043                source: "div(a, b)".into(),
3044            },
3045            EmbeddingError::NonePropagated {
3046                accessor: "as_bool",
3047                source: "{missing}".into(),
3048            },
3049        ];
3050        for v in variants {
3051            let _ = format!("{v}");
3052        }
3053    }
3054
3055    #[test]
3056    fn typed_surface_string() {
3057        let v: String = eval_const_expr_typed("\"hello\"").unwrap();
3058        assert_eq!(v, "hello");
3059    }
3060
3061    #[test]
3062    fn typed_surface_type_mismatch() {
3063        // expression yields U64; host requests f64 — widening allowed
3064        let v: f64 = eval_const_expr_typed("42").unwrap();
3065        assert_eq!(v, 42.0);
3066        // expression yields U64; host requests bool — interpreted as bool (nonzero)
3067        let v: bool = eval_const_expr_typed("1").unwrap();
3068        assert!(v);
3069        let v: bool = eval_const_expr_typed("0").unwrap();
3070        assert!(!v);
3071    }
3072
3073    #[test]
3074    fn typed_surface_return_path_adapter() {
3075        // γ-6: expression produces U64; host requests String.
3076        // The catalog's U64ToString adapter heals the return-path.
3077        let v: String = eval_const_expr_typed("42").unwrap();
3078        assert_eq!(v, "42");
3079
3080        // Expression produces F64; host requests String via catalog
3081        // F64ToString. (Note: f64's Display is locale-independent
3082        // but format may add trailing zeros.)
3083        let v: String = eval_const_expr_typed("3.14").unwrap();
3084        assert!(v.starts_with("3.14"), "got {v}");
3085    }
3086
3087    #[test]
3088    fn typed_surface_return_path_no_adapter_errors() {
3089        // Bytes → Bool isn't in the catalog. Confirm the typed
3090        // error fires when the catalog can't heal.
3091        // (Need an expression producing Bytes; use a string-
3092        // literal-to-bytes conversion via bytes_of or similar
3093        // if available; otherwise use a roundtrip that fails.)
3094        //
3095        // Skipping concrete bytes producer for this test —
3096        // the contract is exercised by the negative path in
3097        // typed_surface_type_mismatch already.
3098    }
3099
3100    #[test]
3101    fn typed_strict_rejects_lossy_conversion() {
3102        // U64 → Bool is in the catalog (γ-6 added it) but
3103        // lossy. Strict mode must reject.
3104        let result: Result<bool, _> = eval_const_expr_typed_strict("42");
3105        match result {
3106            Err(EmbeddingError::TypeMismatch {
3107                from_type, to_type, ..
3108            }) => {
3109                assert!(matches!(from_type, crate::ast::PortType::U64));
3110                assert!(matches!(to_type, crate::ast::PortType::Bool));
3111            }
3112            other => panic!("expected TypeMismatch, got {other:?}"),
3113        }
3114    }
3115
3116    #[test]
3117    fn typed_strict_accepts_lossless_conversion() {
3118        // U64 → String via display — lossless.
3119        let v: String = eval_const_expr_typed_strict("42").unwrap();
3120        assert_eq!(v, "42");
3121
3122        // Same type, no adapter.
3123        let v: f64 = eval_const_expr_typed_strict("42.0").unwrap();
3124        assert_eq!(v, 42.0);
3125    }
3126
3127    /// Strict mode answers about the types, not about the one value
3128    /// in hand: `U64 → F64` is refused because `u64` has 64 magnitude
3129    /// bits and `f64`'s significand holds 53, so values above `2^53`
3130    /// round. A host that wants the number as an `f64` writes it as
3131    /// one. The type-level answer is the same for every input, which
3132    /// a value-level one would not be.
3133    #[test]
3134    fn typed_strict_refuses_a_widening_that_rounds() {
3135        let r: Result<f64, _> = eval_const_expr_typed_strict("42");
3136        assert!(
3137            matches!(r, Err(EmbeddingError::TypeMismatch { .. })),
3138            "{r:?}"
3139        );
3140        assert!(!is_lossless_adapter(
3141            crate::ast::PortType::U64,
3142            crate::ast::PortType::F64
3143        ));
3144        assert!(!is_lossless_adapter(
3145            crate::ast::PortType::I64,
3146            crate::ast::PortType::F64
3147        ));
3148        // The narrow integers do fit, which the old eleven-pair
3149        // table did not say.
3150        for from in [
3151            crate::ast::PortType::U8,
3152            crate::ast::PortType::U16,
3153            crate::ast::PortType::U32,
3154        ] {
3155            assert!(
3156                is_lossless_adapter(from, crate::ast::PortType::U64),
3157                "{from:?} → U64"
3158            );
3159            assert!(
3160                is_lossless_adapter(from, crate::ast::PortType::F64),
3161                "{from:?} → F64"
3162            );
3163        }
3164        // Signed never fits unsigned, however wide.
3165        assert!(!is_lossless_adapter(
3166            crate::ast::PortType::I8,
3167            crate::ast::PortType::U128
3168        ));
3169    }
3170
3171    #[test]
3172    fn shared_computed_start_over_a_coordinate_is_refused() {
3173        // A computed starting value is evaluated once, at
3174        // initialization, so it may not read a coordinate.
3175        let src = r#"
3176            input cycle: u64
3177            shared rolling := hash(cycle)
3178        "#;
3179        let err = compile_polydat_interpreter(src)
3180            .expect_err("a starting value over a coordinate must error");
3181        assert!(
3182            err.to_string().contains("shared 'rolling'")
3183                && err.to_string().contains("coordinate 'cycle'"),
3184            "error: {err}"
3185        );
3186    }
3187
3188    #[test]
3189    fn shared_computed_start_is_seeded_at_init() {
3190        let src = r#"
3191            input cycle: u64
3192            extern base: u64 = 20
3193            shared rolling := u64_add(base, base)
3194        "#;
3195        let k = compile_polydat_interpreter(src).expect("a computed start compiles");
3196        assert_eq!(k.lookup("rolling"), Some(crate::ast::Value::U64(40)));
3197    }
3198
3199    #[test]
3200    fn shared_const_is_refused() {
3201        let err = compile_polydat_interpreter("shared const x := 1\n")
3202            .expect_err("`shared const` must error");
3203        assert!(
3204            err.to_string().contains("const") && err.to_string().contains("shared"),
3205            "error: {err}"
3206        );
3207    }
3208
3209    #[test]
3210    fn final_modifier_tracked() {
3211        let src = r#"
3212            input cycle: u64
3213            const dim := 128
3214        "#;
3215        let kernel = compile_polydat_interpreter(src).unwrap();
3216        assert_eq!(
3217            kernel.program().output_modifier("dim"),
3218            crate::dsl::ast::BindingModifier::CONST
3219        );
3220    }
3221
3222    #[test]
3223    fn shared_literal_modifier_tracked() {
3224        let src = r#"
3225            input cycle: u64
3226            shared budget := 100
3227        "#;
3228        let kernel = compile_polydat_interpreter(src).unwrap();
3229        assert_eq!(
3230            kernel.program().output_modifier("budget"),
3231            crate::dsl::ast::BindingModifier::SHARED
3232        );
3233        // Shared cells back the output via a port-passthrough node
3234        // reading the input slot; `lookup` is the cell-aware read.
3235        assert_eq!(kernel.lookup("budget").unwrap().as_u64(), 100);
3236    }
3237
3238    #[test]
3239    fn const_literal_modifier_tracked() {
3240        let src = r#"
3241            input cycle: u64
3242            const max_dim := 256
3243        "#;
3244        let kernel = compile_polydat_interpreter(src).unwrap();
3245        assert_eq!(
3246            kernel.program().output_modifier("max_dim"),
3247            crate::dsl::ast::BindingModifier::CONST
3248        );
3249        assert_eq!(kernel.get_constant("max_dim").unwrap().as_u64(), 256);
3250    }
3251
3252    #[test]
3253    fn compile_string_constant() {
3254        let src = r#"
3255            input cycle: u64
3256            label := "hello world"
3257        "#;
3258        let mut kernel = compile_polydat_interpreter(src).unwrap();
3259        kernel.set_inputs(&[0]);
3260        assert_eq!(kernel.pull_ref("label").as_str(), "hello world");
3261    }
3262
3263    #[test]
3264    fn compile_int_constant() {
3265        let src = r#"
3266            input cycle: u64
3267            base := 1710000000000
3268        "#;
3269        let mut kernel = compile_polydat_interpreter(src).unwrap();
3270        kernel.set_inputs(&[0]);
3271        assert_eq!(kernel.pull_ref("base").as_u64(), 1_710_000_000_000);
3272    }
3273
3274    // --- Diagnostic tests ---
3275
3276    #[test]
3277    fn error_unknown_function() {
3278        let src = "input cycle: u64\nresult := foobar(cycle)";
3279        let (_result, report) = compile_polydat_checked(src);
3280        assert!(report.has_errors());
3281        let errors = report.errors();
3282        assert!(
3283            errors
3284                .iter()
3285                .any(|e| e.message.contains("unknown function"))
3286        );
3287        assert!(errors.iter().any(|e| e.message.contains("foobar")));
3288    }
3289
3290    #[test]
3291    fn explicit_coordinates_rejects_unbound() {
3292        // With explicit coordinates, unbound references are errors
3293        let src = "input cycle: u64\nh := hash(unknown)";
3294        let (_, report) = compile_polydat_checked(src);
3295        assert!(report.has_errors());
3296        assert!(
3297            report
3298                .errors()
3299                .iter()
3300                .any(|e| e.message.contains("undefined") && e.message.contains("unknown"))
3301        );
3302    }
3303
3304    #[test]
3305    fn warning_forward_reference() {
3306        let src = r#"
3307            input cycle: u64
3308            result := mod(h, 100)
3309            h := hash(cycle)
3310        "#;
3311        let (_, report) = compile_polydat_checked(src);
3312        let warnings = report.warnings();
3313        assert!(
3314            warnings
3315                .iter()
3316                .any(|w| w.message.contains("forward reference")),
3317            "should warn about forward ref, got: {:?}",
3318            warnings
3319        );
3320    }
3321
3322    #[test]
3323    fn error_undefined_wire() {
3324        let src = r#"
3325            input cycle: u64
3326            result := hash(nonexistent)
3327        "#;
3328        let (_, report) = compile_polydat_checked(src);
3329        assert!(report.has_errors());
3330        assert!(
3331            report
3332                .errors()
3333                .iter()
3334                .any(|e| e.message.contains("undefined") && e.message.contains("nonexistent"))
3335        );
3336    }
3337
3338    #[test]
3339    fn error_report_includes_source_line() {
3340        let src = "input cycle: u64\nresult := unknown_func(cycle)";
3341        let (_, report) = compile_polydat_checked(src);
3342        let s = report.to_string();
3343        assert!(
3344            s.contains("unknown_func"),
3345            "report should include source context"
3346        );
3347    }
3348
3349    // --- Strict mode tests ---
3350
3351    #[test]
3352    fn strict_requires_explicit_inputs() {
3353        // Without inputs declaration, strict mode should error
3354        let src = "h := hash(cycle)";
3355        let result = strict(src, true);
3356        assert!(result.is_err());
3357        let err = result.unwrap_err();
3358        assert!(
3359            err.to_string().contains("strict mode"),
3360            "expected strict error, got: {err}"
3361        );
3362        assert!(
3363            err.to_string().contains("inputs"),
3364            "expected inputs mention, got: {err}"
3365        );
3366    }
3367
3368    // --- Dead code elimination tests ---
3369
3370    // --- Strict mode comprehensive tests ---
3371
3372    // --- eval_const_expr tests ---
3373
3374    #[test]
3375    fn eval_const_expr_fails_on_inputs() {
3376        // 'cycle' is a runtime input — should fail as const expr
3377        let r = eval_const_expr("hash(cycle)");
3378        assert!(r.is_err(), "hash(cycle) should fail as a const expression");
3379    }
3380
3381    // ─────────────────────────────────────────────────────────────
3382    // The const contract (evaluation_model.md, "Const Binding
3383    // Contract"): a literal const folds at build; any other const is
3384    // evaluated when its kernel is initialized. A const that reads a
3385    // coordinate is a compile error.
3386    // ─────────────────────────────────────────────────────────────
3387
3388    #[test]
3389    fn init_binding_compile_const_folded() {
3390        // Pure init: literal arg, no externs. Folds at compile
3391        // time; the compiled program's output_map points at a
3392        // ConstU64 leaf.
3393        let src = "const dim := 128\n";
3394        let kernel = compile_polydat_interpreter(src).expect("init compile-const");
3395        let prog = kernel.program();
3396        assert!(prog.const_outputs().contains(&"dim"));
3397        let &(node_idx, _) = prog.output_map_lookup("dim").expect("dim in output map");
3398        // After fold, the node has empty wiring (leaf const).
3399        assert!(
3400            prog.wiring[node_idx].is_empty(),
3401            "compile-const init binding 'dim' must fold to a leaf const node"
3402        );
3403    }
3404
3405    #[test]
3406    fn a_const_over_an_extern_is_evaluated_at_init() {
3407        // A const over an extern compiles and is evaluated when the
3408        // kernel is initialized, from the extern's value then.
3409        let src = "extern profile: str = \"p1\"\n\
3410                   const label := \"label_{profile}\"\n";
3411        let mut k = compile_polydat_interpreter(src).expect("a const may read an extern");
3412        assert_eq!(k.pull_ref("label").as_str(), "label_p1");
3413    }
3414
3415    #[test]
3416    fn a_const_over_a_volatile_source_captures_it_at_init() {
3417        // A const over a nondeterministic source is evaluated once, when
3418        // the kernel is initialized, and holds that value until `init`
3419        // runs again; every other read of the source re-reads it.
3420        let src = "const first := counter()\nnow := counter()\n";
3421        let mut k = compile_polydat_interpreter(src).expect("a const may capture a volatile value");
3422        let captured = k.pull_ref("first").as_u64();
3423        let _ = k.pull_ref("now");
3424        let _ = k.pull_ref("now");
3425        assert_eq!(
3426            k.pull_ref("first").as_u64(),
3427            captured,
3428            "reads do not re-evaluate a const"
3429        );
3430        crate::kernel::Kernel::init(&mut k).expect("re-initialize");
3431        assert_ne!(
3432            k.pull_ref("first").as_u64(),
3433            captured,
3434            "init evaluates the const again"
3435        );
3436    }
3437
3438    #[test]
3439    fn init_outputs_threaded_into_program() {
3440        // Sanity: the compiler records every `init`-declared name
3441        // on the program's const outputs so the executor can walk
3442        // them at scope activation.
3443        let src = "const a := 1\n\
3444                   const b := 2\n\
3445                   c := 3\n";
3446        let kernel = compile_polydat_interpreter(src).unwrap();
3447        let init_set = kernel.program().const_outputs();
3448        assert!(init_set.contains(&"a"), "const 'a' should be tracked");
3449        assert!(init_set.contains(&"b"), "const 'b' should be tracked");
3450        assert!(
3451            !init_set.contains(&"c"),
3452            "non-const 'c' must not be tracked"
3453        );
3454    }
3455
3456    /// Auto-extern slots inferred from RHS shape land at the
3457    /// boundary with their actual type (Str / U64 / F64 / Bool)
3458    /// rather than the `PortType::Ext` catchall, so workloads that
3459    /// use `set:` blocks with iter-var interpolation meet no
3460    /// `U64 → Ext` boundary-adapter miss.
3461    ///
3462    /// Test path: declare an iteration extern explicitly with
3463    /// `extern N: str` (no default → `IterationExtern` kind,
3464    /// effectively-const at scope-init); reference it from a
3465    /// const RHS. The const target then needs an auto-extern
3466    /// slot (RHS has a ref), and the inferrer picks the
3467    /// referenced input's type.
3468    #[test]
3469    fn auto_extern_slot_inherits_string_template_type() {
3470        let src = r#"
3471            extern some_outer_var: str
3472            const x := "{some_outer_var}"
3473        "#;
3474        let kernel = compile_polydat_interpreter(src).expect("compile");
3475        assert_eq!(
3476            kernel.program().input_port_type("x"),
3477            Some(crate::ast::PortType::Str),
3478            "string-template auto-extern MUST be Str, not Ext",
3479        );
3480    }
3481
3482    /// Identifier reference auto-extern inherits the referenced
3483    /// input's type. `const y := other_str_input` → y is Str.
3484    #[test]
3485    fn auto_extern_slot_inherits_ident_reference_type() {
3486        let src = r#"
3487            extern other: str
3488            const y := other
3489        "#;
3490        let kernel = compile_polydat_interpreter(src).expect("compile");
3491        assert_eq!(
3492            kernel.program().input_port_type("y"),
3493            Some(crate::ast::PortType::Str),
3494            "ident-RHS auto-extern MUST inherit referenced input's type",
3495        );
3496    }
3497
3498    /// `dataset_prebuffer(...)` returns `Value::Handle` — the
3499    /// auto-extern slot for `const prebuffered := dataset_prebuffer(...)`
3500    /// MUST be `PortType::Handle`, not the `Ext` catchall.
3501    /// (`dataset_prebuffer` is a vectordata node, so the test only
3502    /// exists when that feature registers it.)
3503    #[cfg(feature = "vectordata")]
3504    #[test]
3505    fn auto_extern_slot_for_dataset_prebuffer_is_handle() {
3506        let src = r#"
3507            extern source_uri: str
3508            const prebuffered := dataset_prebuffer(source_uri)
3509        "#;
3510        let kernel = compile_polydat_interpreter(src).expect("compile");
3511        assert_eq!(
3512            kernel.program().input_port_type("prebuffered"),
3513            Some(crate::ast::PortType::Handle),
3514            "dataset_prebuffer auto-extern MUST be Handle, not Ext",
3515        );
3516    }
3517}