Skip to main content

polydat_core/compile/
assembly.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Programmatic assembly API for building Polydat Kernels.
5//!
6//! The assembler validates wiring and types, auto-inserts edge adapters,
7//! topologically sorts nodes, and builds a kernel on any engine: a host
8//! adds nodes and wires (or takes the assembler the DSL built from
9//! source) and calls [`PolydatAssembler::compile_kernel`] for the default
10//! engine, [`PolydatAssembler::compile_with`] for a named one, or
11//! [`PolydatAssembler::compile`] for the interpreter kernel as a concrete
12//! type. The `try_compile*` constructors build one engine's kernel as its
13//! concrete type for the differential suites and the ladder.
14
15use std::collections::HashMap;
16
17use crate::ast::SlotShape;
18use crate::ast::{PolydatNode, PortType};
19use crate::compile::closures::{
20    CompiledKernelPull, CompiledKernelPush, CompiledKernelPushPull, CompiledKernelRaw,
21};
22use crate::compile::select::{self, ProvMode};
23use crate::kernel::{PolydatKernel, PolydatProgram, WireSource};
24use crate::library::convert::{F64ToString, U64ToF64, U64ToString};
25use crate::library::json::JsonToStr;
26
27/// A reference to a value in the assembler: either a coordinate or a
28/// node output port.
29#[derive(Debug, Clone)]
30pub enum WireRef {
31    /// A graph input, by name.
32    Input(String),
33    /// A node output: `(node_name, output_port_index)`.
34    Node(String, usize),
35}
36
37impl WireRef {
38    /// Convenience: reference the first (or only) output of a named node.
39    pub fn node(name: impl Into<String>) -> Self {
40        WireRef::Node(name.into(), 0)
41    }
42
43    /// Reference a specific output port of a named node.
44    pub fn node_port(name: impl Into<String>, port: usize) -> Self {
45        WireRef::Node(name.into(), port)
46    }
47
48    /// Reference a graph input by name.
49    pub fn input(name: impl Into<String>) -> Self {
50        WireRef::Input(name.into())
51    }
52}
53
54struct PendingNode {
55    name: String,
56    node: Box<dyn PolydatNode>,
57    inputs: Vec<WireRef>,
58    /// Whether the scope the node was written in has `strict_values`
59    /// on, when that scope is not the program's own: `Some` for a node
60    /// of a module body, which decides for the node whatever the
61    /// program's pragmas say, and `None` for a node of the program,
62    /// which follows the program's set (polydat_grammar.md §14).
63    strict_values: Option<bool>,
64}
65
66/// Errors that can occur during assembly.
67#[derive(Debug)]
68pub enum AssemblyError {
69    /// A wire reference names no node output or input.
70    UnknownWire(String),
71    /// A wire's type does not match the port it feeds and no adapter heals it.
72    TypeMismatch {
73        /// The producing node.
74        from_node: String,
75        /// Its output port index.
76        from_port: usize,
77        /// The output's type.
78        from_type: PortType,
79        /// The consuming node.
80        to_node: String,
81        /// Its input port index.
82        to_port: usize,
83        /// The type the port requires.
84        to_type: PortType,
85    },
86    /// Two nodes were added under one name.
87    DuplicateNode(String),
88    /// The wiring has a cycle.
89    CycleDetected,
90    /// A node was wired with the wrong number of inputs.
91    ArityMismatch {
92        /// The node.
93        node_name: String,
94        /// Inputs its signature takes.
95        expected: usize,
96        /// Inputs it was given.
97        got: usize,
98    },
99    /// A compile-constant step could not be computed; see
100    /// [`KernelError::ConstantFold`], which this becomes at the kernel
101    /// boundary. Carried here so the interpreter's build path, which
102    /// speaks `AssemblyError`, reports the same kind as the compiled
103    /// engines do rather than folding it into `Other`.
104    ConstantFold(String),
105    /// A `const` binding could not be computed when the kernel was
106    /// initialized; see [`KernelError::ConstInit`], which this becomes at
107    /// the kernel boundary.
108    ConstInit {
109        /// The const.
110        name: String,
111        /// Why its expression failed, as the node reported it.
112        reason: String,
113    },
114    /// `CompileOptions::input_variance` is `Error` and these inputs'
115    /// types were inferred rather than declared, as `(name, inferred
116    /// type)` (input_variance.md §4).
117    OpenInputs(Vec<(String, PortType)>),
118    /// Native code generation failed for an interpreter cone under
119    /// `JitMode::Force`, which builds native code or fails (engines.md
120    /// §2.1).
121    NativeCone {
122        /// The cone's label, naming its members.
123        cone: String,
124        /// The code generator's error text.
125        reason: String,
126    },
127    /// Catch-all for errors from downstream phases (e.g., strict mode).
128    Other(String),
129}
130
131impl std::fmt::Display for AssemblyError {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        match self {
134            AssemblyError::UnknownWire(name) => {
135                write!(f, "unknown wire: '{name}'\n\n")?;
136                writeln!(f, "  No node output or coordinate named '{name}' exists.")?;
137                write!(
138                    f,
139                    "  Check spelling, or add a node that produces this output."
140                )
141            }
142            AssemblyError::TypeMismatch {
143                from_node,
144                from_port,
145                from_type,
146                to_node,
147                to_port,
148                to_type,
149            } => {
150                writeln!(
151                    f,
152                    "type mismatch: cannot connect {from_type} output to {to_type} input"
153                )?;
154                writeln!(f)?;
155                writeln!(
156                    f,
157                    "  {from_node} [{from_port}]  ──({from_type})──▶  {to_node} [{to_port}] expects {to_type}"
158                )?;
159                writeln!(f)?;
160                // Suggest auto-adapters that exist
161                let suggestion = match (from_type, to_type) {
162                    (PortType::U64, PortType::Str) => {
163                        Some("This should auto-convert. If you see this, file a bug.")
164                    }
165                    (PortType::F64, PortType::Str) => {
166                        Some("This should auto-convert. If you see this, file a bug.")
167                    }
168                    (PortType::U64, PortType::F64) => {
169                        Some("This should auto-convert. If you see this, file a bug.")
170                    }
171                    (PortType::U64, PortType::Bytes) => {
172                        Some("Add u64_to_bytes() between them to convert.")
173                    }
174                    (PortType::Str, PortType::Bytes) => {
175                        Some("String cannot be directly used as bytes.")
176                    }
177                    (PortType::U64, PortType::Json) => {
178                        Some("Add to_json() between them to wrap as JSON.")
179                    }
180                    (PortType::Str, PortType::Json) => {
181                        Some("Add str_to_json() to parse the string as JSON.")
182                    }
183                    (PortType::Bytes, PortType::Str) => {
184                        Some("Add to_hex() or to_base64() to convert bytes to string.")
185                    }
186                    (PortType::Bytes, PortType::U64) => {
187                        Some("Bytes cannot be directly converted to u64.")
188                    }
189                    _ => None,
190                };
191                if let Some(hint) = suggestion {
192                    write!(f, "  Hint: {hint}")?;
193                }
194                Ok(())
195            }
196            AssemblyError::DuplicateNode(name) => {
197                write!(f, "duplicate node name: '{name}'\n\n")?;
198                write!(f, "  Two nodes cannot share the same name.")
199            }
200            AssemblyError::CycleDetected => {
201                write!(f, "cycle detected in DAG\n\n")?;
202                writeln!(
203                    f,
204                    "  The graph contains a loop. Polydat graphs must be acyclic"
205                )?;
206                write!(f, "  (data flows in one direction only).")
207            }
208            AssemblyError::ArityMismatch {
209                node_name,
210                expected,
211                got,
212            } => {
213                write!(f, "wrong number of inputs for '{node_name}'\n\n")?;
214                writeln!(f, "  Expected {expected} input(s), but got {got}.")?;
215                if *got < *expected {
216                    write!(f, "  Connect more wires to this node's input ports.")
217                } else {
218                    write!(f, "  Disconnect extra wires from this node.")
219                }
220            }
221            AssemblyError::ConstantFold(msg) => write!(
222                f,
223                "a value this program computes at build could not be computed: {msg}"
224            ),
225            AssemblyError::ConstInit { name, reason } => write!(
226                f,
227                "the const '{name}' could not be computed when the kernel was initialized: {reason}"
228            ),
229            AssemblyError::OpenInputs(inputs) => {
230                writeln!(
231                    f,
232                    "these inputs' types were inferred, not declared, and input variance \
233                     is set to refuse them:"
234                )?;
235                for (name, ty) in inputs {
236                    writeln!(f, "  {name} (inferred {ty})")?;
237                }
238                write!(
239                    f,
240                    "Declare each one's type (`extern name: <type>`), or set \
241                     `input_variance` to `Warn` or `Info` to convert what is written to them."
242                )
243            }
244            AssemblyError::NativeCone { cone, reason } => write!(
245                f,
246                "native code generation failed for cone {cone} under JitMode::Force: {reason}"
247            ),
248            AssemblyError::Other(msg) => write!(f, "{msg}"),
249        }
250    }
251}
252
253impl std::error::Error for AssemblyError {}
254
255/// The dataset forms every named output of `resolved` can depend on
256/// ([`crate::kernel::PolydatProgram::dataset_sources`]), for a compiled
257/// kernel to answer as the interpreter does. A program with no `forms`
258/// or `fragment` wire has nothing to find and is not walked.
259fn dataset_sources_of_outputs(
260    resolved: &ResolvedDag,
261) -> HashMap<String, crate::kernel::DatasetSources> {
262    let carries_datasets = |typ: PortType| matches!(typ, PortType::Forms | PortType::Fragment);
263    let any = resolved.nodes.iter().any(|node| {
264        node.meta()
265            .outs
266            .iter()
267            .any(|port| carries_datasets(port.typ))
268    }) || resolved
269        .input_defs
270        .iter()
271        .any(|input| carries_datasets(input.port_type));
272    resolved
273        .output_map
274        .iter()
275        .map(|(name, (node, _))| {
276            let sources = if any {
277                crate::kernel::dataset_sources_of(
278                    &resolved.nodes,
279                    &resolved.wiring,
280                    &resolved.input_defs,
281                    *node,
282                )
283            } else {
284                Default::default()
285            };
286            (name.clone(), sources)
287        })
288        .collect()
289}
290
291/// Validated, topologically sorted intermediate form.
292pub(crate) struct ResolvedDag {
293    /// Nodes in topological order.
294    pub(crate) nodes: Vec<Box<dyn PolydatNode>>,
295    /// Per-node wiring (in topological order).
296    pub(crate) wiring: Vec<Vec<WireSource>>,
297    /// All input definitions (coordinates + captures).
298    pub(crate) input_defs: Vec<crate::kernel::InputDef>,
299    /// Number of coordinate inputs.
300    pub(crate) coord_count: usize,
301    /// Output name → (node_index_in_sorted, output_port_index).
302    pub(crate) output_map: HashMap<String, (usize, usize)>,
303    /// Output names in declaration order.
304    pub(crate) output_order: Vec<String>,
305    /// Source text for diagnostics.
306    pub(crate) source: String,
307    /// Diagnostic context.
308    pub(crate) context: String,
309    /// Output binding modifiers.
310    pub(crate) output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
311    /// Names declared with `const` (evaluation_model.md §"Const Binding
312    /// Contract").
313    pub(crate) const_outputs: std::collections::HashSet<String>,
314    /// The const bindings a kernel initializes, in dependency order.
315    pub(crate) const_inits: Vec<crate::kernel::ConstInit>,
316    /// The cursors the program declares.
317    pub(crate) cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
318    /// The compile ledger every program built from this graph records in.
319    pub(crate) ledger: std::sync::Arc<crate::kernel::CompileLedger>,
320    /// The resource scope of the tree every program built from this
321    /// graph belongs to.
322    pub(crate) resources: crate::resource::ResourceScope,
323}
324
325impl ResolvedDag {
326    /// Coordinate input names (for P2/P3 kernels that use positional u64 buffers).
327    fn input_names(&self) -> Vec<String> {
328        self.input_defs[..self.coord_count]
329            .iter()
330            .map(|d| d.name.clone())
331            .collect()
332    }
333
334    /// The digest of this graph's identity (scope_model.md §8), taken
335    /// before any engine folds or fuses it, so every engine's kernel
336    /// reports the same canonical hash.
337    pub(crate) fn graph_identity(&self) -> [u8; 32] {
338        crate::kernel::IdentityGraph {
339            nodes: &self.nodes,
340            wiring: &self.wiring,
341            input_defs: &self.input_defs,
342            outputs: self
343                .output_map
344                .iter()
345                .map(|(n, &(ni, pi))| (n.as_str(), ni, pi))
346                .collect(),
347            output_modifiers: &self.output_modifiers,
348            const_outputs: &self.const_outputs,
349        }
350        .digest()
351    }
352}
353
354/// Per-port slot layout for compiled kernels
355/// (type_system_alignment.md §6). Each port occupies
356/// `PortType::slot_width()` consecutive buffer slots: an immediate
357/// is one slot; a 128-bit value or a `Ref2` pair is two.
358struct SlotLayout {
359    /// Per kernel input: first slot index.
360    input_starts: Vec<usize>,
361    /// Total slots occupied by kernel inputs.
362    coord_slots: usize,
363    /// Per node, per output port: first slot index.
364    port_offsets: Vec<Vec<usize>>,
365    /// Total buffer length.
366    total_slots: usize,
367}
368
369fn slot_layout(resolved: &ResolvedDag) -> SlotLayout {
370    let mut input_starts = Vec::with_capacity(resolved.coord_count);
371    let mut next = 0usize;
372    for d in &resolved.input_defs {
373        input_starts.push(next);
374        next += d.port_type.slot_width();
375    }
376    let coord_slots = next;
377    let mut port_offsets: Vec<Vec<usize>> = Vec::with_capacity(resolved.nodes.len());
378    for node in &resolved.nodes {
379        let mut po = Vec::with_capacity(node.meta().outs.len());
380        for out in &node.meta().outs {
381            po.push(next);
382            next += out.typ.slot_width();
383        }
384        port_offsets.push(po);
385    }
386    SlotLayout {
387        input_starts,
388        coord_slots,
389        port_offsets,
390        total_slots: next,
391    }
392}
393
394/// Compiled-op selection for one node: a copy step inline, then the
395/// pure-scalar `compiled_u64` (cheapest dispatch), then the slot kit
396/// for every other shape (type_system_alignment.md §4,
397/// compiled_handles.md §3), else `None` → typed-eval
398/// fallback. `wire_types` is the type of each wire input.
399fn node_step_op(
400    node: &dyn crate::ast::PolydatNode,
401    wire_types: &[PortType],
402) -> Option<(
403    crate::compile::closures::StepOp,
404    Vec<crate::ast::ScratchElem>,
405)> {
406    // A plain copy (`identity`, a `__port_` passthrough): an inline
407    // slot copy of an immediate; a `Ref2` value is copied into the
408    // step's own scratch, since a pair is never forwarded (axiom S3).
409    let meta = node.meta();
410    if (meta.name == "identity" || meta.name.starts_with("__port_")) && meta.outs.len() == 1 {
411        return Some(match meta.outs[0].typ.slot_color() {
412            crate::ast::SlotColor::Ref2 => {
413                let kit = ref_copy_kit(meta.outs[0].typ)?;
414                (crate::compile::closures::StepOp::Slot(kit.op), kit.scratch)
415            }
416            _ => (crate::compile::closures::StepOp::Copy, Vec::new()),
417        });
418    }
419    if let Some(op) = node.compiled_u64() {
420        return Some((crate::compile::closures::StepOp::U64(op), Vec::new()));
421    }
422    node.compiled_slot(
423        wire_types,
424        crate::compile::select::Engine::Closures(crate::compile::select::Provenance::Auto),
425    )
426    .map(|kit| (crate::compile::closures::StepOp::Slot(kit.op), kit.scratch))
427}
428
429/// Axiom S9(a): the `(first slot, scratch index)` pairs of a step's
430/// scratch-backed `Ref2` outputs. A kit's scratch entries pair with
431/// the step's `Ref2` output ports in port order, skipping the entries
432/// that publish no pair (a native cone's slot buffer, a render's body
433/// kernels, a node's own state); a `Ref2` output beyond the kit's publishing entries is
434/// not scratch-backed (a pair into interned bytes) and is validated by
435/// nothing. `base` is the index of the kit's first entry in the
436/// kernel's scratch. A kit with more publishing entries than the step
437/// has `Ref2` outputs is a macro or builder bug, caught at
438/// construction (axiom S3).
439pub(crate) fn scratch_pairs(
440    name: &str,
441    ref_starts: &[usize],
442    scratch: &[crate::ast::ScratchElem],
443    base: usize,
444) -> Vec<(usize, usize)> {
445    use crate::ast::ScratchElem;
446    let publishing: Vec<usize> = scratch
447        .iter()
448        .enumerate()
449        .filter(|(_, e)| {
450            !matches!(
451                e,
452                ScratchElem::Slots | ScratchElem::Kernels | ScratchElem::State
453            )
454        })
455        .map(|(k, _)| base + k)
456        .collect();
457    assert!(
458        publishing.len() <= ref_starts.len(),
459        "slot-op step '{name}' declares {} publishing scratch entries for {} Ref output ports",
460        publishing.len(),
461        ref_starts.len()
462    );
463    ref_starts.iter().copied().zip(publishing).collect()
464}
465
466/// The compiled form of a copy of a `Ref2` value (`identity`, the
467/// compiler's `__port_<name>` passthrough, a type assertion): the pair
468/// is never forwarded (axiom S3), so the elements are copied into this
469/// step's own scratch entry and its pair is published. `None` for an
470/// immediate color, which is copied inline.
471pub(crate) fn ref_copy_kit(ty: PortType) -> Option<crate::ast::CompiledSlotKit> {
472    use crate::ast::ScratchBuf;
473    let elem = ty.scratch_elem()?;
474    Some(crate::ast::CompiledSlotKit {
475        scratch: vec![elem],
476        op: Box::new(
477            move |inputs: &[u64], outputs: &mut [u64], scratch: &mut [ScratchBuf]| {
478                let (p, n) = (inputs[0] as usize, inputs[1] as usize);
479                macro_rules! copy_into {
480                    ($v:expr, $t:ty) => {{
481                        $v.clear();
482                        // SAFETY: the pair was published by the producing
483                        // step into storage alive until it reruns (axioms
484                        // S3, S4), and the layout typed it `$t`.
485                        $v.extend_from_slice(unsafe {
486                            std::slice::from_raw_parts(p as *const $t, n)
487                        });
488                    }};
489                }
490                match &mut scratch[0] {
491                    ScratchBuf::Str(v) | ScratchBuf::Bytes(v) => copy_into!(v, u8),
492                    ScratchBuf::F32(v) => copy_into!(v, f32),
493                    ScratchBuf::F64(v) => copy_into!(v, f64),
494                    ScratchBuf::F16(v) => copy_into!(v, half::f16),
495                    ScratchBuf::I8(v) => copy_into!(v, i8),
496                    ScratchBuf::I16(v) => copy_into!(v, i16),
497                    ScratchBuf::I32(v) => copy_into!(v, i32),
498                    ScratchBuf::I64(v) => copy_into!(v, i64),
499                    ScratchBuf::Value(v) => {
500                        v.clear();
501                        if n > 0 {
502                            // SAFETY: as above; a value pair names one `Value`.
503                            v.push(unsafe { (*(p as *const crate::ast::Value)).clone() });
504                        }
505                    }
506                    ScratchBuf::Slots(_) | ScratchBuf::Kernels(_) | ScratchBuf::State(_) => {
507                        unreachable!("a copy owns only a value entry")
508                    }
509                }
510                let (ptr, len) = scratch[0].ptr_len();
511                outputs[0] = ptr;
512                outputs[1] = len;
513            },
514        ),
515    })
516}
517
518/// The compiled form of `identity`, synthesized by the builder: a slot
519/// copy, for every port color except `Ref2`, which
520/// [`ref_copy_kit`] carries. The node itself is polymorphic over
521/// `Value` and so has no kit of its own; the builder knows the
522/// resolved port type and can supply one.
523pub(crate) fn identity_op(node: &dyn crate::ast::PolydatNode) -> Option<crate::ast::CompiledU64Op> {
524    let meta = node.meta();
525    if meta.name != "identity" || meta.outs.len() != 1 {
526        return None;
527    }
528    if meta.outs[0].typ.slot_color() == crate::ast::SlotColor::Ref2 {
529        return None;
530    }
531    Some(Box::new(|inputs: &[u64], outputs: &mut [u64]| {
532        outputs.copy_from_slice(inputs)
533    }))
534}
535
536impl SlotLayout {
537    /// Flattened input slot list for one node: every wire source
538    /// contributes its full width, in port order.
539    fn input_slots(&self, resolved: &ResolvedDag, node_idx: usize) -> Vec<usize> {
540        let mut slots = Vec::new();
541        for source in &resolved.wiring[node_idx] {
542            let (start, w) = match source {
543                WireSource::Input(c) => (
544                    self.input_starts.get(*c).copied().unwrap_or(*c),
545                    resolved
546                        .input_defs
547                        .get(*c)
548                        .map(|d| d.port_type.slot_width())
549                        .unwrap_or(1),
550                ),
551                WireSource::NodeOutput(u, p) => (
552                    self.port_offsets[*u][*p],
553                    resolved.nodes[*u].meta().outs[*p].typ.slot_width(),
554                ),
555            };
556            slots.extend(start..start + w);
557        }
558        slots
559    }
560
561    /// Flattened output slot list for one node.
562    fn output_slots(&self, resolved: &ResolvedDag, node_idx: usize) -> Vec<usize> {
563        let mut slots = Vec::new();
564        for (p, out) in resolved.nodes[node_idx].meta().outs.iter().enumerate() {
565            let start = self.port_offsets[node_idx][p];
566            slots.extend(start..start + out.typ.slot_width());
567        }
568        slots
569    }
570
571    /// Output name → first slot of the named port.
572    fn named_outputs(&self, resolved: &ResolvedDag) -> HashMap<String, usize> {
573        resolved
574            .output_map
575            .iter()
576            .map(|(name, (n, p))| (name.clone(), self.port_offsets[*n][*p]))
577            .collect()
578    }
579
580    /// Axiom S2: per-slot mask of the slots raw readers must refuse,
581    /// over the whole buffer — kernel inputs and node outputs alike.
582    /// Both slots of a Ref pair are masked, since their bits are an
583    /// address and a length rather than a value; only a typed accessor
584    /// or a boundary decode may read them.
585    fn ref_slot_mask(&self, resolved: &ResolvedDag) -> Vec<bool> {
586        use crate::ast::SlotColor;
587        let mut mask = vec![false; self.total_slots];
588        let mut mark = |start: usize, color: SlotColor| match color {
589            SlotColor::Ref2 => {
590                mask[start] = true;
591                mask[start + 1] = true;
592            }
593            SlotColor::Imm1 | SlotColor::Imm2 => {}
594        };
595        for (i, d) in resolved.input_defs.iter().enumerate() {
596            mark(self.input_starts[i], d.port_type.slot_color());
597        }
598        for (n, node) in resolved.nodes.iter().enumerate() {
599            for (p, out) in node.meta().outs.iter().enumerate() {
600                mark(self.port_offsets[n][p], out.typ.slot_color());
601            }
602        }
603        mask
604    }
605
606    /// First slot of each Ref2-colored output port of one node,
607    /// in port order — pairs with the node's `CompiledSlotKit`
608    /// scratch entries (axiom S3).
609    fn ref_output_starts(&self, resolved: &ResolvedDag, node_idx: usize) -> Vec<usize> {
610        resolved.nodes[node_idx]
611            .meta()
612            .outs
613            .iter()
614            .enumerate()
615            .filter(|(_, out)| out.typ.slot_color() == crate::ast::SlotColor::Ref2)
616            .map(|(p, _)| self.port_offsets[node_idx][p])
617            .collect()
618    }
619
620    /// Expand per-INPUT dependent-step lists to per-SLOT lists so
621    /// the kernels' slot-indexed dirty tracking / changed-mask
622    /// bits stay coherent under multi-slot inputs (every slot of
623    /// one input shares that input's dependents). Identity for
624    /// all-scalar inputs.
625    fn expand_dependents(&self, resolved: &ResolvedDag, deps: &[Vec<usize>]) -> Vec<Vec<usize>> {
626        let mut out = Vec::with_capacity(self.coord_slots);
627        for (i, d) in resolved.input_defs.iter().enumerate() {
628            for _ in 0..d.port_type.slot_width() {
629                out.push(deps.get(i).cloned().unwrap_or_default());
630            }
631        }
632        out
633    }
634}
635
636/// Builder for assembling a Polydat Kernel programmatically.
637pub struct PolydatAssembler {
638    /// All input definitions. Coordinates come first (indices 0..coord_count).
639    input_defs: Vec<crate::kernel::InputDef>,
640    /// How many of the inputs are coordinates.
641    coord_count: usize,
642    nodes: Vec<PendingNode>,
643    /// Output declarations in insertion order.
644    output_order: Vec<String>,
645    outputs: HashMap<String, WireRef>,
646    /// Original source text for diagnostics. Set by the DSL compiler.
647    source: String,
648    /// Diagnostic context (e.g., "workload.yaml bindings").
649    context: String,
650    /// Binding modifiers for named outputs.
651    output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
652    /// The const bindings a kernel initializes, in dependency order.
653    const_inits: Vec<crate::kernel::ConstInit>,
654    /// `shared` registers whose starting value is computed, as
655    /// `(register input, output computing the value)`.
656    shared_starts: Vec<(String, String)>,
657    /// A template's build is not initialized: its inputs come from a
658    /// binder, and each kernel bound from it is initialized then.
659    pub(crate) template: bool,
660    /// Names declared with the `const` keyword. Subject to the
661    /// const binding contract (evaluation_model.md §"Const Binding
662    /// Contract").
663    const_outputs: std::collections::HashSet<String>,
664    /// The `strict_values` pragma (graph_compiler.md §2, strict-wire
665    /// assertions): when true, the resolver checks a compile-time
666    /// constant source against its sink port's `Port.constraint` at
667    /// build and splices an `AssertValue` in front of every other
668    /// constrained wire input.
669    pub(crate) strict_values: bool,
670    /// The `strict_values` mark nodes added now carry; see
671    /// [`Self::set_scope_strict_values`].
672    scope_strict_values: Option<bool>,
673    /// Strict mode: an implicit type coercion is refused at wire
674    /// resolution, and a config wire fed from a cycle-time source, a
675    /// nondeterministic node no `volatile` output acknowledges, and a
676    /// binding nothing reads are refused at build, on every engine.
677    pub(crate) strict: bool,
678    /// What `resolve` does with an input whose type was inferred
679    /// (input_variance.md §4).
680    input_variance: crate::dsl::compile::InputVariance,
681    /// How much of the interpreter's graph `compile()` fuses into native
682    /// cones; `None` is [`JitMode::Auto`](crate::compile::cone::JitMode).
683    /// `compile_with(Engine::Interpreter(mode))` takes its mode from the
684    /// engine.
685    pub(crate) jit_mode: Option<crate::compile::cone::JitMode>,
686    /// The compile ledger every program built from this assembler
687    /// records in: a fresh one unless the compiler hands down the
688    /// tree's.
689    pub(crate) ledger: std::sync::Arc<crate::kernel::CompileLedger>,
690    /// The resource scope of the tree every kernel built from this
691    /// assembler belongs to: a fresh one unless the compiler hands down
692    /// the tree's, or a caller sets it with [`Self::set_resources`].
693    pub(crate) resources: crate::resource::ResourceScope,
694    /// The cursors the program declares (engines.md §3.5), set
695    /// by the DSL compiler so every kernel built from this assembler
696    /// knows them.
697    cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
698}
699
700/// `(coord_slots, total_slots, steps, named outputs, ref-slot
701/// mask)` — the Phase-2 compiled layout shared by the closure
702/// kernel builders.
703type P2Layout = (
704    usize,
705    usize,
706    Vec<crate::compile::closures::P2Step>,
707    HashMap<String, usize>,
708    Vec<bool>,
709    crate::compile::closures::P2Extras,
710);
711
712/// `(coord_slots, total_slots, JIT steps, named outputs, scratch,
713/// volatile steps)` — the JIT compiled layout shared by the native
714/// kernel builders; the scratch is what a state owns for the steps'
715/// kits, with each step's entries placed, and the volatile steps are
716/// the never-current ones (runtime_model.md, R1.v).
717#[cfg(feature = "jit")]
718type JitLayout = (
719    usize,
720    usize,
721    Vec<(crate::compile::jit::JitOp, Vec<usize>, Vec<usize>)>,
722    HashMap<String, usize>,
723    crate::compile::jit::ScratchPlan,
724    Vec<usize>,
725);
726
727impl PolydatAssembler {
728    /// Create a new assembler with the given coordinate names.
729    pub fn new(input_names: Vec<String>) -> Self {
730        let coord_count = input_names.len();
731        let input_defs: Vec<crate::kernel::InputDef> = input_names
732            .into_iter()
733            .map(|name| crate::kernel::InputDef {
734                name,
735                default: crate::ast::Value::U64(0),
736                port_type: crate::ast::PortType::U64,
737                kind: crate::kernel::InputKind::Coordinate,
738                // Declared by `set_input_type` when the program types it.
739                type_origin: crate::kernel::TypeOrigin::Inferred,
740                converts_to: None,
741            })
742            .collect();
743        Self {
744            input_defs,
745            coord_count,
746            nodes: Vec::new(),
747            output_order: Vec::new(),
748            outputs: HashMap::new(),
749            source: String::new(),
750            context: "(assembler)".into(),
751            output_modifiers: HashMap::new(),
752            const_inits: Vec::new(),
753            shared_starts: Vec::new(),
754            template: false,
755            const_outputs: std::collections::HashSet::new(),
756            strict_values: false,
757            scope_strict_values: None,
758            strict: false,
759            input_variance: crate::dsl::compile::InputVariance::Fixed,
760            jit_mode: None,
761            cursor_schemas: Vec::new(),
762            ledger: crate::kernel::CompileLedger::new(),
763            resources: crate::resource::ResourceScope::new(),
764        }
765    }
766
767    /// The resource scope every kernel built from this assembler reports
768    /// through [`Kernel::resources`]. A caller
769    /// that builds nodes itself hands each factory a
770    /// [`BuildContext`](crate::dsl::factory::BuildContext) over the same
771    /// scope, so the nodes and the kernel see one accessor.
772    pub fn set_resources(&mut self, resources: crate::resource::ResourceScope) {
773        self.resources = resources;
774    }
775
776    /// Record the cursors the program declares, with the partitions the
777    /// compiler resolved for each. Every kernel built from this
778    /// assembler reports them through `cursor_schemas` and narrows one
779    /// through `set_cursor`.
780    pub fn set_cursor_schemas(&mut self, schemas: Vec<crate::iteration::source::SourceSchema>) {
781        self.cursor_schemas = schemas;
782    }
783
784    /// The cursors the program declares.
785    pub fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
786        &self.cursor_schemas
787    }
788
789    /// Set the `strict_types` and `strict_values` pragmas
790    /// (graph_compiler.md §2). Under `strict_values` the resolver
791    /// checks constant sources at build and inserts value assertion
792    /// nodes on the other constrained wires. `strict_types` has no
793    /// effect: wires are statically typed, so a runtime type assertion
794    /// has nothing to catch. Both are off by default.
795    pub fn set_strict_wires(&mut self, _strict_types: bool, strict_values: bool) {
796        self.strict_values = strict_values;
797    }
798
799    /// Strict mode, on every engine this assembler builds for: an
800    /// implicit type coercion, a config wire fed from a cycle-time
801    /// source, a nondeterministic node no `volatile` output
802    /// acknowledges, and a binding nothing reads are errors. Off by
803    /// default; the DSL sets it from its `strict` option.
804    pub fn set_strict(&mut self, strict: bool) {
805        self.strict = strict;
806    }
807
808    /// Override the interpreter's cone mode for this compile
809    /// (engines.md §2).
810    /// Unset means `JitMode::Auto`.
811    pub fn set_jit_mode(&mut self, mode: crate::compile::cone::JitMode) {
812        self.jit_mode = Some(mode);
813    }
814
815    /// Set the source text and diagnostic context for this assembler.
816    /// Called by the DSL compiler to attach the original Polydat source.
817    pub fn set_context(&mut self, source: &str, context: &str) {
818        self.source = source.to_string();
819        self.context = context.to_string();
820    }
821
822    /// Add a node to the assembler with the given name and input wiring.
823    pub fn add_node(
824        &mut self,
825        name: impl Into<String>,
826        node: Box<dyn PolydatNode>,
827        inputs: Vec<WireRef>,
828    ) -> &mut Self {
829        self.nodes.push(PendingNode {
830            name: name.into(),
831            node,
832            inputs,
833            strict_values: self.scope_strict_values,
834        });
835        self
836    }
837
838    /// Set the `strict_values` mark of the nodes added from here on and
839    /// return the mark it replaces. `Some(on)` says the nodes are
840    /// written in a scope other than the program's own, whose pragmas
841    /// decide for them; `None` says they follow the program's set. The
842    /// compiler sets it while a module body inlines, so the module's
843    /// own pragmas decide for the module's nodes and the host's decide
844    /// for the host's (polydat_grammar.md §14).
845    pub(crate) fn set_scope_strict_values(&mut self, mark: Option<bool>) -> Option<bool> {
846        std::mem::replace(&mut self.scope_strict_values, mark)
847    }
848
849    /// Set the binding modifier for a named output.
850    pub fn set_output_modifier(&mut self, name: &str, modifier: crate::dsl::ast::BindingModifier) {
851        if modifier != crate::dsl::ast::BindingModifier::NONE {
852            self.output_modifiers.insert(name.to_string(), modifier);
853        }
854    }
855
856    /// Mark an output as a `const`: a value fixed for the life of every
857    /// kernel built from this assembler. `name` is an output, or a node
858    /// when no output has the name.
859    ///
860    /// A const whose value is known at build (it reads no input and no
861    /// nondeterministic node) folds there. Any other const is captured
862    /// when a kernel is initialized ([`crate::Kernel::init`]), the same
863    /// way on every engine: its expression is evaluated once and every
864    /// reader of it reads the captured value. See
865    /// [`crate::kernel::ConstInit`].
866    pub fn mark_const_output(&mut self, name: &str) {
867        self.const_outputs.insert(name.to_string());
868    }
869
870    /// Give the `shared` register at input `name` the starting value
871    /// output `source` computes. A kernel's initialization evaluates it
872    /// once and writes it through the register, while nothing has
873    /// written the register: a scope attached to a register another
874    /// scope declared never seeds it again.
875    pub(crate) fn mark_shared_start(&mut self, name: &str, source: &str) {
876        self.shared_starts
877            .push((name.to_string(), source.to_string()));
878    }
879
880    /// Rewrite the graph so every const whose value is not known at
881    /// build is captured when a kernel is initialized, and record how
882    /// ([`crate::kernel::ConstInit`]), in the order initialization
883    /// evaluates them: each after the consts it reads.
884    ///
885    /// For a captured const `x`: its expression becomes the output
886    /// `__init_x`; its value lives in the input slot `__const_x`, which
887    /// only initialization writes; and every reader of its wire, the
888    /// output `x` included, reads a passthrough of that slot, so nothing
889    /// re-evaluates it. A const whose expression reads an input also gets
890    /// an input of its own name when it has none, which a binder fills
891    /// with the enclosing scope's value: what the const falls back to
892    /// when its expression yields `None`.
893    ///
894    /// A const may not read a coordinate: a const is fixed for the
895    /// kernel's life, and a coordinate advances every cycle. Consts that
896    /// read each other in a cycle cannot be ordered. Both are errors.
897    fn capture_consts(&mut self) -> Result<(), AssemblyError> {
898        use crate::dsl::ast::BindingModifier;
899        use crate::kernel::{InputKind, TypeOrigin};
900
901        let node_of = |nodes: &[PendingNode], name: &str| nodes.iter().position(|n| n.name == name);
902        // What a wire's cone reaches, walking back from `start`: the
903        // inputs it reads, and whether a nondeterministic node, or
904        // `start` itself through a cycle, is in it.
905        let cone = |nodes: &[PendingNode], start: &str| -> (Vec<String>, bool) {
906            let by_name: HashMap<&str, usize> = nodes
907                .iter()
908                .enumerate()
909                .rev()
910                .map(|(i, n)| (n.name.as_str(), i))
911                .collect();
912            let mut inputs: Vec<String> = Vec::new();
913            let mut runtime = false;
914            let mut seen = vec![false; nodes.len()];
915            let first = by_name.get(start).copied();
916            let mut stack: Vec<usize> = first.into_iter().collect();
917            while let Some(i) = stack.pop() {
918                if std::mem::replace(&mut seen[i], true) {
919                    // The walk came back to where it started: the const
920                    // reads itself, which only a captured const can.
921                    if Some(i) == first {
922                        runtime = true;
923                    }
924                    continue;
925                }
926                if matches!(
927                    nodes[i].node.purity(),
928                    crate::ast::Purity::Nondeterministic { .. }
929                ) {
930                    runtime = true;
931                }
932                for wire in &nodes[i].inputs {
933                    match wire {
934                        WireRef::Input(name) => {
935                            if !inputs.contains(name) {
936                                inputs.push(name.clone());
937                            }
938                        }
939                        WireRef::Node(name, _) => stack.extend(by_name.get(name.as_str())),
940                    }
941                }
942            }
943            (inputs, runtime)
944        };
945
946        // The consts not known at build, in the order their producing
947        // nodes were added, each with its wire.
948        let mut captured: Vec<(usize, String, String, usize)> = Vec::new();
949        for name in &self.const_outputs {
950            let (node, port) = match self.outputs.get(name) {
951                Some(WireRef::Node(node, port)) => (node.clone(), *port),
952                Some(WireRef::Input(_)) => continue,
953                None if node_of(&self.nodes, name).is_some() => (name.clone(), 0),
954                None => continue,
955            };
956            let Some(order) = node_of(&self.nodes, &node) else {
957                continue;
958            };
959            let (inputs, runtime) = cone(&self.nodes, &node);
960            if inputs.is_empty() && !runtime {
961                continue;
962            }
963            captured.push((order, name.clone(), node, port));
964        }
965        captured.sort();
966
967        // Rewrite each: its expression under `__init_<name>`, its readers
968        // on a passthrough of its slot.
969        let mut records: Vec<(String, String, String, PortType, bool)> = Vec::new();
970        for (_, name, node, port) in captured {
971            let Some(index) = node_of(&self.nodes, &node) else {
972                continue;
973            };
974            let Some(ty) = self.nodes[index].node.meta().outs.get(port).map(|p| p.typ) else {
975                return Err(AssemblyError::UnknownWire(format!("{node}[{port}]")));
976            };
977            let source = format!("__init_{name}");
978            let slot = format!("__const_{name}");
979            // The const's own node keeps its expression under the source
980            // name, so the const's name is the passthrough's.
981            let renamed = node == name;
982            let root = if renamed {
983                source.clone()
984            } else {
985                node.clone()
986            };
987            let passthrough = if renamed || node_of(&self.nodes, &name).is_none() {
988                name.clone()
989            } else {
990                slot.clone()
991            };
992            if renamed {
993                self.nodes[index].name = source.clone();
994            }
995            let redirect = |wire: &mut WireRef| {
996                if let WireRef::Node(n, p) = wire
997                    && *n == node
998                {
999                    if *p == port {
1000                        *wire = WireRef::node(passthrough.clone());
1001                    } else {
1002                        *n = root.clone();
1003                    }
1004                }
1005            };
1006            for pending in &mut self.nodes {
1007                pending.inputs.iter_mut().for_each(redirect);
1008            }
1009            self.outputs.values_mut().for_each(redirect);
1010            self.add_input(&slot, crate::ast::Value::None, ty, InputKind::Const);
1011            self.add_node(
1012                &passthrough,
1013                Box::new(crate::library::identity::PortPassthrough::new(&slot, ty)),
1014                vec![WireRef::input(&slot)],
1015            );
1016            self.add_output(&source, WireRef::node_port(&root, port));
1017            // The expression carries the const's modifier, so a
1018            // nondeterministic read in it is acknowledged: the const
1019            // takes one reading, at initialization.
1020            let modifier = *self
1021                .output_modifiers
1022                .entry(name.clone())
1023                .or_insert(BindingModifier::CONST);
1024            self.set_output_modifier(&source, modifier);
1025            records.push((name, slot, source, ty, false));
1026        }
1027        // A `shared` register with a computed starting value: its input
1028        // is the slot, written at initialization while nothing has
1029        // written the register.
1030        for (name, source) in std::mem::take(&mut self.shared_starts) {
1031            let Some(ty) = self.input_type(&name) else {
1032                return Err(AssemblyError::UnknownWire(name));
1033            };
1034            records.push((name.clone(), name, source, ty, true));
1035        }
1036
1037        // What each captured const reads, with every other captured
1038        // const read as its slot.
1039        let slot_owner: HashMap<String, String> = records
1040            .iter()
1041            .map(|(name, slot, _, _, _)| (slot.clone(), name.clone()))
1042            .collect();
1043        let mut pending: Vec<(crate::kernel::ConstInit, Vec<String>)> = Vec::new();
1044        for (name, slot, source, ty, register) in records {
1045            let root = match self.outputs.get(&source) {
1046                Some(WireRef::Node(n, _)) => n.clone(),
1047                _ => return Err(AssemblyError::UnknownWire(source)),
1048            };
1049            let (inputs, _) = cone(&self.nodes, &root);
1050            if let Some(coord) = inputs.iter().find(|i| {
1051                self.input_defs
1052                    .iter()
1053                    .any(|d| &d.name == *i && d.kind == InputKind::Coordinate)
1054            }) {
1055                let what = if register {
1056                    format!("the starting value of shared '{name}'")
1057                } else {
1058                    format!("const '{name}'")
1059                };
1060                return Err(AssemblyError::Other(format!(
1061                    "{what} reads the coordinate '{coord}': it is evaluated once when the \
1062                     kernel is initialized, and a coordinate advances every cycle. Read an \
1063                     extern or a const instead."
1064                )));
1065            }
1066            let deps: Vec<String> = inputs
1067                .iter()
1068                .filter_map(|i| slot_owner.get(i))
1069                .filter(|owner| **owner != name)
1070                .cloned()
1071                .collect();
1072            if !register && !inputs.is_empty() && self.input_type(&name).is_none() {
1073                self.add_input(
1074                    &name,
1075                    crate::ast::Value::None,
1076                    ty,
1077                    InputKind::IterationExtern,
1078                );
1079                self.set_input_origin(&name, TypeOrigin::Inferred);
1080            }
1081            let fallback = (!register && self.input_type(&name).is_some()).then(|| name.clone());
1082            pending.push((
1083                crate::kernel::ConstInit {
1084                    name,
1085                    slot,
1086                    source,
1087                    fallback,
1088                    register,
1089                    slot_index: 0,
1090                    source_index: 0,
1091                    fallback_index: None,
1092                },
1093                deps,
1094            ));
1095        }
1096
1097        // Each after the consts it reads.
1098        let mut ordered: Vec<crate::kernel::ConstInit> = Vec::with_capacity(pending.len());
1099        while !pending.is_empty() {
1100            let (ready, rest): (Vec<_>, Vec<_>) = pending.into_iter().partition(|(_, deps)| {
1101                deps.iter().all(|d| {
1102                    ordered
1103                        .iter()
1104                        .any(|c: &crate::kernel::ConstInit| &c.name == d)
1105                })
1106            });
1107            if ready.is_empty() {
1108                let names: Vec<&str> = rest.iter().map(|(c, _)| c.name.as_str()).collect();
1109                return Err(AssemblyError::Other(format!(
1110                    "the consts {names:?} read each other in a cycle, so none can be evaluated \
1111                     first"
1112                )));
1113            }
1114            ordered.extend(ready.into_iter().map(|(c, _)| c));
1115            pending = rest;
1116        }
1117        let input_index = |name: &str| self.input_defs.iter().position(|d| d.name == name);
1118        for c in &mut ordered {
1119            c.slot_index = input_index(&c.slot).expect("the const's slot was just added");
1120            c.source_index = self
1121                .output_order
1122                .iter()
1123                .position(|n| n == &c.source)
1124                .expect("the const's source output was just added");
1125            c.fallback_index = c.fallback.as_deref().and_then(input_index);
1126        }
1127        self.const_inits = ordered;
1128        Ok(())
1129    }
1130
1131    /// How many nodes the graph holds so far.
1132    pub fn node_count(&self) -> usize {
1133        self.nodes.len()
1134    }
1135
1136    /// Designate a wire as a named output variate.
1137    pub fn add_output(&mut self, name: impl Into<String>, wire: WireRef) -> &mut Self {
1138        let name = name.into();
1139        if !self.outputs.contains_key(&name) {
1140            self.output_order.push(name.clone());
1141        }
1142        self.outputs.insert(name, wire);
1143        self
1144    }
1145
1146    /// Declare an additional named input.
1147    ///
1148    /// Added after coordinate inputs. Nodes wire to it via
1149    /// `WireRef::input(name)` — same as coordinate inputs.
1150    /// `kind` controls the lifecycle classification used by the
1151    /// init-binding contract (see
1152    /// `crates/polydat/docs/design/evaluation_model.md`
1153    /// §"Effectively-Const Nodes"): `IterationExtern` for slots
1154    /// populated by `materialize_wiring_from_outer`, `ExternalWrite` for slots
1155    /// written by capture extraction.
1156    pub fn add_input(
1157        &mut self,
1158        name: impl Into<String>,
1159        default: crate::ast::Value,
1160        port_type: crate::ast::PortType,
1161        kind: crate::kernel::InputKind,
1162    ) -> &mut Self {
1163        self.input_defs.push(crate::kernel::InputDef {
1164            name: name.into(),
1165            default,
1166            port_type,
1167            kind,
1168            type_origin: crate::kernel::TypeOrigin::Declared,
1169            converts_to: None,
1170        });
1171        self
1172    }
1173
1174    /// Override a declared input's port type. `new` seeds every
1175    /// `input_names` entry with `PortType::U64`; this applies the type
1176    /// from an `input <name>: <type>` declaration. No-op if the input
1177    /// isn't present.
1178    pub fn set_input_type(&mut self, name: &str, port_type: crate::ast::PortType) {
1179        if let Some(d) = self.input_defs.iter_mut().find(|d| d.name == name) {
1180            d.port_type = port_type;
1181            d.type_origin = crate::kernel::TypeOrigin::Declared;
1182        }
1183    }
1184
1185    /// Record how input `name`'s type was established: the compiler
1186    /// marks an auto-extern `Inferred`, so `input_variance` can open it
1187    /// (input_variance.md §3). `add_input` records `Declared`.
1188    pub fn set_input_origin(&mut self, name: &str, origin: crate::kernel::TypeOrigin) {
1189        if let Some(d) = self.input_defs.iter_mut().find(|d| d.name == name) {
1190            d.type_origin = origin;
1191        }
1192    }
1193
1194    /// What `resolve` does with an input whose type was inferred.
1195    pub fn set_input_variance(&mut self, variance: crate::dsl::compile::InputVariance) {
1196        self.input_variance = variance;
1197    }
1198
1199    /// Return the names of all inputs (coordinates + captures).
1200    pub fn input_names(&self) -> Vec<&str> {
1201        self.input_defs.iter().map(|d| d.name.as_str()).collect()
1202    }
1203
1204    /// Query the output port type of a named node (first output).
1205    /// Returns `None` if the node is not found or has no output
1206    /// ports; callers surface the absence as a loud diagnostic
1207    /// rather than silently substituting a default.
1208    pub fn node_output_type(&self, name: &str) -> Option<crate::ast::PortType> {
1209        self.nodes
1210            .iter()
1211            .find(|n| n.name == name)
1212            .and_then(|n| n.node.meta().outs.first())
1213            .map(|p| p.typ)
1214    }
1215
1216    /// Return the names of declared outputs.
1217    pub fn output_names(&self) -> Vec<&str> {
1218        self.outputs.keys().map(|s| s.as_str()).collect()
1219    }
1220
1221    /// The node type a named node has, when the name is a node.
1222    pub fn node_type_of(&self, name: &str) -> Option<String> {
1223        self.nodes
1224            .iter()
1225            .find(|pn| pn.name == name)
1226            .map(|pn| pn.node.meta().name.clone())
1227    }
1228
1229    /// Look up the output port type of a named node.
1230    ///
1231    /// Returns the first output port's `PortType` if the node exists.
1232    pub fn output_type(&self, name: &str) -> Option<PortType> {
1233        self.nodes
1234            .iter()
1235            .find(|pn| pn.name == name)
1236            .and_then(|pn| pn.node.meta().outs.first())
1237            .map(|port| port.typ)
1238    }
1239
1240    /// Look up the port type of a graph input by name.
1241    pub fn input_type(&self, name: &str) -> Option<PortType> {
1242        self.input_defs
1243            .iter()
1244            .find(|d| d.name == name)
1245            .map(|d| d.port_type)
1246    }
1247
1248    /// Look up the produced port type of a `WireRef`. Returns `None`
1249    /// if the wire's source isn't yet known to the assembler (e.g.
1250    /// it points to a not-yet-added node — a bug in the binding
1251    /// compiler if it happens).
1252    pub fn wire_type(&self, wire: &WireRef) -> Option<PortType> {
1253        match wire {
1254            WireRef::Input(name) => self.input_type(name),
1255            WireRef::Node(name, port_idx) => self
1256                .nodes
1257                .iter()
1258                .find(|pn| &pn.name == name)
1259                .and_then(|pn| pn.node.meta().outs.get(*port_idx))
1260                .map(|p| p.typ),
1261        }
1262    }
1263
1264    /// Validate, resolve, and produce a Phase 1 runtime kernel.
1265    pub fn compile(self) -> Result<PolydatKernel, AssemblyError> {
1266        self.compile_with_log(None)
1267    }
1268
1269    /// Compile with diagnostic event logging.
1270    pub fn compile_with_log(
1271        self,
1272        mut log: Option<&mut crate::dsl::events::CompileEventLog>,
1273    ) -> Result<PolydatKernel, AssemblyError> {
1274        let jit_mode = self.jit_mode.unwrap_or_default();
1275        let strict = self.strict;
1276        let template = self.template;
1277        let mut resolved = self.resolve_with_log(log.as_deref_mut())?;
1278        let (node_total, output_total) = (resolved.nodes.len(), resolved.output_order.len());
1279        let identity = resolved.graph_identity();
1280        crate::compile::cone::extract_jit_cones(&mut resolved, jit_mode)?;
1281        let _coord_names = resolved.input_names();
1282        let modifiers = resolved.output_modifiers.clone();
1283        let cursors = std::mem::take(&mut resolved.cursor_schemas);
1284        let mut kernel = PolydatKernel::new_with_inputs(
1285            resolved.nodes,
1286            resolved.wiring,
1287            resolved.input_defs,
1288            resolved.coord_count,
1289            resolved.output_map,
1290            resolved.output_order,
1291            resolved.const_outputs,
1292            modifiers,
1293            &resolved.source,
1294            &resolved.context,
1295            log.as_deref_mut(),
1296            strict,
1297            resolved.ledger.clone(),
1298        )?;
1299        kernel.set_resources(resolved.resources.clone());
1300        kernel.set_graph_identity(identity);
1301        if !cursors.is_empty() {
1302            kernel.set_cursor_schemas(cursors);
1303        }
1304        kernel.set_cone_mode(jit_mode);
1305        kernel.set_const_inits(resolved.const_inits);
1306        Self::log_summary(log, node_total, output_total);
1307        if template {
1308            return Ok(kernel);
1309        }
1310        crate::kernel::Kernel::init(&mut kernel).map_err(|e| match e {
1311            KernelError::ConstInit { name, reason } => AssemblyError::ConstInit { name, reason },
1312            other => AssemblyError::ConstInit {
1313                name: String::new(),
1314                reason: other.to_string(),
1315            },
1316        })?;
1317        Ok(kernel)
1318    }
1319
1320    /// Strict mode's build-time refusals on a resolved graph, the ones
1321    /// the interpreter's fold makes: what a compiled engine checks
1322    /// before it builds, so strict means the same thing on every engine.
1323    fn refuse_strict(resolved: &ResolvedDag) -> Result<(), AssemblyError> {
1324        let classes = PolydatProgram::classify_lifecycle(
1325            &resolved.nodes,
1326            &resolved.wiring,
1327            &resolved.input_defs,
1328            &resolved.output_map,
1329            &resolved.output_modifiers,
1330        );
1331        let is_init: Vec<bool> = classes
1332            .lifecycle
1333            .iter()
1334            .map(|lc| *lc == crate::kernel::EvalLifecycle::CompileConst)
1335            .collect();
1336        match PolydatProgram::strict_violation(
1337            &resolved.nodes,
1338            &resolved.wiring,
1339            &is_init,
1340            &resolved.output_map,
1341            &resolved.output_modifiers,
1342        ) {
1343            Some(violation) => Err(AssemblyError::Other(violation)),
1344            None => Ok(()),
1345        }
1346    }
1347
1348    /// A node with no closure form, as a refusal naming the closure
1349    /// tier and the reason the layout gave.
1350    fn refused_by_closures(reason: String) -> KernelError {
1351        KernelError::Refused {
1352            engine: Engine::Closures(Provenance::Auto),
1353            reason,
1354        }
1355    }
1356
1357    /// A node native code cannot run, as a refusal naming the native
1358    /// engine and the reason the layout gave.
1359    fn refused_by_native(reason: String) -> KernelError {
1360        KernelError::Refused {
1361            engine: Engine::Native(Provenance::Auto),
1362            reason,
1363        }
1364    }
1365
1366    /// The same, naming the pure tier: on `Native` a node without a
1367    /// native lowering runs its closure, so only the pure tier turns
1368    /// that into a refusal, and the error should say which engine
1369    /// refused.
1370    #[cfg_attr(not(feature = "jit"), allow(dead_code))]
1371    fn refused_by_pure_native(reason: String) -> KernelError {
1372        KernelError::Refused {
1373            engine: Engine::PureNative(Provenance::Auto),
1374            reason,
1375        }
1376    }
1377
1378    /// Shared: extract P2 compiled steps + slot layout from resolved DAG.
1379    /// Returns None if any node lacks a compiled form.
1380    fn build_p2_layout(resolved: &ResolvedDag) -> Result<P2Layout, String> {
1381        let layout = slot_layout(resolved);
1382
1383        let mut compiled_ops = Vec::with_capacity(resolved.nodes.len());
1384        let mut extras = crate::compile::closures::P2Extras::default();
1385        for (node_idx, node) in resolved.nodes.iter().enumerate() {
1386            compiled_ops.push(
1387                node_step_op(node.as_ref(), &wire_types_of(resolved, node_idx)).ok_or_else(
1388                    || {
1389                        format!(
1390                            "node '{}' has no compiled form (docs/design/engines.md §8)",
1391                            node.meta().name
1392                        )
1393                    },
1394                )?,
1395            );
1396        }
1397        extras.externs = crate::compile::externs::Externs::new(
1398            &resolved.input_defs,
1399            resolved.coord_count,
1400            &layout.input_starts,
1401            &resolved.cursor_schemas,
1402            &shared_outputs_of(resolved),
1403            resolved.ledger.clone(),
1404        )?;
1405        extras.externs.set_resources(resolved.resources.clone());
1406        extras.externs.set_graph_identity(resolved.graph_identity());
1407        extras.externs.set_output_names(&resolved.output_order);
1408        extras
1409            .externs
1410            .set_dataset_sources(dataset_sources_of_outputs(resolved));
1411        extras
1412            .externs
1413            .set_output_modifiers(&resolved.output_modifiers);
1414        extras.externs.set_const_inits(&resolved.const_inits);
1415        extras.externs.set_fixed_outputs(fixed_outputs(resolved));
1416        extras.output_types = resolved
1417            .output_map
1418            .iter()
1419            .map(|(name, (n, p))| (name.clone(), resolved.nodes[*n].meta().outs[*p].typ))
1420            .collect();
1421
1422        // The runtime model's lifecycle classification, the one rule the
1423        // interpreter's fold applies, and the provenance the plan is
1424        // derived from.
1425        let classes = PolydatProgram::classify_lifecycle(
1426            &resolved.nodes,
1427            &resolved.wiring,
1428            &resolved.input_defs,
1429            &resolved.output_map,
1430            &resolved.output_modifiers,
1431        );
1432        let inventory = PolydatProgram::compute_node_inventory(&resolved.nodes, &resolved.wiring);
1433        let per_input = PolydatProgram::compute_dependents(
1434            &inventory.input_provenance,
1435            resolved.input_defs.len(),
1436        );
1437        extras.input_dependents = layout.expand_dependents(resolved, &per_input);
1438        extras.attribution = std::sync::Arc::new(Self::attribution_of(resolved));
1439
1440        let mut steps = Vec::with_capacity(resolved.nodes.len());
1441        for (node_idx, (op, scratch)) in compiled_ops.into_iter().enumerate() {
1442            steps.push(crate::compile::closures::P2Step {
1443                name: resolved.nodes[node_idx].meta().name.clone(),
1444                op,
1445                input_slots: layout.input_slots(resolved, node_idx),
1446                output_slots: layout.output_slots(resolved, node_idx),
1447                ref_output_starts: layout.ref_output_starts(resolved, node_idx),
1448                scratch,
1449                accepts_none: resolved.nodes[node_idx].accepts_none_inputs(),
1450                volatile: classes.nondeterministic[node_idx],
1451                constant: classes.lifecycle[node_idx] == crate::kernel::EvalLifecycle::CompileConst,
1452                side: matches!(
1453                    resolved.nodes[node_idx].purity(),
1454                    crate::ast::Purity::SideChannel { .. }
1455                ),
1456            });
1457        }
1458        let output_map = layout.named_outputs(resolved);
1459        let ref_slots = layout.ref_slot_mask(resolved);
1460
1461        Ok((
1462            layout.coord_slots,
1463            layout.total_slots,
1464            steps,
1465            output_map,
1466            ref_slots,
1467            extras,
1468        ))
1469    }
1470
1471    /// Shared: resolve nodes to JIT steps + slot layout.
1472    #[cfg(feature = "jit")]
1473    pub(crate) fn build_jit_layout(resolved: &ResolvedDag) -> Result<JitLayout, String> {
1474        let layout = slot_layout(resolved);
1475
1476        // Every step's scratch entries are placed in the state's
1477        // scratch as the steps are laid out (axiom S3): a reference
1478        // output's pair names its own entry, wherever the step runs.
1479        let mut scratch = crate::compile::jit::ScratchPlan::default();
1480        let mut jit_steps = Vec::new();
1481        for (node_idx, node) in resolved.nodes.iter().enumerate() {
1482            let mut jit_op = crate::compile::jit::classify_node_typed(
1483                node.as_ref(),
1484                &wire_types_of(resolved, node_idx),
1485            );
1486            if matches!(jit_op, crate::compile::jit::JitOp::Fallback) {
1487                return Err(format!(
1488                    "node '{}' has no native form and no kit; pure native code cannot run it",
1489                    node.meta().name
1490                ));
1491            }
1492            let base = scratch.elems.len();
1493            jit_op.place_scratch(base);
1494            let elems = jit_op.scratch_elems().to_vec();
1495            scratch.refs.extend(scratch_pairs(
1496                &node.meta().name,
1497                &layout.ref_output_starts(resolved, node_idx),
1498                &elems,
1499                base,
1500            ));
1501            scratch.elems.extend(elems);
1502            jit_steps.push((
1503                jit_op,
1504                layout.input_slots(resolved, node_idx),
1505                layout.output_slots(resolved, node_idx),
1506            ));
1507        }
1508
1509        let output_map = layout.named_outputs(resolved);
1510        // The runtime model's lifecycle classification, the one rule the
1511        // interpreter's fold applies: a nondeterministic node, or one
1512        // downstream of it, is never current on any engine.
1513        let classes = PolydatProgram::classify_lifecycle(
1514            &resolved.nodes,
1515            &resolved.wiring,
1516            &resolved.input_defs,
1517            &resolved.output_map,
1518            &resolved.output_modifiers,
1519        );
1520        let volatile: Vec<usize> = (0..resolved.nodes.len())
1521            .filter(|&i| classes.nondeterministic[i])
1522            .collect();
1523        Ok((
1524            layout.coord_slots,
1525            layout.total_slots,
1526            jit_steps,
1527            output_map,
1528            scratch,
1529            volatile,
1530        ))
1531    }
1532
1533    /// The slots a pure-P3 kernel's raw readers must refuse and the
1534    /// port type of each named output, for typed decode
1535    /// (compiled_handles.md §4).
1536    #[cfg(feature = "jit")]
1537    fn jit_slot_info(resolved: &ResolvedDag) -> (Vec<bool>, HashMap<String, PortType>) {
1538        let layout = slot_layout(resolved);
1539        let guard = layout.ref_slot_mask(resolved);
1540        let types = resolved
1541            .output_map
1542            .iter()
1543            .map(|(name, (n, p))| (name.clone(), resolved.nodes[*n].meta().outs[*p].typ))
1544            .collect();
1545        (guard, types)
1546    }
1547
1548    #[cfg(feature = "jit")]
1549    fn jit_push_pull_from(
1550        resolved: ResolvedDag,
1551    ) -> Result<crate::compile::jit::JitKernelPushPull, KernelError> {
1552        let _coord_names = resolved.input_names();
1553        let (coord_count, total_slots, jit_steps, output_map, scratch, volatile) =
1554            Self::build_jit_layout(&resolved).map_err(Self::refused_by_pure_native)?;
1555        let (guard, types) = Self::jit_slot_info(&resolved);
1556        let deps = slot_layout(&resolved).expand_dependents(
1557            &resolved,
1558            &PolydatProgram::compute_dependents(
1559                &PolydatProgram::compute_provenance(&resolved.nodes, &resolved.wiring),
1560                resolved.input_defs.len(),
1561            ),
1562        );
1563        let externs = Self::externs_of(&resolved).map_err(Self::refused_by_pure_native)?;
1564        let attribution = std::sync::Arc::new(Self::attribution_of(&resolved));
1565        let (folded, origin) = Self::constant_steps(&resolved, &jit_steps);
1566        let alone = Self::side_channels(&resolved);
1567        let mut k = crate::compile::jit::compile_jit_push_pull(
1568            coord_count,
1569            total_slots,
1570            jit_steps,
1571            output_map,
1572            resolved.nodes,
1573            deps,
1574            externs,
1575            scratch,
1576            volatile,
1577            alone,
1578        )
1579        .map_err(Self::refused_by_pure_native)?;
1580        k.set_slot_info(guard, types);
1581        k.set_attribution(attribution);
1582        // After the attribution, so a constant that fails at build names
1583        // its node as it would at evaluation.
1584        k.fold_constants(&folded, &origin, total_slots)?;
1585        Ok(k)
1586    }
1587
1588    /// This graph's compile-constant steps, and the program step each
1589    /// one came from. The closure tier and the hybrid run their
1590    /// constant steps out of the step list they keep; the pure tier
1591    /// compiles one function over every step and keeps no list, so its
1592    /// constants are compiled a second time into an entry of their own
1593    /// and run once over the kernel's buffer. Same classification as
1594    /// the other two engines use, from the runtime model's lifecycle.
1595    #[cfg(feature = "jit")]
1596    #[allow(clippy::type_complexity)]
1597    fn constant_steps(
1598        resolved: &ResolvedDag,
1599        jit_steps: &[(crate::compile::jit::JitOp, Vec<usize>, Vec<usize>)],
1600    ) -> (
1601        Vec<(crate::compile::jit::JitOp, Vec<usize>, Vec<usize>)>,
1602        Vec<usize>,
1603    ) {
1604        let classes = PolydatProgram::classify_lifecycle(
1605            &resolved.nodes,
1606            &resolved.wiring,
1607            &resolved.input_defs,
1608            &resolved.output_map,
1609            &resolved.output_modifiers,
1610        );
1611        // One step per node, pushed in node order by `build_jit_layout`,
1612        // so a step's index is its node's.
1613        jit_steps
1614            .iter()
1615            .enumerate()
1616            .filter(|(i, _)| {
1617                classes.lifecycle.get(*i) == Some(&crate::kernel::EvalLifecycle::CompileConst)
1618            })
1619            .map(|(i, s)| (s.clone(), i))
1620            .unzip()
1621    }
1622
1623    /// Per node, and so per pure-native step, whether it is a side
1624    /// channel: such a step is a fusion unit of its own, so it fires
1625    /// when its own inputs change and not whenever a neighbor runs.
1626    #[cfg(feature = "jit")]
1627    fn side_channels(resolved: &ResolvedDag) -> Vec<bool> {
1628        resolved
1629            .nodes
1630            .iter()
1631            .map(|n| matches!(n.purity(), crate::ast::Purity::SideChannel { .. }))
1632            .collect()
1633    }
1634
1635    /// The extern inputs of a resolved graph, at the slots the layout
1636    /// gives them, with the graph's identity digest: every compiled
1637    /// kernel built from a resolved graph, raw constructors included,
1638    /// reports the canonical hash the graph has (scope_model.md §8).
1639    fn externs_of(resolved: &ResolvedDag) -> Result<crate::compile::externs::Externs, String> {
1640        let layout = slot_layout(resolved);
1641        let mut externs = crate::compile::externs::Externs::new(
1642            &resolved.input_defs,
1643            resolved.coord_count,
1644            &layout.input_starts,
1645            &resolved.cursor_schemas,
1646            &shared_outputs_of(resolved),
1647            resolved.ledger.clone(),
1648        )?;
1649        externs.set_resources(resolved.resources.clone());
1650        externs.set_graph_identity(resolved.graph_identity());
1651        externs.set_output_names(&resolved.output_order);
1652        externs.set_dataset_sources(dataset_sources_of_outputs(resolved));
1653        externs.set_output_modifiers(&resolved.output_modifiers);
1654        externs.set_const_inits(&resolved.const_inits);
1655        externs.set_fixed_outputs(fixed_outputs(resolved));
1656        Ok(externs)
1657    }
1658
1659    /// Pure native code, raw; see [`Self::try_compile_pure_jit`].
1660    #[doc(hidden)]
1661    #[cfg(feature = "jit")]
1662    pub(crate) fn try_compile_pure_jit_raw(
1663        self,
1664    ) -> Result<crate::compile::jit::JitKernelRaw, KernelError> {
1665        let resolved = self.resolve().map_err(KernelError::Assembly)?;
1666        Self::jit_raw_from(resolved)
1667    }
1668
1669    // ── The typed tier constructors (feature `bench-tiers`) ──────
1670    //
1671    // The same kernels [`Self::compile_slots`] builds, returned as
1672    // their own types instead of `Box<dyn SlotKernel>`.
1673    //
1674    // There is one contract — [`Kernel`](crate::kernel::Kernel) and the
1675    // [`SlotKernel`](crate::compile::SlotKernel) that extends it — and
1676    // these do not add a second. They change only how a caller *holds*
1677    // it: a boxed kernel dispatches, a named one monomorphizes, and
1678    // both are bound by the same trait with the same semantics.
1679    //
1680    // The normative path is `compile_slots`, which picks an engine from
1681    // a runtime value and therefore cannot return a statically known
1682    // type. Only a caller that knows its tier at compile time can use
1683    // these, and only one kind of caller does: a benchmark measuring a
1684    // tier, which otherwise measures the dispatch instead of the
1685    // kernel. On the engine ladder that difference is about a fifth of
1686    // the native tier's per-cycle cost, which is large enough to hide
1687    // the regressions the ladder exists to catch.
1688    //
1689    // Off by default, so an ordinary build and anything a consumer
1690    // links has exactly one door to a kernel.
1691
1692    /// The closure tier with no provenance, as its own type.
1693    #[cfg(feature = "bench-tiers")]
1694    pub fn compile_closures_raw(
1695        self,
1696    ) -> Result<crate::compile::closures::CompiledKernelRaw, KernelError> {
1697        let resolved = self.resolve_with_log(None)?;
1698        let (coord_count, total_slots, steps, output_map, ref_slots, extras) =
1699            Self::build_p2_layout(&resolved).map_err(Self::refused_by_closures)?;
1700        crate::compile::closures::CompiledKernelRaw::new(
1701            coord_count,
1702            total_slots,
1703            steps,
1704            output_map,
1705            ref_slots,
1706            extras,
1707        )
1708    }
1709
1710    /// The native tier with no provenance, as its own type.
1711    #[cfg(all(feature = "bench-tiers", feature = "jit"))]
1712    pub fn compile_native_raw(
1713        self,
1714    ) -> Result<crate::compile::hybrid::HybridKernelRaw, KernelError> {
1715        let resolved = self.resolve_with_log(None)?;
1716        Ok(Self::hybrid_from(resolved)?.into_raw())
1717    }
1718
1719    /// Pure native code with no provenance, as its own type.
1720    #[cfg(all(feature = "bench-tiers", feature = "jit"))]
1721    pub fn compile_pure_native_raw(self) -> Result<crate::compile::jit::JitKernelRaw, KernelError> {
1722        self.try_compile_pure_jit_raw()
1723    }
1724
1725    /// Where each node lives, for the failure path (engines.md §3.4):
1726    /// its name, the outputs it feeds, and `(first slot, port type)`
1727    /// per input port, so a compiled kernel can report a step's failure as the
1728    /// interpreter reports the node's.
1729    pub(crate) fn attribution_of(resolved: &ResolvedDag) -> crate::compile::Attribution {
1730        let layout = slot_layout(resolved);
1731        let sites = resolved
1732            .nodes
1733            .iter()
1734            .enumerate()
1735            .map(|(node_idx, node)| {
1736                let mut outputs: Vec<String> = resolved
1737                    .output_map
1738                    .iter()
1739                    .filter(|(_, (n, _))| *n == node_idx)
1740                    .map(|(name, _)| name.clone())
1741                    .collect();
1742                outputs.sort();
1743                let inputs = resolved.wiring[node_idx]
1744                    .iter()
1745                    .map(|source| match source {
1746                        WireSource::Input(c) => (
1747                            layout.input_starts.get(*c).copied().unwrap_or(*c),
1748                            resolved
1749                                .input_defs
1750                                .get(*c)
1751                                .map(|d| d.port_type)
1752                                .unwrap_or(PortType::U64),
1753                        ),
1754                        WireSource::NodeOutput(u, p) => (
1755                            layout.port_offsets[*u][*p],
1756                            resolved.nodes[*u].meta().outs[*p].typ,
1757                        ),
1758                    })
1759                    .collect();
1760                crate::compile::NodeSite {
1761                    name: node.meta().name.to_string(),
1762                    outputs,
1763                    inputs,
1764                }
1765            })
1766            .collect();
1767        crate::compile::Attribution {
1768            sites,
1769            context: resolved.context.clone(),
1770        }
1771    }
1772
1773    #[cfg(feature = "jit")]
1774    fn jit_raw_from(
1775        resolved: ResolvedDag,
1776    ) -> Result<crate::compile::jit::JitKernelRaw, KernelError> {
1777        let _coord_names = resolved.input_names();
1778        let (coord_count, total_slots, jit_steps, output_map, scratch, volatile) =
1779            Self::build_jit_layout(&resolved).map_err(Self::refused_by_pure_native)?;
1780        let (guard, types) = Self::jit_slot_info(&resolved);
1781        let externs = Self::externs_of(&resolved).map_err(Self::refused_by_pure_native)?;
1782        let attribution = std::sync::Arc::new(Self::attribution_of(&resolved));
1783        let (folded, origin) = Self::constant_steps(&resolved, &jit_steps);
1784        let alone = Self::side_channels(&resolved);
1785        let mut k = crate::compile::jit::compile_jit_raw_with(
1786            coord_count,
1787            total_slots,
1788            jit_steps,
1789            output_map,
1790            resolved.nodes,
1791            externs,
1792            scratch,
1793            volatile,
1794            alone,
1795        )
1796        .map_err(Self::refused_by_pure_native)?;
1797        k.set_slot_info(guard, types);
1798        k.set_attribution(attribution);
1799        // After the attribution, so a constant that fails at build names
1800        // its node as it would at evaluation.
1801        k.fold_constants(&folded, &origin, total_slots)?;
1802        Ok(k)
1803    }
1804
1805    /// Compile the conservative perfect-ordinal Tier-1 SIMD execution plan.
1806    ///
1807    /// Ordinary `compile()` semantics are unchanged. This explicit surface
1808    /// retains the selected scalar DAG as a fallback and synthesizes a second,
1809    /// register-typed DAG for one named output and driving cursor input.
1810    #[cfg(feature = "jit")]
1811    #[doc(hidden)]
1812    pub fn try_compile_tier1_simd_ordinal(
1813        self,
1814        driving_input: &str,
1815        output: &str,
1816    ) -> Result<
1817        crate::compile::simd_tier1::Tier1SimdExecutor,
1818        crate::compile::simd_tier1::Tier1SimdError,
1819    > {
1820        let resolved = self.resolve().map_err(|error| {
1821            crate::compile::simd_tier1::Tier1SimdError::VectorGraphBuild(error.to_string())
1822        })?;
1823        crate::compile::simd_tier1::compile_tier1_ordinal(resolved, driving_input, output)
1824    }
1825
1826    fn hybrid_from(
1827        resolved: ResolvedDag,
1828    ) -> Result<crate::compile::hybrid::HybridKernel, KernelError> {
1829        let _coord_names = resolved.input_names();
1830        let layout = slot_layout(&resolved);
1831
1832        let output_map = layout.named_outputs(&resolved);
1833        let input_widths: Vec<usize> = resolved
1834            .input_defs
1835            .iter()
1836            .map(|d| d.port_type.slot_width())
1837            .collect();
1838
1839        let ref_slots = layout.ref_slot_mask(&resolved);
1840        let input_types: Vec<PortType> = resolved.input_defs.iter().map(|d| d.port_type).collect();
1841        let externs = Self::externs_of(&resolved).map_err(Self::refused_by_native)?;
1842        let attribution = std::sync::Arc::new(Self::attribution_of(&resolved));
1843        // The runtime model's lifecycle classification, the one rule the
1844        // interpreter's fold applies.
1845        let classes = PolydatProgram::classify_lifecycle(
1846            &resolved.nodes,
1847            &resolved.wiring,
1848            &resolved.input_defs,
1849            &resolved.output_map,
1850            &resolved.output_modifiers,
1851        );
1852        let constant: Vec<bool> = classes
1853            .lifecycle
1854            .iter()
1855            .map(|lc| *lc == crate::kernel::EvalLifecycle::CompileConst)
1856            .collect();
1857        let mut kernel = crate::compile::hybrid::build_hybrid(
1858            &resolved.nodes,
1859            &resolved.wiring,
1860            layout.coord_slots,
1861            layout.total_slots,
1862            &layout.port_offsets,
1863            &layout.input_starts,
1864            &input_widths,
1865            output_map,
1866            ref_slots,
1867            &input_types,
1868            externs,
1869            constant,
1870            classes.nondeterministic,
1871            attribution,
1872        )?;
1873        kernel.retain_nodes(resolved.nodes);
1874        Ok(kernel)
1875    }
1876
1877    /// Internal: validate, resolve wiring, insert adapters, topological sort.
1878    /// Report the compiled form each node has
1879    /// (`CompileEvent::CompileLevelSelected`), a property of the node
1880    /// and its wire types, so the log is the same on every engine
1881    /// (engines.md §7): a native form, a compiled `u64` op, a slot
1882    /// kit, a slot copy, or interpretation only. A node is named by
1883    /// the output it produces when it produces one.
1884    fn log_forms(resolved: &ResolvedDag, log: &mut crate::dsl::events::CompileEventLog) {
1885        for (node_idx, node) in resolved.nodes.iter().enumerate() {
1886            let wire_types = wire_types_of(resolved, node_idx);
1887            // Without the `jit` feature there is no native form to
1888            // report: every node reaches its closure, its slot copy, or
1889            // interpretation, which the arms below name.
1890            #[cfg(feature = "jit")]
1891            let native = !matches!(
1892                crate::compile::jit::classify_node_typed(node.as_ref(), &wire_types),
1893                crate::compile::jit::JitOp::Fallback
1894            );
1895            #[cfg(not(feature = "jit"))]
1896            let native = false;
1897            let level = if native {
1898                "native"
1899            } else {
1900                match node_step_op(node.as_ref(), &wire_types) {
1901                    Some((crate::compile::closures::StepOp::Copy, _)) => "slot copy",
1902                    Some((crate::compile::closures::StepOp::U64(_), _)) => "compiled u64 op",
1903                    Some((crate::compile::closures::StepOp::Slot(_), _)) => "slot kit",
1904                    None => "interpreted",
1905                }
1906            };
1907            let name = resolved
1908                .output_map
1909                .iter()
1910                .find(|(_, (ni, _))| *ni == node_idx)
1911                .map(|(n, _)| n.clone())
1912                .unwrap_or_else(|| node.meta().name.clone());
1913            log.push(crate::dsl::events::CompileEvent::CompileLevelSelected {
1914                node: name,
1915                level: level.to_string(),
1916            });
1917        }
1918    }
1919
1920    /// Close the log with the program's shape
1921    /// (`CompileEvent::Summary`): the resolved node and output counts,
1922    /// the same on every engine, and the constants the build folded,
1923    /// counted from the log itself.
1924    fn log_summary(
1925        log: Option<&mut crate::dsl::events::CompileEventLog>,
1926        nodes: usize,
1927        outputs: usize,
1928    ) {
1929        if let Some(log) = log {
1930            let constants_folded = log
1931                .events()
1932                .iter()
1933                .filter(|e| matches!(e, crate::dsl::events::CompileEvent::ConstantFolded { .. }))
1934                .count();
1935            log.push(crate::dsl::events::CompileEvent::Summary {
1936                nodes,
1937                outputs,
1938                constants_folded,
1939            });
1940        }
1941    }
1942
1943    /// Resolve with no log. Only the pure-native paths take it, and
1944    /// those need code generation, so it is gated as they are.
1945    #[cfg(feature = "jit")]
1946    fn resolve(self) -> Result<ResolvedDag, AssemblyError> {
1947        self.resolve_with_log(None)
1948    }
1949
1950    fn resolve_with_log(
1951        mut self,
1952        mut log: Option<&mut crate::dsl::events::CompileEventLog>,
1953    ) -> Result<ResolvedDag, AssemblyError> {
1954        // Consts first: a captured const adds inputs, which the variance
1955        // and extern passes below see like any other.
1956        self.capture_consts()?;
1957        // Input variance (input_variance.md §4). An input whose type the
1958        // compiler inferred rather than the author declared is *open*:
1959        // by the host's setting it keeps its inferred type, stops the
1960        // build, or takes any value, converted in front of its readers
1961        // by a node placed below. Coordinates are never open: they are
1962        // positioned with `set_inputs` and are always `u64`.
1963        let open: Vec<usize> = self
1964            .input_defs
1965            .iter()
1966            .enumerate()
1967            .filter(|(_, d)| {
1968                d.kind != crate::kernel::InputKind::Coordinate
1969                    && d.type_origin == crate::kernel::TypeOrigin::Inferred
1970                    && d.port_type != PortType::Dyn
1971            })
1972            .map(|(i, _)| i)
1973            .collect();
1974        let variance_level = match self.input_variance {
1975            crate::dsl::compile::InputVariance::Fixed => None,
1976            crate::dsl::compile::InputVariance::Error => {
1977                if !open.is_empty() {
1978                    return Err(AssemblyError::OpenInputs(
1979                        open.iter()
1980                            .map(|&i| {
1981                                (
1982                                    self.input_defs[i].name.clone(),
1983                                    self.input_defs[i].port_type,
1984                                )
1985                            })
1986                            .collect(),
1987                    ));
1988                }
1989                None
1990            }
1991            crate::dsl::compile::InputVariance::Warn => {
1992                Some(crate::dsl::events::EventLevel::Warning)
1993            }
1994            crate::dsl::compile::InputVariance::Info => Some(crate::dsl::events::EventLevel::Info),
1995        };
1996        if variance_level.is_some() {
1997            for &i in &open {
1998                let def = &mut self.input_defs[i];
1999                def.converts_to = Some(def.port_type);
2000                def.port_type = PortType::Dyn;
2001            }
2002        }
2003        // An extern without a default is `None` until the host sets it,
2004        // and every consumer reads `None` through it; the log names each
2005        // one so a host knows what it must set (engines.md §3.3).
2006        // A cursor's slots are `None` until narrowed by design and are
2007        // not externs a host sets by value.
2008        if let Some(log) = log.as_deref_mut() {
2009            let cursor_slot = |name: &str| {
2010                self.cursor_schemas
2011                    .iter()
2012                    .any(|s| name.starts_with(&format!("{}__cursor", s.name)))
2013            };
2014            for def in &self.input_defs {
2015                if matches!(
2016                    def.kind,
2017                    crate::kernel::InputKind::ExternalWrite
2018                        | crate::kernel::InputKind::IterationExtern
2019                ) && def.default == crate::ast::Value::None
2020                    && !cursor_slot(&def.name)
2021                {
2022                    log.push(crate::dsl::events::CompileEvent::ExternWithoutDefault {
2023                        name: def.name.clone(),
2024                        port_type: def.port_type.to_string(),
2025                    });
2026                }
2027            }
2028        }
2029        // Build name → index map for nodes
2030        let mut name_to_idx: HashMap<String, usize> = HashMap::new();
2031        for (i, pn) in self.nodes.iter().enumerate() {
2032            if name_to_idx.contains_key(&pn.name) {
2033                return Err(AssemblyError::DuplicateNode(pn.name.clone()));
2034            }
2035            name_to_idx.insert(pn.name.clone(), i);
2036        }
2037
2038        // Build input name → index map (covers both coords and captures)
2039        let input_to_idx: HashMap<String, usize> = self
2040            .input_defs
2041            .iter()
2042            .enumerate()
2043            .map(|(i, d)| (d.name.clone(), i))
2044            .collect();
2045
2046        // Validate arity
2047        for pn in &self.nodes {
2048            let expected = pn.node.meta().wire_inputs().len();
2049            let got = pn.inputs.len();
2050            if expected != got {
2051                return Err(AssemblyError::ArityMismatch {
2052                    node_name: pn.name.clone(),
2053                    expected,
2054                    got,
2055                });
2056            }
2057        }
2058
2059        let mut all_nodes: Vec<PendingNode> = Vec::new();
2060        let mut all_name_to_idx: HashMap<String, usize> = HashMap::new();
2061        let mut adapter_count = 0usize;
2062        let mut assertion_count = 0usize;
2063        let strict_values = self.strict_values;
2064        let strict = self.strict;
2065        // The assertions this pass inserts, by node index, with the
2066        // constraint each enforces: the structural mark
2067        // `constraint_proof` reads to accept an upstream guard.
2068        let mut inserted_guards: HashMap<usize, crate::dsl::const_constraints::ConstConstraint> =
2069            HashMap::new();
2070        // Nodes whose output the author declared `volatile`: never
2071        // constants, whatever their inputs.
2072        let volatile_nodes: std::collections::HashSet<String> = self
2073            .output_modifiers
2074            .iter()
2075            .filter(|(_, m)| m.is_volatile())
2076            .filter_map(|(name, _)| match self.outputs.get(name) {
2077                Some(WireRef::Node(node, _)) => Some(node.clone()),
2078                _ => None,
2079            })
2080            .collect();
2081
2082        for pn in self.nodes {
2083            let idx = all_nodes.len();
2084            all_name_to_idx.insert(pn.name.clone(), idx);
2085            all_nodes.push(pn);
2086        }
2087
2088        let mut resolved_wiring: Vec<Vec<WireSource>> = Vec::new();
2089        // One converter per (input, target type), shared by its readers.
2090        let mut converters: HashMap<(usize, PortType), usize> = HashMap::new();
2091
2092        for node_idx in 0..all_nodes.len() {
2093            let mut node_wiring = Vec::new();
2094
2095            for (port_idx, wire_ref) in all_nodes[node_idx].inputs.clone().iter().enumerate() {
2096                let port = all_nodes[node_idx].node.meta().wire_inputs()[port_idx].clone();
2097                let expected_type = port.typ;
2098
2099                let (source, source_type) = match wire_ref {
2100                    WireRef::Input(name) => {
2101                        let input_idx = input_to_idx
2102                            .get(name)
2103                            .ok_or_else(|| AssemblyError::UnknownWire(name.clone()))?;
2104                        let source_type = self.input_defs[*input_idx].port_type;
2105                        (WireSource::Input(*input_idx), source_type)
2106                    }
2107                    WireRef::Node(name, out_port) => {
2108                        let src_idx = all_name_to_idx
2109                            .get(name)
2110                            .ok_or_else(|| AssemblyError::UnknownWire(name.clone()))?;
2111                        let src_type = all_nodes[*src_idx].node.meta().outs[*out_port].typ;
2112                        (WireSource::NodeOutput(*src_idx, *out_port), src_type)
2113                    }
2114                };
2115
2116                // A port that takes the wire as it is gets no
2117                // adapter and no check: converting the value would
2118                // change what the node reads. The port says so
2119                // itself (`Port::accepts_any_type`), so the check stays
2120                // on for the node's other ports, such as `pick`'s `Bool`
2121                // selectors.
2122                //
2123                // A `Dyn` input feeding a typed port reads through a
2124                // converter to that type (input_variance.md §5), placed
2125                // once per input and type and shared by every reader.
2126                if source_type == PortType::Dyn
2127                    && !port.accepts_any_type
2128                    && expected_type != PortType::Dyn
2129                {
2130                    let WireSource::Input(input_idx) = source else {
2131                        unreachable!("only an input slot is typed `Dyn`")
2132                    };
2133                    let conv_idx = match converters.get(&(input_idx, expected_type)) {
2134                        Some(&idx) => idx,
2135                        None => {
2136                            let converter = crate::convert::InputConverter::new(
2137                                &self.input_defs[input_idx].name,
2138                                expected_type,
2139                            );
2140                            let conv_name = converter.meta().name.clone();
2141                            let idx = all_nodes.len();
2142                            all_name_to_idx.insert(conv_name.clone(), idx);
2143                            while resolved_wiring.len() <= idx {
2144                                resolved_wiring.push(Vec::new());
2145                            }
2146                            resolved_wiring[idx] = vec![source.clone()];
2147                            all_nodes.push(PendingNode {
2148                                name: conv_name,
2149                                node: Box::new(converter),
2150                                inputs: vec![],
2151                                strict_values: None,
2152                            });
2153                            converters.insert((input_idx, expected_type), idx);
2154                            idx
2155                        }
2156                    };
2157                    node_wiring.push(WireSource::NodeOutput(conv_idx, 0));
2158                } else if port.accepts_any_type || source_type == expected_type {
2159                    node_wiring.push(source);
2160                } else if let Some(adapter) = auto_adapter(source_type, expected_type) {
2161                    if strict {
2162                        return Err(AssemblyError::Other(format!(
2163                            "strict mode: implicit type coercion {source_type} → {expected_type} \
2164                             into '{}'. Use an explicit conversion function (e.g., to_f64, \
2165                             to_i64, f64_to_u64).",
2166                            all_nodes[node_idx].name
2167                        )));
2168                    }
2169                    let adapter_name = format!("__adapt_{adapter_count}");
2170                    adapter_count += 1;
2171                    let adapter_idx = all_nodes.len();
2172
2173                    if let Some(ref mut log) = log {
2174                        let from_name = match wire_ref {
2175                            WireRef::Input(n) => n.clone(),
2176                            WireRef::Node(n, _) => n.clone(),
2177                        };
2178                        let to_name = all_nodes[node_idx].name.clone();
2179                        log.push(if is_lossless_widening(source_type, expected_type) {
2180                            crate::dsl::events::CompileEvent::TypeWidening {
2181                                from: source_type.to_keyword(),
2182                                to: expected_type.to_keyword(),
2183                                context: format!("{from_name} → {to_name}"),
2184                            }
2185                        } else {
2186                            crate::dsl::events::CompileEvent::TypeAdapterInserted {
2187                                from_node: from_name,
2188                                to_node: to_name,
2189                                adapter: format!("{source_type:?}→{expected_type:?}"),
2190                            }
2191                        });
2192                    }
2193
2194                    all_name_to_idx.insert(adapter_name.clone(), adapter_idx);
2195
2196                    let adapter_wiring = vec![source];
2197                    while resolved_wiring.len() <= adapter_idx {
2198                        resolved_wiring.push(Vec::new());
2199                    }
2200                    resolved_wiring[adapter_idx] = adapter_wiring;
2201
2202                    // The adapter converts for the sink, so it is
2203                    // written in the sink's scope and linted under
2204                    // that scope's pragmas.
2205                    let sink_mark = all_nodes[node_idx].strict_values;
2206                    all_nodes.push(PendingNode {
2207                        name: adapter_name,
2208                        node: adapter,
2209                        inputs: vec![],
2210                        strict_values: sink_mark,
2211                    });
2212
2213                    node_wiring.push(WireSource::NodeOutput(adapter_idx, 0));
2214                } else {
2215                    let from_name = match wire_ref {
2216                        WireRef::Input(n) => n.clone(),
2217                        WireRef::Node(n, _) => n.clone(),
2218                    };
2219                    return Err(AssemblyError::TypeMismatch {
2220                        from_node: from_name,
2221                        from_port: match wire_ref {
2222                            WireRef::Input(_) => 0,
2223                            WireRef::Node(_, p) => *p,
2224                        },
2225                        from_type: source_type,
2226                        to_node: all_nodes[node_idx].name.clone(),
2227                        to_port: port_idx,
2228                        to_type: expected_type,
2229                    });
2230                }
2231
2232                // === Strict-wire assertion insertion (graph_compiler.md §2) ===
2233                //
2234                // After a wire is resolved (and any type adapter
2235                // inserted), the sink port's declared `constraint`
2236                // is checked under strict_values as the scope the
2237                // sink was written in sets it: a module body's own
2238                // pragmas, or the program's. A compile-time
2239                // constant source is checked now, and a violation
2240                // stops the build; the guard this pass inserted for
2241                // the same constraint needs no second guard; any
2242                // other source gets an `AssertValue` spliced in
2243                // front of the sink.
2244                let sink_port = &all_nodes[node_idx].node.meta().wire_inputs()[port_idx];
2245                if let Some(constraint) = sink_port.constraint {
2246                    let last_source = node_wiring.last().expect("wire just pushed").clone();
2247                    let proof = if all_nodes[node_idx].strict_values.unwrap_or(strict_values) {
2248                        constraint_proof(
2249                            &all_nodes,
2250                            &inserted_guards,
2251                            &volatile_nodes,
2252                            &last_source,
2253                            &constraint,
2254                        )
2255                    } else {
2256                        ConstraintProof::NotChecked
2257                    };
2258                    if let ConstraintProof::Violated { value, message } = &proof {
2259                        let sink = &all_nodes[node_idx];
2260                        // A parser's own message says what it refused.
2261                        let detail = match constraint {
2262                            crate::dsl::const_constraints::ConstConstraint::StrParser(_) => {
2263                                format!(" ({message})")
2264                            }
2265                            _ => String::new(),
2266                        };
2267                        return Err(AssemblyError::Other(format!(
2268                            "strict_values: port '{}' of '{}' ({}) must be {}, but its \
2269                             source is the constant {value}{detail}",
2270                            sink_port.name,
2271                            sink.name,
2272                            sink.node.meta().name,
2273                            crate::library::assertions::describe_constraint(&constraint),
2274                        )));
2275                    }
2276                    if matches!(proof, ConstraintProof::Unproven) {
2277                        let assert_name = format!("__assert_v_{assertion_count}");
2278                        assertion_count += 1;
2279                        let assert_idx = all_nodes.len();
2280
2281                        if let Some(ref mut log) = log {
2282                            let from_name = match wire_ref {
2283                                WireRef::Input(n) => n.clone(),
2284                                WireRef::Node(n, _) => n.clone(),
2285                            };
2286                            log.push(crate::dsl::events::CompileEvent::AssertionInserted {
2287                                from_node: from_name,
2288                                to_node: all_nodes[node_idx].name.clone(),
2289                                kind: format!("{:?} value-assert {:?}", expected_type, constraint),
2290                            });
2291                        }
2292
2293                        all_name_to_idx.insert(assert_name.clone(), assert_idx);
2294                        let assert_wiring = vec![last_source];
2295                        while resolved_wiring.len() <= assert_idx {
2296                            resolved_wiring.push(Vec::new());
2297                        }
2298                        resolved_wiring[assert_idx] = assert_wiring;
2299
2300                        all_nodes.push(PendingNode {
2301                            name: assert_name,
2302                            node: crate::library::assertions::assert_value_node(
2303                                expected_type,
2304                                constraint,
2305                            ),
2306                            inputs: vec![],
2307                            strict_values: None,
2308                        });
2309                        inserted_guards.insert(assert_idx, constraint);
2310
2311                        // Replace the just-pushed source with the
2312                        // assertion's output.
2313                        *node_wiring.last_mut().unwrap() = WireSource::NodeOutput(assert_idx, 0);
2314                    } else if let Some(ref mut log) = log {
2315                        let from_name = match wire_ref {
2316                            WireRef::Input(n) => n.clone(),
2317                            WireRef::Node(n, _) => n.clone(),
2318                        };
2319                        log.push(crate::dsl::events::CompileEvent::AssertionSkipped {
2320                            from_node: from_name,
2321                            to_node: all_nodes[node_idx].name.clone(),
2322                            reason: proof.skip_reason().into(),
2323                        });
2324                    }
2325                }
2326            }
2327
2328            while resolved_wiring.len() <= node_idx {
2329                resolved_wiring.push(Vec::new());
2330            }
2331            resolved_wiring[node_idx] = node_wiring;
2332        }
2333
2334        while resolved_wiring.len() < all_nodes.len() {
2335            resolved_wiring.push(Vec::new());
2336        }
2337
2338        // --- Node fusion optimization ---
2339        //
2340        // Recognize fusible subgraph patterns and replace them with
2341        // semantically equivalent fused nodes (graph_compiler.md §5.2).
2342        {
2343            let rules = crate::compile::fusion::default_rules();
2344            if !rules.is_empty() {
2345                // Collect node indices that are directly referenced by outputs.
2346                // These nodes must not be consumed as interior nodes by fusion.
2347                let mut output_nodes: Vec<usize> = Vec::new();
2348                for wire_ref in self.outputs.values() {
2349                    if let WireRef::Node(node_name, _) = wire_ref
2350                        && let Some(&idx) = all_name_to_idx.get(node_name)
2351                    {
2352                        output_nodes.push(idx);
2353                    }
2354                }
2355
2356                // Convert to Option<Box<dyn PolydatNode>> for the fusion
2357                // pass, which replaces nodes in place, so each index
2358                // keeps its scope mark for the round-trip lint.
2359                let marks: Vec<Option<bool>> =
2360                    all_nodes.iter().map(|pn| pn.strict_values).collect();
2361                let mut opt_nodes: Vec<Option<Box<dyn PolydatNode>>> =
2362                    all_nodes.into_iter().map(|pn| Some(pn.node)).collect();
2363
2364                let fused_count = crate::compile::fusion::apply_fusions(
2365                    &mut opt_nodes,
2366                    &mut resolved_wiring,
2367                    &mut all_name_to_idx,
2368                    &rules,
2369                    &output_nodes,
2370                );
2371                if fused_count > 0
2372                    && let Some(ref mut log) = log
2373                {
2374                    log.push(crate::dsl::events::CompileEvent::FusionApplied {
2375                        pattern: "subgraph".into(),
2376                        nodes_replaced: fused_count,
2377                    });
2378                }
2379
2380                // Convert back, rebuilding PendingNode wrappers.
2381                // Fused-away nodes (None) get placeholder names.
2382                all_nodes = opt_nodes
2383                    .into_iter()
2384                    .enumerate()
2385                    .map(|(i, opt)| PendingNode {
2386                        name: all_name_to_idx
2387                            .iter()
2388                            .find(|&(_, &idx)| idx == i)
2389                            .map(|(n, _)| n.clone())
2390                            .unwrap_or_else(|| format!("__removed_{i}")),
2391                        node: opt.unwrap_or_else(|| {
2392                            Box::new(crate::library::identity::Identity::new(
2393                                crate::ast::PortType::U64,
2394                            ))
2395                        }),
2396                        inputs: vec![], // wiring is in resolved_wiring
2397                        strict_values: marks[i],
2398                    })
2399                    .collect();
2400            }
2401        }
2402
2403        // --- Dead code elimination ---
2404        //
2405        // Trace backward from output nodes to find all reachable nodes.
2406        // Only reachable nodes participate in the topological sort and
2407        // end up in the final kernel. This prunes unused binding chains
2408        // when the caller requests a subset of outputs.
2409        let node_count = all_nodes.len();
2410        let mut reachable = vec![false; node_count];
2411        {
2412            let mut worklist: Vec<usize> = Vec::new();
2413            // Seed with output nodes
2414            for wire_ref in self.outputs.values() {
2415                if let WireRef::Node(node_name, _) = wire_ref
2416                    && let Some(&idx) = all_name_to_idx.get(node_name)
2417                {
2418                    worklist.push(idx);
2419                }
2420            }
2421            // Side-effecting nodes are pinned alive regardless
2422            // of reachability from a declared output. `log_info`
2423            // and friends emit one audit-log line per eval as a
2424            // deliberate side effect — DCE-pruning them would
2425            // silently drop diagnostic logging the operator
2426            // explicitly asked for. The set is closed and
2427            // matched by node-meta name so the marker survives
2428            // any wiring shape (passthrough, captured-but-unused,
2429            // synthesised wrapper, etc.).
2430            for (idx, pn) in all_nodes.iter().enumerate() {
2431                if matches!(
2432                    pn.node.meta().name.as_str(),
2433                    "log_debug" | "log_info" | "log_warn" | "log_error"
2434                ) {
2435                    worklist.push(idx);
2436                }
2437            }
2438            // Walk backward through wiring
2439            while let Some(idx) = worklist.pop() {
2440                if reachable[idx] {
2441                    continue;
2442                }
2443                reachable[idx] = true;
2444                for source in &resolved_wiring[idx] {
2445                    if let WireSource::NodeOutput(upstream, _) = source
2446                        && !reachable[*upstream]
2447                    {
2448                        worklist.push(*upstream);
2449                    }
2450                }
2451            }
2452        }
2453        let live_count = reachable.iter().filter(|&&r| r).count();
2454
2455        // Every converter that survived pruning is reported at the level
2456        // the host asked for (input_variance.md §4), in the order it was
2457        // placed; an input the setting opened that nothing reads is
2458        // reported once too, so no opened input goes unseen.
2459        if let Some(log) = log.as_deref_mut() {
2460            let mut placed: Vec<(usize, usize, PortType)> = converters
2461                .iter()
2462                .filter(|&(_, &idx)| reachable[idx])
2463                .map(|(&(input, to), &idx)| (idx, input, to))
2464                .collect();
2465            placed.sort_unstable_by_key(|&(idx, _, _)| idx);
2466            for &(idx, input, to) in &placed {
2467                let def = &self.input_defs[input];
2468                let (origin, level) = match (def.converts_to, variance_level) {
2469                    (Some(_), Some(level)) => ("inferred", level),
2470                    _ => ("declared dyn", crate::dsl::events::EventLevel::Info),
2471                };
2472                log.push(crate::dsl::events::CompileEvent::InputConverterInserted {
2473                    input: def.name.clone(),
2474                    to: to.to_keyword().to_string(),
2475                    node: all_nodes[idx].name.clone(),
2476                    origin: origin.to_string(),
2477                    level,
2478                });
2479            }
2480            if let Some(level) = variance_level {
2481                for &input in &open {
2482                    if placed.iter().any(|&(_, i, _)| i == input) {
2483                        continue;
2484                    }
2485                    let def = &self.input_defs[input];
2486                    log.push(crate::dsl::events::CompileEvent::InputConverterInserted {
2487                        input: def.name.clone(),
2488                        to: def
2489                            .converts_to
2490                            .unwrap_or(def.port_type)
2491                            .to_keyword()
2492                            .to_string(),
2493                        node: "(none: nothing reads it)".to_string(),
2494                        origin: "inferred".to_string(),
2495                        level,
2496                    });
2497                }
2498            }
2499        }
2500
2501        // Topological sort (Kahn's algorithm) over reachable nodes only
2502        let mut in_degree = vec![0usize; node_count];
2503        let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); node_count];
2504
2505        for (node_idx, wiring) in resolved_wiring.iter().enumerate() {
2506            if !reachable[node_idx] {
2507                continue;
2508            }
2509            for source in wiring {
2510                if let WireSource::NodeOutput(upstream, _) = source {
2511                    in_degree[node_idx] += 1;
2512                    dependents[*upstream].push(node_idx);
2513                }
2514            }
2515        }
2516
2517        let mut queue: Vec<usize> = (0..node_count)
2518            .filter(|i| reachable[*i] && in_degree[*i] == 0)
2519            .collect();
2520        let mut sorted_order: Vec<usize> = Vec::with_capacity(live_count);
2521
2522        while let Some(idx) = queue.pop() {
2523            sorted_order.push(idx);
2524            for &dep in &dependents[idx] {
2525                in_degree[dep] -= 1;
2526                if in_degree[dep] == 0 {
2527                    queue.push(dep);
2528                }
2529            }
2530        }
2531
2532        if sorted_order.len() != live_count {
2533            return Err(AssemblyError::CycleDetected);
2534        }
2535
2536        let mut old_to_new = vec![0usize; node_count];
2537        for (new_idx, &old_idx) in sorted_order.iter().enumerate() {
2538            old_to_new[old_idx] = new_idx;
2539        }
2540
2541        // Each final node's scope mark, for the round-trip lint.
2542        let final_marks: Vec<Option<bool>> = sorted_order
2543            .iter()
2544            .map(|&old_idx| all_nodes[old_idx].strict_values)
2545            .collect();
2546        let mut sorted_nodes: Vec<Option<Box<dyn PolydatNode>>> =
2547            all_nodes.into_iter().map(|pn| Some(pn.node)).collect();
2548
2549        let final_nodes: Vec<Box<dyn PolydatNode>> = sorted_order
2550            .iter()
2551            .map(|&old_idx| sorted_nodes[old_idx].take().unwrap())
2552            .collect();
2553
2554        let final_wiring: Vec<Vec<WireSource>> = sorted_order
2555            .iter()
2556            .map(|&old_idx| {
2557                resolved_wiring[old_idx]
2558                    .iter()
2559                    .map(|source| match source {
2560                        WireSource::Input(c) => WireSource::Input(*c),
2561                        WireSource::NodeOutput(old_up, port) => {
2562                            WireSource::NodeOutput(old_to_new[*old_up], *port)
2563                        }
2564                    })
2565                    .collect()
2566            })
2567            .collect();
2568
2569        let mut final_output_map: HashMap<String, (usize, usize)> = HashMap::new();
2570        for (name, wire_ref) in &self.outputs {
2571            match wire_ref {
2572                WireRef::Input(coord_name) => {
2573                    return Err(AssemblyError::UnknownWire(format!(
2574                        "output '{name}' references coordinate '{coord_name}' directly; \
2575                         wire through a node instead"
2576                    )));
2577                }
2578                WireRef::Node(node_name, port) => {
2579                    let old_idx = all_name_to_idx
2580                        .get(node_name)
2581                        .ok_or_else(|| AssemblyError::UnknownWire(node_name.clone()))?;
2582                    final_output_map.insert(name.clone(), (old_to_new[*old_idx], *port));
2583                }
2584            }
2585        }
2586
2587        // Structural type-round-trip lint (see
2588        // `compile::roundtrip_lint`): a value modulated `T → Y → … → T`
2589        // through pure conversion/formatting machinery violates the
2590        // native-types-stay-native principle. Warning by default; a
2591        // hard error when the scope the restoring node was written in
2592        // has strict_values on: a module body's own pragmas, or the
2593        // program's (graph_compiler.md §2.3, polydat_grammar.md §14.1).
2594        for (i, f) in crate::compile::roundtrip_lint::lint_type_round_trips(
2595            &final_nodes,
2596            &final_wiring,
2597            &self.input_defs,
2598        ) {
2599            if final_marks[i].unwrap_or(strict_values) {
2600                return Err(AssemblyError::Other(f.message()));
2601            }
2602            // Through the audit log, which the host routes; a library
2603            // does not write to the process's stderr on its own.
2604            crate::library::support::audit::warn(&f.message());
2605            if let Some(ref mut log) = log {
2606                log.push(crate::dsl::events::CompileEvent::Warning {
2607                    message: f.message(),
2608                });
2609            }
2610        }
2611
2612        if let Some(log) = log {
2613            let resolved_view = ResolvedDag {
2614                nodes: final_nodes,
2615                wiring: final_wiring,
2616                input_defs: self.input_defs,
2617                coord_count: self.coord_count,
2618                output_map: final_output_map,
2619                output_order: self.output_order,
2620                source: self.source,
2621                context: self.context,
2622                output_modifiers: self.output_modifiers,
2623                const_outputs: self.const_outputs,
2624                const_inits: self.const_inits,
2625                cursor_schemas: self.cursor_schemas,
2626                ledger: self.ledger,
2627                resources: self.resources,
2628            };
2629            Self::log_forms(&resolved_view, log);
2630            return Ok(resolved_view);
2631        }
2632        Ok(ResolvedDag {
2633            nodes: final_nodes,
2634            wiring: final_wiring,
2635            input_defs: self.input_defs,
2636            coord_count: self.coord_count,
2637            output_map: final_output_map,
2638            output_order: self.output_order,
2639            source: self.source,
2640            context: self.context,
2641            output_modifiers: self.output_modifiers,
2642            const_outputs: self.const_outputs,
2643            const_inits: self.const_inits,
2644            cursor_schemas: self.cursor_schemas,
2645            ledger: self.ledger,
2646            resources: self.resources,
2647        })
2648    }
2649}
2650
2651/// What the strict-wire pass knows about a constrained wire at
2652/// build (graph_compiler.md §2).
2653enum ConstraintProof {
2654    /// `strict_values` is off: nothing is checked.
2655    NotChecked,
2656    /// The source is a compile-time constant whose value satisfies
2657    /// the constraint.
2658    ConstantSatisfies,
2659    /// The source is a compile-time constant that evaluates to
2660    /// `None`, which the sink never reads (none_semantics.md Rule 1).
2661    ConstantNone,
2662    /// The source is the guard this pass inserted for the same
2663    /// constraint.
2664    Guarded,
2665    /// The source is a compile-time constant whose value fails the
2666    /// constraint.
2667    Violated {
2668        /// The constant, as displayed.
2669        value: String,
2670        /// The constraint's own message for the value.
2671        message: String,
2672    },
2673    /// Nothing is known at build; the wire needs a runtime guard.
2674    Unproven,
2675}
2676
2677impl ConstraintProof {
2678    /// The reason the `AssertionSkipped` event gives for a wire that
2679    /// gets no guard.
2680    fn skip_reason(&self) -> &'static str {
2681        match self {
2682            ConstraintProof::NotChecked => "strict_values not enabled",
2683            ConstraintProof::ConstantSatisfies => "constant source satisfies the constraint",
2684            ConstraintProof::ConstantNone => "constant source is None",
2685            ConstraintProof::Guarded => "upstream assertion",
2686            ConstraintProof::Violated { .. } => "constant source fails the constraint",
2687            ConstraintProof::Unproven => "no skip rule matched",
2688        }
2689    }
2690}
2691
2692/// Decide what the build knows about `src` against the sink's value
2693/// `constraint`.
2694///
2695/// - A **compile-time constant** is a node with no wire inputs that is
2696///   not nondeterministic: its purity is not
2697///   [`Purity::Nondeterministic`](crate::ast::Purity::Nondeterministic)
2698///   and no `volatile` output names it. It is evaluated here and its
2699///   value checked, so a violation is a build error rather than a
2700///   runtime panic.
2701/// - An **inserted guard** is an `AssertValue` this pass spliced in for
2702///   an equal constraint, known by its index in `inserted_guards`.
2703/// - Everything else, including an input slot and a nondeterministic
2704///   zero-input node, is unproven.
2705fn constraint_proof(
2706    all_nodes: &[PendingNode],
2707    inserted_guards: &HashMap<usize, crate::dsl::const_constraints::ConstConstraint>,
2708    volatile_nodes: &std::collections::HashSet<String>,
2709    src: &WireSource,
2710    constraint: &crate::dsl::const_constraints::ConstConstraint,
2711) -> ConstraintProof {
2712    let WireSource::NodeOutput(idx, port) = src else {
2713        return ConstraintProof::Unproven;
2714    };
2715    if let Some(guarded) = inserted_guards.get(idx) {
2716        return if crate::library::assertions::same_constraint(guarded, constraint) {
2717            ConstraintProof::Guarded
2718        } else {
2719            ConstraintProof::Unproven
2720        };
2721    }
2722    let pending = &all_nodes[*idx];
2723    let node = pending.node.as_ref();
2724    let nondeterministic = matches!(node.purity(), crate::ast::Purity::Nondeterministic { .. })
2725        || volatile_nodes.contains(&pending.name);
2726    if !node.meta().wire_inputs().is_empty() || nondeterministic {
2727        return ConstraintProof::Unproven;
2728    }
2729    // A panic here is the same failure the constant fold reports
2730    // with its own diagnostic; the wire keeps its runtime guard.
2731    let mut outputs = vec![crate::ast::Value::None; node.meta().outs.len()];
2732    let evaluated = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2733        node.eval(&[], &mut outputs);
2734    }));
2735    if evaluated.is_err() {
2736        return ConstraintProof::Unproven;
2737    }
2738    let Some(value) = outputs.get(*port) else {
2739        return ConstraintProof::Unproven;
2740    };
2741    if matches!(value, crate::ast::Value::None) {
2742        return ConstraintProof::ConstantNone;
2743    }
2744    match crate::library::assertions::check_value(constraint, value, "the value") {
2745        Some(Ok(())) => ConstraintProof::ConstantSatisfies,
2746        Some(Err(message)) => ConstraintProof::Violated {
2747            value: value.to_display_string(),
2748            message,
2749        },
2750        None => ConstraintProof::Unproven,
2751    }
2752}
2753
2754/// The `shared` bindings of a resolved graph, by name: each is an
2755/// extern the compiled kernels bind to a cell (engines.md §3.6).
2756pub(crate) fn shared_outputs_of(resolved: &ResolvedDag) -> Vec<&str> {
2757    let mut shared: Vec<&str> = resolved
2758        .output_modifiers
2759        .iter()
2760        .filter(|(_, m)| **m == crate::dsl::ast::BindingModifier::SHARED)
2761        .map(|(name, _)| name.as_str())
2762        .collect();
2763    shared.sort();
2764    shared
2765}
2766
2767/// Whether the adapter from `from` to `to` is a lossless numeric
2768/// widening, the class the adapter table lists first: reported as a
2769/// `TypeWidening`, where every other adapter is a `TypeAdapterInserted`.
2770fn is_lossless_widening(from: PortType, to: PortType) -> bool {
2771    use PortType as P;
2772    matches!(
2773        (from, to),
2774        (P::U64, P::F64)
2775            | (P::U32, P::U64)
2776            | (P::U32, P::I64)
2777            | (P::U32, P::F64)
2778            | (P::I32, P::I64)
2779            | (P::I32, P::F64)
2780            | (P::I64, P::F64)
2781            | (P::F32, P::F64)
2782    )
2783}
2784
2785pub(crate) fn wire_types_of(resolved: &ResolvedDag, node_idx: usize) -> Vec<PortType> {
2786    resolved.wiring[node_idx]
2787        .iter()
2788        .map(|src| match src {
2789            crate::kernel::WireSource::Input(i) => resolved.input_defs[*i].port_type,
2790            crate::kernel::WireSource::NodeOutput(j, p) => resolved.nodes[*j].meta().outs[*p].typ,
2791        })
2792        .collect()
2793}
2794
2795/// The lossless adapter node from one port type to another, if the
2796/// catalog has one: what the assembler inserts between a wire and a port
2797/// of different types.
2798pub fn auto_adapter(from: PortType, to: PortType) -> Option<Box<dyn PolydatNode>> {
2799    use crate::library::convert::{
2800        BoolToStr, BoolToU64, F32ToF64, F32ToString, I32ToF64, I32ToI64, I32ToString, I64ToF64,
2801        I64ToString, U32ToF64, U32ToI64, U32ToString, U32ToU64,
2802    };
2803    use crate::library::polyfill as P;
2804    use crate::library::polyfill_128 as W;
2805    use crate::library::polyfill_complete as C;
2806    use crate::library::polyfill_narrow as N;
2807    match (from, to) {
2808        // ── Numeric widening (lossless) ─────────────────────────
2809        (PortType::U64, PortType::F64) => Some(Box::new(U64ToF64::new())),
2810        (PortType::U32, PortType::U64) => Some(Box::new(U32ToU64::new())),
2811        (PortType::U32, PortType::I64) => Some(Box::new(U32ToI64::new())),
2812        (PortType::U32, PortType::F64) => Some(Box::new(U32ToF64::new())),
2813        (PortType::I32, PortType::I64) => Some(Box::new(I32ToI64::new())),
2814        (PortType::I32, PortType::F64) => Some(Box::new(I32ToF64::new())),
2815        // Rounds past 2^24 and never fails, which is class A —
2816        // totality, not losslessness. It is the scalar counterpart of
2817        // the element-wise `VecI32 -> VecF32` below.
2818        (PortType::I32, PortType::F32) => Some(Box::new(P::I32ToF32::new())),
2819        (PortType::I64, PortType::F64) => Some(Box::new(I64ToF64::new())),
2820        (PortType::F32, PortType::F64) => Some(Box::new(F32ToF64::new())),
2821
2822        // ── X → Str (every type renders as a string) ────────────
2823        (PortType::U64, PortType::Str) => Some(Box::new(U64ToString::new())),
2824        (PortType::F64, PortType::Str) => Some(Box::new(F64ToString::new())),
2825        (PortType::Bool, PortType::Str) => Some(Box::new(BoolToStr::new())),
2826        (PortType::Json, PortType::Str) => Some(Box::new(JsonToStr::new())),
2827        (PortType::U32, PortType::Str) => Some(Box::new(U32ToString::new())),
2828        (PortType::I32, PortType::Str) => Some(Box::new(I32ToString::new())),
2829        (PortType::I64, PortType::Str) => Some(Box::new(I64ToString::new())),
2830        (PortType::F32, PortType::Str) => Some(Box::new(F32ToString::new())),
2831
2832        // ── Bool ↔ numeric (always-defined; 1/0 mapping) ────────
2833        (PortType::Bool, PortType::U64) => Some(Box::new(BoolToU64::new())),
2834        (PortType::Bool, PortType::U32) => Some(Box::new(P::BoolToU32::new())),
2835        (PortType::Bool, PortType::I64) => Some(Box::new(P::BoolToI64::new())),
2836        (PortType::Bool, PortType::I32) => Some(Box::new(P::BoolToI32::new())),
2837        (PortType::Bool, PortType::F64) => Some(Box::new(P::BoolToF64::new())),
2838        (PortType::Bool, PortType::F32) => Some(Box::new(P::BoolToF32::new())),
2839        (PortType::U64, PortType::Bool) => {
2840            Some(Box::new(crate::library::convert::U64ToBool::new()))
2841        }
2842        (PortType::U32, PortType::Bool) => Some(Box::new(P::U32ToBool::new())),
2843        (PortType::I64, PortType::Bool) => Some(Box::new(P::I64ToBool::new())),
2844        (PortType::I32, PortType::Bool) => Some(Box::new(P::I32ToBool::new())),
2845        (PortType::F64, PortType::Bool) => Some(Box::new(P::F64ToBool::new())),
2846        (PortType::F32, PortType::Bool) => Some(Box::new(P::F32ToBool::new())),
2847
2848        // ── X → Bytes (little-endian serialize, always-defined) ─
2849        (PortType::U64, PortType::Bytes) => Some(Box::new(P::U64ToBytes::new())),
2850        (PortType::U32, PortType::Bytes) => Some(Box::new(P::U32ToBytes::new())),
2851        (PortType::I64, PortType::Bytes) => Some(Box::new(P::I64ToBytes::new())),
2852        (PortType::I32, PortType::Bytes) => Some(Box::new(P::I32ToBytes::new())),
2853        (PortType::F64, PortType::Bytes) => Some(Box::new(P::F64ToBytes::new())),
2854        (PortType::F32, PortType::Bytes) => Some(Box::new(P::F32ToBytes::new())),
2855        (PortType::Bool, PortType::Bytes) => Some(Box::new(P::BoolToBytes::new())),
2856        (PortType::VecF32, PortType::Bytes) => Some(Box::new(P::VecF32ToBytes::new())),
2857        (PortType::VecI32, PortType::Bytes) => Some(Box::new(P::VecI32ToBytes::new())),
2858
2859        // ── X → Json (integer / bool wraps; F* and VecF32 are
2860        //              boundary-only because non-finite floats
2861        //              aren't representable in JSON) ────────────
2862        (PortType::U64, PortType::Json) => Some(Box::new(P::U64ToJson::new())),
2863        (PortType::U32, PortType::Json) => Some(Box::new(P::U32ToJson::new())),
2864        (PortType::I64, PortType::Json) => Some(Box::new(P::I64ToJson::new())),
2865        (PortType::I32, PortType::Json) => Some(Box::new(P::I32ToJson::new())),
2866        (PortType::Bool, PortType::Json) => Some(Box::new(P::BoolToJson::new())),
2867        (PortType::VecI32, PortType::Json) => Some(Box::new(P::VecI32ToJson::new())),
2868
2869        // ── Vec ↔ Vec (VecI32 → VecF32 is lossless) ─────────────
2870        (PortType::VecI32, PortType::VecF32) => Some(Box::new(P::VecI32ToVecF32::new())),
2871
2872        // ── Narrow cranelift widths (u8/i8/u16/i16/f16) ─────────
2873        // Lossless widenings + Display renders + Bool maps + LE
2874        // byte / JSON wraps, mirroring the u32/i32/f32 rows.
2875        // (type_system_alignment.md §2)
2876        (PortType::U8, PortType::U64) => Some(Box::new(N::U8ToU64::new())),
2877        (PortType::U8, PortType::U32) => Some(Box::new(N::U8ToU32::new())),
2878        (PortType::U8, PortType::U16) => Some(Box::new(N::U8ToU16::new())),
2879        (PortType::U8, PortType::F64) => Some(Box::new(N::U8ToF64::new())),
2880        (PortType::U16, PortType::U64) => Some(Box::new(N::U16ToU64::new())),
2881        (PortType::U16, PortType::U32) => Some(Box::new(N::U16ToU32::new())),
2882        (PortType::U16, PortType::F64) => Some(Box::new(N::U16ToF64::new())),
2883        (PortType::I8, PortType::I64) => Some(Box::new(N::I8ToI64::new())),
2884        (PortType::I8, PortType::I32) => Some(Box::new(N::I8ToI32::new())),
2885        (PortType::I8, PortType::I16) => Some(Box::new(N::I8ToI16::new())),
2886        (PortType::I8, PortType::F64) => Some(Box::new(N::I8ToF64::new())),
2887        (PortType::I16, PortType::I64) => Some(Box::new(N::I16ToI64::new())),
2888        (PortType::I16, PortType::I32) => Some(Box::new(N::I16ToI32::new())),
2889        (PortType::I16, PortType::F64) => Some(Box::new(N::I16ToF64::new())),
2890        (PortType::F16, PortType::F32) => Some(Box::new(N::F16ToF32::new())),
2891        (PortType::F16, PortType::F64) => Some(Box::new(N::F16ToF64::new())),
2892        // Totality fills: unsigned → strictly-larger signed, and
2893        // narrow int → f32 (exact, magnitude ≤ 2^24). All class A.
2894        (PortType::U8, PortType::I16) => Some(Box::new(N::U8ToI16::new())),
2895        (PortType::U8, PortType::I32) => Some(Box::new(N::U8ToI32::new())),
2896        (PortType::U8, PortType::I64) => Some(Box::new(N::U8ToI64::new())),
2897        (PortType::U8, PortType::F32) => Some(Box::new(N::U8ToF32::new())),
2898        (PortType::U16, PortType::I32) => Some(Box::new(N::U16ToI32::new())),
2899        (PortType::U16, PortType::I64) => Some(Box::new(N::U16ToI64::new())),
2900        (PortType::U16, PortType::F32) => Some(Box::new(N::U16ToF32::new())),
2901        (PortType::I8, PortType::F32) => Some(Box::new(N::I8ToF32::new())),
2902        (PortType::I16, PortType::F32) => Some(Box::new(N::I16ToF32::new())),
2903        (PortType::U8, PortType::F16) => Some(Box::new(N::U8ToF16::new())),
2904        (PortType::I8, PortType::F16) => Some(Box::new(N::I8ToF16::new())),
2905        (PortType::U8, PortType::Str) => Some(Box::new(N::U8ToString::new())),
2906        (PortType::U16, PortType::Str) => Some(Box::new(N::U16ToString::new())),
2907        (PortType::I8, PortType::Str) => Some(Box::new(N::I8ToString::new())),
2908        (PortType::I16, PortType::Str) => Some(Box::new(N::I16ToString::new())),
2909        (PortType::F16, PortType::Str) => Some(Box::new(N::F16ToString::new())),
2910        (PortType::Bool, PortType::U8) => Some(Box::new(N::BoolToU8::new())),
2911        (PortType::Bool, PortType::U16) => Some(Box::new(N::BoolToU16::new())),
2912        (PortType::Bool, PortType::I8) => Some(Box::new(N::BoolToI8::new())),
2913        (PortType::Bool, PortType::I16) => Some(Box::new(N::BoolToI16::new())),
2914        (PortType::Bool, PortType::F16) => Some(Box::new(N::BoolToF16::new())),
2915        (PortType::U8, PortType::Bool) => Some(Box::new(N::U8ToBool::new())),
2916        (PortType::U16, PortType::Bool) => Some(Box::new(N::U16ToBool::new())),
2917        (PortType::I8, PortType::Bool) => Some(Box::new(N::I8ToBool::new())),
2918        (PortType::I16, PortType::Bool) => Some(Box::new(N::I16ToBool::new())),
2919        (PortType::F16, PortType::Bool) => Some(Box::new(N::F16ToBool::new())),
2920        (PortType::U8, PortType::Bytes) => Some(Box::new(N::U8ToBytes::new())),
2921        (PortType::U16, PortType::Bytes) => Some(Box::new(N::U16ToBytes::new())),
2922        (PortType::I8, PortType::Bytes) => Some(Box::new(N::I8ToBytes::new())),
2923        (PortType::I16, PortType::Bytes) => Some(Box::new(N::I16ToBytes::new())),
2924        (PortType::F16, PortType::Bytes) => Some(Box::new(N::F16ToBytes::new())),
2925        (PortType::U8, PortType::Json) => Some(Box::new(N::U8ToJson::new())),
2926        (PortType::U16, PortType::Json) => Some(Box::new(N::U16ToJson::new())),
2927        (PortType::I8, PortType::Json) => Some(Box::new(N::I8ToJson::new())),
2928        (PortType::I16, PortType::Json) => Some(Box::new(N::I16ToJson::new())),
2929
2930        // ── 128-bit integers (cranelift I128) ───────────────────
2931        // Widenings from the 64-bit carriers, Display renders,
2932        // LE byte / decimal-string JSON wraps. → f64 mirrors
2933        // u64→f64's class-A treatment (defined for every input).
2934        (PortType::U64, PortType::U128) => Some(Box::new(W::U64ToU128::new())),
2935        (PortType::U64, PortType::I128) => Some(Box::new(W::U64ToI128::new())),
2936        (PortType::I64, PortType::I128) => Some(Box::new(W::I64ToI128::new())),
2937        // Totality fills: every ≤64-bit integer widens losslessly
2938        // into the 128-bit carriers (unsigned → both signednesses,
2939        // signed → i128), `bool` widens to both, and the nonzero
2940        // test `128 → bool` is total. All class A.
2941        (PortType::U8, PortType::U128) => Some(Box::new(W::U8ToU128::new())),
2942        (PortType::U8, PortType::I128) => Some(Box::new(W::U8ToI128::new())),
2943        (PortType::U16, PortType::U128) => Some(Box::new(W::U16ToU128::new())),
2944        (PortType::U16, PortType::I128) => Some(Box::new(W::U16ToI128::new())),
2945        (PortType::U32, PortType::U128) => Some(Box::new(W::U32ToU128::new())),
2946        (PortType::U32, PortType::I128) => Some(Box::new(W::U32ToI128::new())),
2947        (PortType::I8, PortType::I128) => Some(Box::new(W::I8ToI128::new())),
2948        (PortType::I16, PortType::I128) => Some(Box::new(W::I16ToI128::new())),
2949        (PortType::I32, PortType::I128) => Some(Box::new(W::I32ToI128::new())),
2950        (PortType::Bool, PortType::U128) => Some(Box::new(W::BoolToU128::new())),
2951        (PortType::Bool, PortType::I128) => Some(Box::new(W::BoolToI128::new())),
2952        (PortType::U128, PortType::Bool) => Some(Box::new(W::U128ToBool::new())),
2953        (PortType::I128, PortType::Bool) => Some(Box::new(W::I128ToBool::new())),
2954        (PortType::U128, PortType::F64) => Some(Box::new(W::U128ToF64::new())),
2955        (PortType::I128, PortType::F64) => Some(Box::new(W::I128ToF64::new())),
2956        (PortType::U128, PortType::Str) => Some(Box::new(W::U128ToString::new())),
2957        (PortType::I128, PortType::Str) => Some(Box::new(W::I128ToString::new())),
2958        (PortType::U128, PortType::Bytes) => Some(Box::new(W::U128ToBytes::new())),
2959        (PortType::I128, PortType::Bytes) => Some(Box::new(W::I128ToBytes::new())),
2960        (PortType::U128, PortType::Json) => Some(Box::new(W::U128ToJson::new())),
2961        (PortType::I128, PortType::Json) => Some(Box::new(W::I128ToJson::new())),
2962
2963        // ── Register views (free bitcasts) ──────────────────────
2964        // Any reg→reg pair heals with a zero-cost retag — the
2965        // materialized "views are free bitcasts" rule
2966        // (type_system_alignment.md §3).
2967        (from, to) if crate::library::register_view::is_reg_port(from) => {
2968            crate::library::register_view::reg_view(to)
2969        }
2970
2971        // ── Vector lane completion — class A (total) ────────────
2972        // Lossless inter-lane widenings, `→ Bytes` serialise, and
2973        // integer-lane `→ Json`/`→ Str`. See library/polyfill_complete.rs.
2974        (PortType::VecI8, PortType::VecI16) => Some(Box::new(C::VecI8ToVecI16::new())),
2975        (PortType::VecI8, PortType::VecI32) => Some(Box::new(C::VecI8ToVecI32::new())),
2976        (PortType::VecI8, PortType::VecI64) => Some(Box::new(C::VecI8ToVecI64::new())),
2977        (PortType::VecI8, PortType::VecF16) => Some(Box::new(C::VecI8ToVecF16::new())),
2978        (PortType::VecI8, PortType::VecF32) => Some(Box::new(C::VecI8ToVecF32::new())),
2979        (PortType::VecI8, PortType::VecF64) => Some(Box::new(C::VecI8ToVecF64::new())),
2980        (PortType::VecI16, PortType::VecI32) => Some(Box::new(C::VecI16ToVecI32::new())),
2981        (PortType::VecI16, PortType::VecI64) => Some(Box::new(C::VecI16ToVecI64::new())),
2982        (PortType::VecI16, PortType::VecF32) => Some(Box::new(C::VecI16ToVecF32::new())),
2983        (PortType::VecI16, PortType::VecF64) => Some(Box::new(C::VecI16ToVecF64::new())),
2984        (PortType::VecI32, PortType::VecI64) => Some(Box::new(C::VecI32ToVecI64::new())),
2985        (PortType::VecI32, PortType::VecF64) => Some(Box::new(C::VecI32ToVecF64::new())),
2986        (PortType::VecI64, PortType::VecF64) => Some(Box::new(C::VecI64ToVecF64::new())),
2987        (PortType::VecF16, PortType::VecF32) => Some(Box::new(C::VecF16ToVecF32::new())),
2988        (PortType::VecF16, PortType::VecF64) => Some(Box::new(C::VecF16ToVecF64::new())),
2989        (PortType::VecF32, PortType::VecF64) => Some(Box::new(C::VecF32ToVecF64::new())),
2990        (PortType::VecF64, PortType::Bytes) => Some(Box::new(C::VecF64ToBytes::new())),
2991        (PortType::VecI64, PortType::Bytes) => Some(Box::new(C::VecI64ToBytes::new())),
2992        (PortType::VecF16, PortType::Bytes) => Some(Box::new(C::VecF16ToBytes::new())),
2993        (PortType::VecI16, PortType::Bytes) => Some(Box::new(C::VecI16ToBytes::new())),
2994        (PortType::VecI8, PortType::Bytes) => Some(Box::new(C::VecI8ToBytes::new())),
2995        (PortType::VecI64, PortType::Json) => Some(Box::new(C::VecI64ToJson::new())),
2996        (PortType::VecI16, PortType::Json) => Some(Box::new(C::VecI16ToJson::new())),
2997        (PortType::VecI8, PortType::Json) => Some(Box::new(C::VecI8ToJson::new())),
2998        (PortType::VecI32, PortType::Str) => Some(Box::new(P::VecI32ToStr::new())),
2999        (PortType::VecI64, PortType::Str) => Some(Box::new(C::VecI64ToStr::new())),
3000        (PortType::VecI16, PortType::Str) => Some(Box::new(C::VecI16ToStr::new())),
3001        (PortType::VecI8, PortType::Str) => Some(Box::new(C::VecI8ToStr::new())),
3002
3003        _ => None,
3004    }
3005}
3006
3007/// Boundary adapter catalog. Consulted by
3008/// `adapt_boundary_value` when a host-injected scope value
3009/// crosses into a typed slot. Strictly a superset of
3010/// [`auto_adapter`]: every intra-graph adapter is also a
3011/// boundary adapter, plus all the lossy / parseable / shape-
3012/// checking adapters that can panic on input the assembler
3013/// can't statically verify.
3014///
3015/// Boundary-only adapters fall into four classes:
3016///
3017/// - **Numeric narrowings** — `U64→{U32, I64, I32, F32}`,
3018///   `F64→{U64, U32, I64, I32, F32}`, etc. Range-checked,
3019///   panic on out-of-range.
3020/// - **Str → X parsers** — workload-param flow (YAML string
3021///   interpolations, comma-split iter-values). Panic on
3022///   unparseable input.
3023/// - **Bytes → X parsers** — wrong-length panics. Numeric
3024///   reads expect exactly sizeof(N) bytes; Vec reads expect
3025///   a multiple of sizeof(element).
3026/// - **Json → X extractors** — shape mismatch panics
3027///   (`Json::Array` expected for Vec; `Json::Number` for
3028///   numerics; etc.).
3029///
3030/// Plus a small set of "almost-auto" adapters that the
3031/// assembler can't promote because they panic on non-finite
3032/// floats: `F64→Json`, `F32→Json`, `VecF32→Json`,
3033/// `VecF32→Str`.
3034///
3035/// See `polydat/docs/design/type_system.md`.
3036pub fn boundary_adapter(from: PortType, to: PortType) -> Option<Box<dyn PolydatNode>> {
3037    if let Some(adapter) = auto_adapter(from, to) {
3038        return Some(adapter);
3039    }
3040    use crate::library::convert::{StrToBool, StrToF64, StrToU64};
3041    use crate::library::polyfill as P;
3042    use crate::library::polyfill_128 as W;
3043    use crate::library::polyfill_complete as C;
3044    use crate::library::polyfill_narrow as N;
3045    match (from, to) {
3046        // ── Numeric narrowings + non-widening casts ─────────────
3047        (PortType::U64, PortType::U32) => Some(Box::new(P::U64ToU32::new())),
3048        (PortType::U64, PortType::I64) => Some(Box::new(P::U64ToI64::new())),
3049        (PortType::U64, PortType::I32) => Some(Box::new(P::U64ToI32::new())),
3050        (PortType::U64, PortType::F32) => Some(Box::new(P::U64ToF32::new())),
3051        (PortType::U32, PortType::I32) => Some(Box::new(P::U32ToI32::new())),
3052        (PortType::U32, PortType::F32) => Some(Box::new(P::U32ToF32::new())),
3053        (PortType::I64, PortType::U64) => Some(Box::new(P::I64ToU64::new())),
3054        (PortType::I64, PortType::U32) => Some(Box::new(P::I64ToU32::new())),
3055        (PortType::I64, PortType::I32) => Some(Box::new(P::I64ToI32::new())),
3056        (PortType::I64, PortType::F32) => Some(Box::new(P::I64ToF32::new())),
3057        (PortType::I32, PortType::U64) => Some(Box::new(P::I32ToU64::new())),
3058        (PortType::I32, PortType::U32) => Some(Box::new(P::I32ToU32::new())),
3059        (PortType::I32, PortType::F32) => Some(Box::new(P::I32ToF32::new())),
3060        (PortType::F64, PortType::U64) => Some(Box::new(P::F64ToU64Checked::new())),
3061        (PortType::F64, PortType::U32) => Some(Box::new(P::F64ToU32::new())),
3062        (PortType::F64, PortType::I64) => Some(Box::new(P::F64ToI64::new())),
3063        (PortType::F64, PortType::I32) => Some(Box::new(P::F64ToI32::new())),
3064        (PortType::F64, PortType::F32) => Some(Box::new(P::F64ToF32::new())),
3065        (PortType::F32, PortType::U64) => Some(Box::new(P::F32ToU64::new())),
3066        (PortType::F32, PortType::U32) => Some(Box::new(P::F32ToU32::new())),
3067        (PortType::F32, PortType::I64) => Some(Box::new(P::F32ToI64::new())),
3068        (PortType::F32, PortType::I32) => Some(Box::new(P::F32ToI32::new())),
3069
3070        // ── Str → X parsers (boundary-only: panic on unparseable)
3071        (PortType::Str, PortType::Bool) => Some(Box::new(StrToBool::new())),
3072        (PortType::Str, PortType::U64) => Some(Box::new(StrToU64::new())),
3073        (PortType::Str, PortType::F64) => Some(Box::new(StrToF64::new())),
3074        (PortType::Str, PortType::U32) => Some(Box::new(P::StrToU32::new())),
3075        (PortType::Str, PortType::I64) => Some(Box::new(P::StrToI64::new())),
3076        (PortType::Str, PortType::I32) => Some(Box::new(P::StrToI32::new())),
3077        (PortType::Str, PortType::F32) => Some(Box::new(P::StrToF32::new())),
3078        (PortType::Str, PortType::Bytes) => Some(Box::new(P::StrToBytes::new())),
3079        (PortType::Str, PortType::Json) => Some(Box::new(P::StrToJson::new())),
3080        (PortType::Str, PortType::VecF32) => Some(Box::new(P::StrToVecF32::new())),
3081        (PortType::Str, PortType::VecI32) => Some(Box::new(P::StrToVecI32::new())),
3082
3083        // ── Bytes → X (length-checked, little-endian) ───────────
3084        (PortType::Bytes, PortType::U64) => Some(Box::new(P::BytesToU64::new())),
3085        (PortType::Bytes, PortType::U32) => Some(Box::new(P::BytesToU32::new())),
3086        (PortType::Bytes, PortType::I64) => Some(Box::new(P::BytesToI64::new())),
3087        (PortType::Bytes, PortType::I32) => Some(Box::new(P::BytesToI32::new())),
3088        (PortType::Bytes, PortType::F64) => Some(Box::new(P::BytesToF64::new())),
3089        (PortType::Bytes, PortType::F32) => Some(Box::new(P::BytesToF32::new())),
3090        (PortType::Bytes, PortType::Bool) => Some(Box::new(P::BytesToBool::new())),
3091        (PortType::Bytes, PortType::Str) => Some(Box::new(P::BytesToStr::new())),
3092        (PortType::Bytes, PortType::Json) => Some(Box::new(P::BytesToJson::new())),
3093        (PortType::Bytes, PortType::VecF32) => Some(Box::new(P::BytesToVecF32::new())),
3094        (PortType::Bytes, PortType::VecI32) => Some(Box::new(P::BytesToVecI32::new())),
3095
3096        // ── Json → X (shape-checked) ────────────────────────────
3097        (PortType::Json, PortType::U64) => Some(Box::new(P::JsonToU64::new())),
3098        (PortType::Json, PortType::U32) => Some(Box::new(P::JsonToU32::new())),
3099        (PortType::Json, PortType::I64) => Some(Box::new(P::JsonToI64::new())),
3100        (PortType::Json, PortType::I32) => Some(Box::new(P::JsonToI32::new())),
3101        (PortType::Json, PortType::F64) => Some(Box::new(P::JsonToF64::new())),
3102        (PortType::Json, PortType::F32) => Some(Box::new(P::JsonToF32::new())),
3103        (PortType::Json, PortType::Bool) => Some(Box::new(P::JsonToBool::new())),
3104        (PortType::Json, PortType::Bytes) => Some(Box::new(P::JsonToBytes::new())),
3105        (PortType::Json, PortType::VecF32) => Some(Box::new(P::JsonToVecF32::new())),
3106        (PortType::Json, PortType::VecI32) => Some(Box::new(P::JsonToVecI32::new())),
3107
3108        // ── Almost-auto (panic on non-finite floats) ────────────
3109        (PortType::F64, PortType::Json) => Some(Box::new(P::F64ToJson::new())),
3110        (PortType::F32, PortType::Json) => Some(Box::new(P::F32ToJson::new())),
3111        (PortType::VecF32, PortType::Json) => Some(Box::new(P::VecF32ToJson::new())),
3112        (PortType::VecF32, PortType::Str) => Some(Box::new(P::VecF32ToStr::new())),
3113
3114        // ── Vec ↔ Vec (lossy round) ─────────────────────────────
3115        (PortType::VecF32, PortType::VecI32) => Some(Box::new(P::VecF32ToVecI32::new())),
3116
3117        // ── Narrow cranelift widths (u8/i8/u16/i16/f16) ─────────
3118        // Range-checked narrowings + parsers + shape-checked
3119        // extractors, mirroring the u32/i32/f32 rows.
3120        (PortType::U64, PortType::U8) => Some(Box::new(N::U64ToU8::new())),
3121        (PortType::U32, PortType::U8) => Some(Box::new(N::U32ToU8::new())),
3122        (PortType::U16, PortType::U8) => Some(Box::new(N::U16ToU8::new())),
3123        (PortType::I64, PortType::U8) => Some(Box::new(N::I64ToU8::new())),
3124        (PortType::F64, PortType::U8) => Some(Box::new(N::F64ToU8::new())),
3125        (PortType::U64, PortType::U16) => Some(Box::new(N::U64ToU16::new())),
3126        (PortType::U32, PortType::U16) => Some(Box::new(N::U32ToU16::new())),
3127        (PortType::I64, PortType::U16) => Some(Box::new(N::I64ToU16::new())),
3128        (PortType::F64, PortType::U16) => Some(Box::new(N::F64ToU16::new())),
3129        (PortType::I64, PortType::I8) => Some(Box::new(N::I64ToI8::new())),
3130        (PortType::I32, PortType::I8) => Some(Box::new(N::I32ToI8::new())),
3131        (PortType::U64, PortType::I8) => Some(Box::new(N::U64ToI8::new())),
3132        (PortType::F64, PortType::I8) => Some(Box::new(N::F64ToI8::new())),
3133        (PortType::I64, PortType::I16) => Some(Box::new(N::I64ToI16::new())),
3134        (PortType::I32, PortType::I16) => Some(Box::new(N::I32ToI16::new())),
3135        (PortType::U64, PortType::I16) => Some(Box::new(N::U64ToI16::new())),
3136        (PortType::F64, PortType::I16) => Some(Box::new(N::F64ToI16::new())),
3137        (PortType::F64, PortType::F16) => Some(Box::new(N::F64ToF16::new())),
3138        (PortType::F32, PortType::F16) => Some(Box::new(N::F32ToF16::new())),
3139        (PortType::U64, PortType::F16) => Some(Box::new(N::U64ToF16::new())),
3140        (PortType::Str, PortType::U8) => Some(Box::new(N::StrToU8::new())),
3141        (PortType::Str, PortType::U16) => Some(Box::new(N::StrToU16::new())),
3142        (PortType::Str, PortType::I8) => Some(Box::new(N::StrToI8::new())),
3143        (PortType::Str, PortType::I16) => Some(Box::new(N::StrToI16::new())),
3144        (PortType::Str, PortType::F16) => Some(Box::new(N::StrToF16::new())),
3145        (PortType::Bytes, PortType::U8) => Some(Box::new(N::BytesToU8::new())),
3146        (PortType::Bytes, PortType::U16) => Some(Box::new(N::BytesToU16::new())),
3147        (PortType::Bytes, PortType::I8) => Some(Box::new(N::BytesToI8::new())),
3148        (PortType::Bytes, PortType::I16) => Some(Box::new(N::BytesToI16::new())),
3149        (PortType::Bytes, PortType::F16) => Some(Box::new(N::BytesToF16::new())),
3150        (PortType::Json, PortType::U8) => Some(Box::new(N::JsonToU8::new())),
3151        (PortType::Json, PortType::U16) => Some(Box::new(N::JsonToU16::new())),
3152        (PortType::Json, PortType::I8) => Some(Box::new(N::JsonToI8::new())),
3153        (PortType::Json, PortType::I16) => Some(Box::new(N::JsonToI16::new())),
3154        (PortType::Json, PortType::F16) => Some(Box::new(N::JsonToF16::new())),
3155        // f16 → Json panics on non-finite (same as f32 → Json).
3156        (PortType::F16, PortType::Json) => Some(Box::new(N::F16ToJson::new())),
3157
3158        // ── 128-bit integers (range-checked / parse / shape) ────
3159        (PortType::U128, PortType::U64) => Some(Box::new(W::U128ToU64::new())),
3160        (PortType::I128, PortType::I64) => Some(Box::new(W::I128ToI64::new())),
3161        (PortType::I64, PortType::U128) => Some(Box::new(W::I64ToU128::new())),
3162        (PortType::U128, PortType::I128) => Some(Box::new(W::U128ToI128::new())),
3163        (PortType::I128, PortType::U128) => Some(Box::new(W::I128ToU128::new())),
3164        (PortType::F64, PortType::U128) => Some(Box::new(W::F64ToU128::new())),
3165        (PortType::F64, PortType::I128) => Some(Box::new(W::F64ToI128::new())),
3166        (PortType::Str, PortType::U128) => Some(Box::new(W::StrToU128::new())),
3167        (PortType::Str, PortType::I128) => Some(Box::new(W::StrToI128::new())),
3168        (PortType::Bytes, PortType::U128) => Some(Box::new(W::BytesToU128::new())),
3169        (PortType::Bytes, PortType::I128) => Some(Box::new(W::BytesToI128::new())),
3170        (PortType::Json, PortType::U128) => Some(Box::new(W::JsonToU128::new())),
3171        (PortType::Json, PortType::I128) => Some(Box::new(W::JsonToI128::new())),
3172
3173        // ── Scalar matrix completion (library/polyfill_complete.rs) ──
3174        // Every remaining scalar→scalar narrowing / cross-sign /
3175        // float→int / int→narrow-float cell, so the 14×14 scalar
3176        // block has no `·`. All class B (range-checked, can panic).
3177        (PortType::U8, PortType::I8) => Some(Box::new(C::U8ToI8::new())),
3178        (PortType::I8, PortType::U8) => Some(Box::new(C::I8ToU8::new())),
3179        (PortType::I8, PortType::U16) => Some(Box::new(C::I8ToU16::new())),
3180        (PortType::I8, PortType::U32) => Some(Box::new(C::I8ToU32::new())),
3181        (PortType::I8, PortType::U64) => Some(Box::new(C::I8ToU64::new())),
3182        (PortType::I8, PortType::U128) => Some(Box::new(C::I8ToU128::new())),
3183        (PortType::U16, PortType::I8) => Some(Box::new(C::U16ToI8::new())),
3184        (PortType::U16, PortType::I16) => Some(Box::new(C::U16ToI16::new())),
3185        (PortType::U16, PortType::F16) => Some(Box::new(C::U16ToF16::new())),
3186        (PortType::I16, PortType::U8) => Some(Box::new(C::I16ToU8::new())),
3187        (PortType::I16, PortType::I8) => Some(Box::new(C::I16ToI8::new())),
3188        (PortType::I16, PortType::U16) => Some(Box::new(C::I16ToU16::new())),
3189        (PortType::I16, PortType::F16) => Some(Box::new(C::I16ToF16::new())),
3190        (PortType::I16, PortType::U32) => Some(Box::new(C::I16ToU32::new())),
3191        (PortType::I16, PortType::U64) => Some(Box::new(C::I16ToU64::new())),
3192        (PortType::I16, PortType::U128) => Some(Box::new(C::I16ToU128::new())),
3193        (PortType::U32, PortType::I8) => Some(Box::new(C::U32ToI8::new())),
3194        (PortType::U32, PortType::I16) => Some(Box::new(C::U32ToI16::new())),
3195        (PortType::U32, PortType::F16) => Some(Box::new(C::U32ToF16::new())),
3196        (PortType::I32, PortType::U8) => Some(Box::new(C::I32ToU8::new())),
3197        (PortType::I32, PortType::U16) => Some(Box::new(C::I32ToU16::new())),
3198        (PortType::I32, PortType::F16) => Some(Box::new(C::I32ToF16::new())),
3199        (PortType::I32, PortType::U128) => Some(Box::new(C::I32ToU128::new())),
3200        (PortType::F16, PortType::U8) => Some(Box::new(C::F16ToU8::new())),
3201        (PortType::F16, PortType::I8) => Some(Box::new(C::F16ToI8::new())),
3202        (PortType::F16, PortType::U16) => Some(Box::new(C::F16ToU16::new())),
3203        (PortType::F16, PortType::I16) => Some(Box::new(C::F16ToI16::new())),
3204        (PortType::F16, PortType::U32) => Some(Box::new(C::F16ToU32::new())),
3205        (PortType::F16, PortType::I32) => Some(Box::new(C::F16ToI32::new())),
3206        (PortType::F16, PortType::U64) => Some(Box::new(C::F16ToU64::new())),
3207        (PortType::F16, PortType::I64) => Some(Box::new(C::F16ToI64::new())),
3208        (PortType::F16, PortType::U128) => Some(Box::new(C::F16ToU128::new())),
3209        (PortType::F16, PortType::I128) => Some(Box::new(C::F16ToI128::new())),
3210        (PortType::F32, PortType::U8) => Some(Box::new(C::F32ToU8::new())),
3211        (PortType::F32, PortType::I8) => Some(Box::new(C::F32ToI8::new())),
3212        (PortType::F32, PortType::U16) => Some(Box::new(C::F32ToU16::new())),
3213        (PortType::F32, PortType::I16) => Some(Box::new(C::F32ToI16::new())),
3214        (PortType::F32, PortType::U128) => Some(Box::new(C::F32ToU128::new())),
3215        (PortType::F32, PortType::I128) => Some(Box::new(C::F32ToI128::new())),
3216        (PortType::I64, PortType::F16) => Some(Box::new(C::I64ToF16::new())),
3217        (PortType::U128, PortType::U8) => Some(Box::new(C::U128ToU8::new())),
3218        (PortType::U128, PortType::I8) => Some(Box::new(C::U128ToI8::new())),
3219        (PortType::U128, PortType::U16) => Some(Box::new(C::U128ToU16::new())),
3220        (PortType::U128, PortType::I16) => Some(Box::new(C::U128ToI16::new())),
3221        (PortType::U128, PortType::F16) => Some(Box::new(C::U128ToF16::new())),
3222        (PortType::U128, PortType::U32) => Some(Box::new(C::U128ToU32::new())),
3223        (PortType::U128, PortType::I32) => Some(Box::new(C::U128ToI32::new())),
3224        (PortType::U128, PortType::F32) => Some(Box::new(C::U128ToF32::new())),
3225        (PortType::U128, PortType::I64) => Some(Box::new(C::U128ToI64::new())),
3226        (PortType::I128, PortType::U8) => Some(Box::new(C::I128ToU8::new())),
3227        (PortType::I128, PortType::I8) => Some(Box::new(C::I128ToI8::new())),
3228        (PortType::I128, PortType::U16) => Some(Box::new(C::I128ToU16::new())),
3229        (PortType::I128, PortType::I16) => Some(Box::new(C::I128ToI16::new())),
3230        (PortType::I128, PortType::F16) => Some(Box::new(C::I128ToF16::new())),
3231        (PortType::I128, PortType::U32) => Some(Box::new(C::I128ToU32::new())),
3232        (PortType::I128, PortType::I32) => Some(Box::new(C::I128ToI32::new())),
3233        (PortType::I128, PortType::F32) => Some(Box::new(C::I128ToF32::new())),
3234        (PortType::I128, PortType::U64) => Some(Box::new(C::I128ToU64::new())),
3235
3236        // ── Vector lane completion — class B (lossy / checked) ──
3237        // Inter-lane narrowing + float→int, Bytes/Json/Str decode &
3238        // parse, float-lane → Json/Str (non-finite panics).
3239        (PortType::VecI16, PortType::VecI8) => Some(Box::new(C::VecI16ToVecI8::new())),
3240        (PortType::VecI16, PortType::VecF16) => Some(Box::new(C::VecI16ToVecF16::new())),
3241        (PortType::VecI32, PortType::VecI8) => Some(Box::new(C::VecI32ToVecI8::new())),
3242        (PortType::VecI32, PortType::VecI16) => Some(Box::new(C::VecI32ToVecI16::new())),
3243        (PortType::VecI32, PortType::VecF16) => Some(Box::new(C::VecI32ToVecF16::new())),
3244        (PortType::VecI64, PortType::VecI8) => Some(Box::new(C::VecI64ToVecI8::new())),
3245        (PortType::VecI64, PortType::VecI16) => Some(Box::new(C::VecI64ToVecI16::new())),
3246        (PortType::VecI64, PortType::VecI32) => Some(Box::new(C::VecI64ToVecI32::new())),
3247        (PortType::VecI64, PortType::VecF16) => Some(Box::new(C::VecI64ToVecF16::new())),
3248        (PortType::VecI64, PortType::VecF32) => Some(Box::new(C::VecI64ToVecF32::new())),
3249        (PortType::VecF16, PortType::VecI8) => Some(Box::new(C::VecF16ToVecI8::new())),
3250        (PortType::VecF16, PortType::VecI16) => Some(Box::new(C::VecF16ToVecI16::new())),
3251        (PortType::VecF16, PortType::VecI32) => Some(Box::new(C::VecF16ToVecI32::new())),
3252        (PortType::VecF16, PortType::VecI64) => Some(Box::new(C::VecF16ToVecI64::new())),
3253        (PortType::VecF32, PortType::VecI8) => Some(Box::new(C::VecF32ToVecI8::new())),
3254        (PortType::VecF32, PortType::VecI16) => Some(Box::new(C::VecF32ToVecI16::new())),
3255        (PortType::VecF32, PortType::VecI64) => Some(Box::new(C::VecF32ToVecI64::new())),
3256        (PortType::VecF32, PortType::VecF16) => Some(Box::new(C::VecF32ToVecF16::new())),
3257        (PortType::VecF64, PortType::VecI8) => Some(Box::new(C::VecF64ToVecI8::new())),
3258        (PortType::VecF64, PortType::VecI16) => Some(Box::new(C::VecF64ToVecI16::new())),
3259        (PortType::VecF64, PortType::VecI32) => Some(Box::new(C::VecF64ToVecI32::new())),
3260        (PortType::VecF64, PortType::VecI64) => Some(Box::new(C::VecF64ToVecI64::new())),
3261        (PortType::VecF64, PortType::VecF16) => Some(Box::new(C::VecF64ToVecF16::new())),
3262        (PortType::VecF64, PortType::VecF32) => Some(Box::new(C::VecF64ToVecF32::new())),
3263        (PortType::Bytes, PortType::VecF64) => Some(Box::new(C::BytesToVecF64::new())),
3264        (PortType::Bytes, PortType::VecI64) => Some(Box::new(C::BytesToVecI64::new())),
3265        (PortType::Bytes, PortType::VecF16) => Some(Box::new(C::BytesToVecF16::new())),
3266        (PortType::Bytes, PortType::VecI16) => Some(Box::new(C::BytesToVecI16::new())),
3267        (PortType::Bytes, PortType::VecI8) => Some(Box::new(C::BytesToVecI8::new())),
3268        (PortType::VecF64, PortType::Json) => Some(Box::new(C::VecF64ToJson::new())),
3269        (PortType::VecF16, PortType::Json) => Some(Box::new(C::VecF16ToJson::new())),
3270        (PortType::Json, PortType::VecF64) => Some(Box::new(C::JsonToVecF64::new())),
3271        (PortType::Json, PortType::VecI64) => Some(Box::new(C::JsonToVecI64::new())),
3272        (PortType::Json, PortType::VecF16) => Some(Box::new(C::JsonToVecF16::new())),
3273        (PortType::Json, PortType::VecI16) => Some(Box::new(C::JsonToVecI16::new())),
3274        (PortType::Json, PortType::VecI8) => Some(Box::new(C::JsonToVecI8::new())),
3275        (PortType::VecF64, PortType::Str) => Some(Box::new(C::VecF64ToStr::new())),
3276        (PortType::VecF16, PortType::Str) => Some(Box::new(C::VecF16ToStr::new())),
3277        (PortType::Str, PortType::VecF64) => Some(Box::new(C::StrToVecF64::new())),
3278        (PortType::Str, PortType::VecI64) => Some(Box::new(C::StrToVecI64::new())),
3279        (PortType::Str, PortType::VecF16) => Some(Box::new(C::StrToVecF16::new())),
3280        (PortType::Str, PortType::VecI16) => Some(Box::new(C::StrToVecI16::new())),
3281        (PortType::Str, PortType::VecI8) => Some(Box::new(C::StrToVecI8::new())),
3282
3283        _ => None,
3284    }
3285}
3286
3287// ── The one constructor (engines.md §3.5) ─────────────────
3288
3289use crate::compile::select::{Engine, KernelError, Provenance};
3290use crate::kernel::Kernel;
3291
3292/// The outputs whose value is fixed for a kernel's life: those a const
3293/// binding declares, and those whose producing node is compile-constant.
3294fn fixed_outputs(resolved: &ResolvedDag) -> std::collections::HashSet<String> {
3295    let classes = PolydatProgram::classify_lifecycle(
3296        &resolved.nodes,
3297        &resolved.wiring,
3298        &resolved.input_defs,
3299        &resolved.output_map,
3300        &resolved.output_modifiers,
3301    );
3302    resolved
3303        .output_map
3304        .iter()
3305        .filter(|(name, (node, _))| {
3306            resolved.const_outputs.contains(*name)
3307                || classes.lifecycle[*node] == crate::kernel::EvalLifecycle::CompileConst
3308        })
3309        .map(|(name, _)| name.clone())
3310        .collect()
3311}
3312
3313impl PolydatAssembler {
3314    /// Build a kernel on `engine`: the interpreter, the closure tier,
3315    /// the hybrid kernel, or pure native code, with the provenance mode
3316    /// the engine names. Every engine accepts every program the
3317    /// interpreter accepts, or refuses it with a reason naming the node
3318    /// or construct ([`KernelError::Refused`]). The older constructors
3319    /// (`compile`, `try_compile*`, `compile_hybrid`)
3320    /// remain as aliases of this one for their engine.
3321    pub fn compile_with(self, engine: Engine) -> Result<Box<dyn Kernel>, KernelError> {
3322        self.compile_engine_with_log(engine, None)
3323    }
3324
3325    /// [`Self::compile_with`] on [`Engine::default`]: compiled code, with
3326    /// the JIT where the build has it.
3327    pub fn compile_kernel(self) -> Result<Box<dyn Kernel>, KernelError> {
3328        self.compile_with(Engine::default())
3329    }
3330
3331    /// [`Self::compile_with`] with the compile event log, which
3332    /// receives the assembly events for every engine.
3333    pub fn compile_engine_with_log(
3334        self,
3335        engine: Engine,
3336        log: Option<&mut crate::dsl::events::CompileEventLog>,
3337    ) -> Result<Box<dyn Kernel>, KernelError> {
3338        match engine {
3339            // The one engine with no slot surface, and so the one this
3340            // function builds itself.
3341            Engine::Interpreter(cones) => {
3342                let mut asm = self;
3343                asm.jit_mode = Some(cones);
3344                Ok(Box::new(asm.compile_with_log(log)?))
3345            }
3346            // Every compiled engine is built once, by
3347            // `compile_slots_with_log`, and upcast for the caller who
3348            // asked for the ordinary surface. One builder, two views.
3349            _ => Ok(self.compile_slots_with_log(engine, log)?),
3350        }
3351    }
3352
3353    /// Build on `engine` and keep the slot surface: the same kernel
3354    /// [`Self::compile_with`] builds, typed as
3355    /// [`SlotKernel`](crate::compile::SlotKernel) so a caller can read
3356    /// a buffer slot and evaluate one without boxing a `Value`.
3357    ///
3358    /// For testing, measurement and diagnostics, where the layout is
3359    /// the subject. Normative use is `compile_with`, which returns the
3360    /// same kernel as `Box<dyn Kernel>`; a `Box<dyn SlotKernel>`
3361    /// upcasts to one wherever the ordinary surface will do, so a
3362    /// caller that wants both needs only this call.
3363    ///
3364    /// `Engine::Interpreter` is refused, and cannot be anything else:
3365    /// the interpreter holds typed `Value` buffers and has no slot to
3366    /// name. Ask for a compiled engine, or use `compile_with` and the
3367    /// `Kernel` trait, which every engine answers.
3368    pub fn compile_slots(
3369        self,
3370        engine: Engine,
3371    ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3372        self.compile_slots_with_log(engine, None)
3373    }
3374
3375    /// [`Self::compile_slots`] with the compile event log. The kernel is
3376    /// initialized before it is returned: its consts are evaluated.
3377    pub fn compile_slots_with_log(
3378        self,
3379        engine: Engine,
3380        log: Option<&mut crate::dsl::events::CompileEventLog>,
3381    ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3382        let template = self.template;
3383        let mut kernel = self.build_slots_with_log(engine, log)?;
3384        if !template {
3385            crate::kernel::Kernel::init(kernel.as_mut())?;
3386        }
3387        Ok(kernel)
3388    }
3389
3390    /// The compiled kernel on `engine`, not yet initialized.
3391    fn build_slots_with_log(
3392        self,
3393        engine: Engine,
3394        mut log: Option<&mut crate::dsl::events::CompileEventLog>,
3395    ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3396        let refused = |reason: String| KernelError::Refused { engine, reason };
3397        // A builder names its tier but not the provenance mode it was
3398        // asked for, which the caller is entitled to see back. Only a
3399        // refusal is restamped: a fold failure belongs to the program
3400        // and names no engine at all.
3401        let asked = |e: KernelError| match e {
3402            KernelError::Refused { reason, .. } => KernelError::Refused { engine, reason },
3403            other => other,
3404        };
3405        let strict = self.strict;
3406        match engine {
3407            Engine::Interpreter(_) => Err(refused(
3408                "the interpreter has no slot buffer: its buffers are typed `Value`s, so \
3409                 there is no slot to name. Ask for `closures`, `native` or `pure-native` \
3410                 for the slot surface, or compile with `compile_with` and drive the \
3411                 kernel through the `Kernel` trait, which every engine answers."
3412                    .into(),
3413            )),
3414            Engine::Closures(prov) => {
3415                let resolved = self.resolve_with_log(log.as_deref_mut())?;
3416                if strict {
3417                    Self::refuse_strict(&resolved)?;
3418                }
3419                let folded = log.is_some().then(|| Self::constant_sites(&resolved));
3420                let (node_total, output_total) =
3421                    (resolved.nodes.len(), resolved.output_order.len());
3422                let kernel = Self::closures_from(resolved, prov).map_err(asked)?;
3423                Self::log_folded(kernel.as_ref(), folded, log.as_deref_mut());
3424                Self::log_summary(log, node_total, output_total);
3425                Ok(kernel)
3426            }
3427            // Available in every build. Without the `jit` feature this
3428            // engine's kernel has no native segment in it and every
3429            // step is a closure, which `plan()` reports as it reports
3430            // any other mix; the engine is the kernel architecture, and
3431            // how much of it got native code is the plan. Refusing here
3432            // would take a working tier away from an architecture that
3433            // has no code generator, which is the one place it is most
3434            // worth keeping every engine that can be built.
3435            Engine::Native(prov) => {
3436                {
3437                    let resolved = self.resolve_with_log(log.as_deref_mut())?;
3438                    if strict {
3439                        Self::refuse_strict(&resolved)?;
3440                    }
3441                    let folded = log.is_some().then(|| Self::constant_sites(&resolved));
3442                    let (node_total, output_total) =
3443                        (resolved.nodes.len(), resolved.output_order.len());
3444                    // Push without the cone guard has no native kernel
3445                    // (engines.md §4), so a request for it cannot be
3446                    // realized. Refuse it rather than build push-pull and
3447                    // report a mode the caller did not ask for: a kernel's
3448                    // reported configuration is the one it runs.
3449                    if prov == Provenance::Push {
3450                        return Err(refused(
3451                            "native code has no push-only kernel: push-side invalidation \
3452                             without the cone guard has no native form. Ask for `pushpull` \
3453                             for both, `pull` for the guard alone, or `auto` to let the \
3454                             selector choose; `push` alone is available on the closure tier."
3455                                .into(),
3456                        ));
3457                    }
3458                    let prov = Self::provenance_for(prov, &resolved);
3459                    let kernel = Self::hybrid_from(resolved).map_err(asked)?;
3460                    let kernel: Box<dyn crate::compile::SlotKernel> = match prov {
3461                        Provenance::Raw => Box::new(kernel.into_raw()),
3462                        Provenance::Pull => Box::new(kernel.into_pull()),
3463                        // `provenance_for` resolves `Auto` to `Raw`,
3464                        // `Pull`, or `PushPull`, and `Push` was refused
3465                        // above, so this arm is `PushPull` in practice.
3466                        // It refuses rather than panics if the selector
3467                        // ever gains a mode with no native kernel.
3468                        Provenance::PushPull | Provenance::Auto => Box::new(kernel),
3469                        Provenance::Push => {
3470                            return Err(refused("native code has no push-only kernel".into()));
3471                        }
3472                    };
3473                    Self::log_folded(kernel.as_ref(), folded, log.as_deref_mut());
3474                    Self::log_summary(log, node_total, output_total);
3475                    Ok(kernel)
3476                }
3477            }
3478            Engine::PureNative(prov) => {
3479                #[cfg(feature = "jit")]
3480                {
3481                    let resolved = self.resolve_with_log(log.as_deref_mut())?;
3482                    if strict {
3483                        Self::refuse_strict(&resolved)?;
3484                    }
3485                    let folded = log.is_some().then(|| Self::constant_sites(&resolved));
3486                    let (node_total, output_total) =
3487                        (resolved.nodes.len(), resolved.output_order.len());
3488                    // Only raw and push+pull have a pure kernel. A named
3489                    // mode with none is refused rather than silently
3490                    // answered with another, because a kernel reports
3491                    // the configuration it runs; `Auto` delegated the
3492                    // choice, so the selector's pull resolves to
3493                    // push+pull, whose guard subsumes it.
3494                    let prov = match prov {
3495                        Provenance::Auto => match Self::provenance_for(prov, &resolved) {
3496                            Provenance::Raw => Provenance::Raw,
3497                            _ => Provenance::PushPull,
3498                        },
3499                        named @ (Provenance::Raw | Provenance::PushPull) => named,
3500                        other => {
3501                            return Err(refused(format!(
3502                                "pure native code has no {} kernel: the tier keeps only the \
3503                                 two forms the differential needs. Ask for `raw` or \
3504                                 `pushpull`, or `auto` to let the selector choose; every \
3505                                 mode is available on `native`.",
3506                                format!("{other:?}").to_lowercase(),
3507                            )));
3508                        }
3509                    };
3510                    let kernel: Box<dyn crate::compile::SlotKernel> = match prov {
3511                        Provenance::Raw => Box::new(Self::jit_raw_from(resolved).map_err(asked)?),
3512                        _ => Box::new(Self::jit_push_pull_from(resolved).map_err(asked)?),
3513                    };
3514                    Self::log_folded(kernel.as_ref(), folded, log.as_deref_mut());
3515                    Self::log_summary(log, node_total, output_total);
3516                    Ok(kernel)
3517                }
3518                #[cfg(not(feature = "jit"))]
3519                {
3520                    let _ = (prov, log);
3521                    Err(refused(
3522                        "this build has no native code (the `jit` feature is off)".into(),
3523                    ))
3524                }
3525            }
3526        }
3527    }
3528
3529    /// The nodes the compile-constant fold applies to, as the
3530    /// interpreter's fold selects them: no input reaches the node and it
3531    /// has one output; with the slot and type to read once the kernel is
3532    /// built.
3533    fn constant_sites(resolved: &ResolvedDag) -> Vec<(String, usize, crate::ast::PortType)> {
3534        let classes = PolydatProgram::classify_lifecycle(
3535            &resolved.nodes,
3536            &resolved.wiring,
3537            &resolved.input_defs,
3538            &resolved.output_map,
3539            &resolved.output_modifiers,
3540        );
3541        let layout = slot_layout(resolved);
3542        resolved
3543            .nodes
3544            .iter()
3545            .enumerate()
3546            .filter(|(i, n)| {
3547                classes.lifecycle[*i] == crate::kernel::EvalLifecycle::CompileConst
3548                    && n.meta().outs.len() == 1
3549            })
3550            .map(|(i, n)| {
3551                (
3552                    n.meta().name.clone(),
3553                    layout.port_offsets[i][0],
3554                    n.meta().outs[0].typ,
3555                )
3556            })
3557            .collect()
3558    }
3559
3560    /// Record the constants the build folded, as the interpreter's fold
3561    /// records its own: one event per node, with the value it holds.
3562    fn log_folded(
3563        kernel: &dyn Kernel,
3564        sites: Option<Vec<(String, usize, crate::ast::PortType)>>,
3565        log: Option<&mut crate::dsl::events::CompileEventLog>,
3566    ) {
3567        let (Some(sites), Some(log)) = (sites, log) else {
3568            return;
3569        };
3570        for (node, slot, ty) in sites {
3571            let value = crate::kernel::KernelInternals::slot_value(kernel, slot, ty);
3572            if !matches!(value, crate::ast::Value::None) {
3573                log.push(crate::dsl::events::CompileEvent::ConstantFolded {
3574                    node,
3575                    value: value.to_display_string(),
3576                });
3577            }
3578        }
3579    }
3580
3581    /// The provenance mode a compiled engine builds for `prov`: `Auto`
3582    /// is the selector's choice from the resolved graph's shape
3583    /// ([`select::select_prov_mode`]), on the closure tier and the
3584    /// native engine alike; a named mode is taken as given.
3585    fn provenance_for(prov: Provenance, resolved: &ResolvedDag) -> Provenance {
3586        match prov {
3587            Provenance::Auto => {
3588                let analysis =
3589                    select::analyze_graph(&resolved.nodes, &resolved.wiring, &resolved.output_map);
3590                match select::select_prov_mode(&analysis) {
3591                    ProvMode::Raw => Provenance::Raw,
3592                    ProvMode::Pull => Provenance::Pull,
3593                    ProvMode::PushPull => Provenance::PushPull,
3594                }
3595            }
3596            p => p,
3597        }
3598    }
3599
3600    /// The closure-tier kernel of a resolved graph in one provenance
3601    /// mode, or why the closure tier refuses the graph.
3602    fn closures_from(
3603        resolved: ResolvedDag,
3604        prov: Provenance,
3605    ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3606        let prov = Self::provenance_for(prov, &resolved);
3607        let (coord_count, total_slots, steps, output_map, ref_slots, extras) =
3608            Self::build_p2_layout(&resolved).map_err(Self::refused_by_closures)?;
3609        let dependents = || {
3610            slot_layout(&resolved).expand_dependents(
3611                &resolved,
3612                &PolydatProgram::compute_dependents(
3613                    &PolydatProgram::compute_provenance(&resolved.nodes, &resolved.wiring),
3614                    resolved.input_defs.len(),
3615                ),
3616            )
3617        };
3618        Ok(match prov {
3619            Provenance::Raw => Box::new(CompiledKernelRaw::new(
3620                coord_count,
3621                total_slots,
3622                steps,
3623                output_map,
3624                ref_slots,
3625                extras,
3626            )?),
3627            Provenance::Push => Box::new(CompiledKernelPush::new(
3628                coord_count,
3629                total_slots,
3630                steps,
3631                output_map,
3632                dependents(),
3633                ref_slots,
3634                extras,
3635            )?),
3636            Provenance::Pull => Box::new(CompiledKernelPull::new(
3637                coord_count,
3638                total_slots,
3639                steps,
3640                output_map,
3641                &dependents(),
3642                ref_slots,
3643                extras,
3644            )?),
3645            Provenance::PushPull | Provenance::Auto => Box::new(CompiledKernelPushPull::new(
3646                coord_count,
3647                total_slots,
3648                steps,
3649                output_map,
3650                dependents(),
3651                ref_slots,
3652                extras,
3653            )?),
3654        })
3655    }
3656}
3657
3658#[cfg(test)]
3659mod strict_values_tests {
3660    use super::*;
3661    use crate::ast::{NodeMeta, Port, Slot, Value};
3662    use crate::dsl::const_constraints::ConstConstraint;
3663    use crate::dsl::events::{CompileEvent, CompileEventLog};
3664
3665    /// A pass-through whose one input declares `NonZeroU64`.
3666    struct NonZeroSink {
3667        meta: NodeMeta,
3668    }
3669
3670    impl NonZeroSink {
3671        fn new() -> Self {
3672            let mut port = Port::u64("divisor");
3673            port.constraint = Some(ConstConstraint::NonZeroU64);
3674            NonZeroSink {
3675                meta: NodeMeta {
3676                    name: "nonzero_sink".into(),
3677                    ins: vec![Slot::Wire(port)],
3678                    outs: vec![Port::u64("output")],
3679                },
3680            }
3681        }
3682    }
3683
3684    impl PolydatNode for NonZeroSink {
3685        fn meta(&self) -> &NodeMeta {
3686            &self.meta
3687        }
3688        fn eval(&self, inputs: &[Value], outputs: &mut [Value]) {
3689            outputs[0] = inputs[0].clone();
3690        }
3691    }
3692
3693    fn inserted(asm: PolydatAssembler) -> usize {
3694        let mut log = CompileEventLog::new();
3695        asm.resolve_with_log(Some(&mut log)).expect("resolve");
3696        log.events()
3697            .iter()
3698            .filter(|e| matches!(e, CompileEvent::AssertionInserted { .. }))
3699            .count()
3700    }
3701
3702    /// An assertion node the compiler did not insert for the sink's
3703    /// constraint proves nothing: here it guards a different
3704    /// constraint, and the sink still gets its own guard.
3705    #[test]
3706    fn an_upstream_assertion_for_another_constraint_is_not_proof() {
3707        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3708        asm.add_node(
3709            "ranged",
3710            crate::library::assertions::assert_value_node(
3711                PortType::U64,
3712                ConstConstraint::RangeU64 { min: 0, max: 10 },
3713            ),
3714            vec![WireRef::input("cycle")],
3715        );
3716        asm.add_node(
3717            "sink",
3718            Box::new(NonZeroSink::new()),
3719            vec![WireRef::node("ranged")],
3720        );
3721        asm.add_output("out", WireRef::node("sink"));
3722        asm.set_strict_wires(false, true);
3723        assert_eq!(inserted(asm), 1);
3724    }
3725
3726    /// A node named like an inserted guard is not one: the mark is
3727    /// structural, never a name.
3728    #[test]
3729    fn a_guard_like_name_is_not_proof() {
3730        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3731        asm.add_node(
3732            "__assert_v_0",
3733            Box::new(crate::library::identity::Identity::new(PortType::U64)),
3734            vec![WireRef::input("cycle")],
3735        );
3736        asm.add_node(
3737            "sink",
3738            Box::new(NonZeroSink::new()),
3739            vec![WireRef::node("__assert_v_0")],
3740        );
3741        asm.add_output("out", WireRef::node("sink"));
3742        asm.set_strict_wires(false, true);
3743        assert_eq!(inserted(asm), 1);
3744    }
3745
3746    /// A node added under a scope's `strict_values` is checked though
3747    /// the program's own pragmas leave the flag off; one added outside
3748    /// the scope is not.
3749    #[test]
3750    fn scope_strictness_marks_only_the_nodes_added_under_it() {
3751        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3752        let before = asm.set_scope_strict_values(Some(true));
3753        assert_eq!(before, None);
3754        asm.add_node(
3755            "inner",
3756            Box::new(NonZeroSink::new()),
3757            vec![WireRef::input("cycle")],
3758        );
3759        asm.set_scope_strict_values(before);
3760        asm.add_node(
3761            "outer",
3762            Box::new(NonZeroSink::new()),
3763            vec![WireRef::input("cycle")],
3764        );
3765        asm.add_output("a", WireRef::node("inner"));
3766        asm.add_output("b", WireRef::node("outer"));
3767        assert_eq!(inserted(asm), 1);
3768    }
3769
3770    /// A node added under a scope whose pragmas leave `strict_values`
3771    /// off is unchecked though the program's own pragmas turn it on;
3772    /// the program's nodes are checked.
3773    #[test]
3774    fn a_non_strict_scope_is_unchecked_under_a_strict_program() {
3775        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3776        let before = asm.set_scope_strict_values(Some(false));
3777        asm.add_node(
3778            "inner",
3779            Box::new(NonZeroSink::new()),
3780            vec![WireRef::input("cycle")],
3781        );
3782        asm.set_scope_strict_values(before);
3783        asm.add_node(
3784            "outer",
3785            Box::new(NonZeroSink::new()),
3786            vec![WireRef::input("cycle")],
3787        );
3788        asm.add_output("a", WireRef::node("inner"));
3789        asm.add_output("b", WireRef::node("outer"));
3790        asm.set_strict_wires(false, true);
3791        assert_eq!(inserted(asm), 1);
3792    }
3793}