Skip to main content

polydat_core/compile/
mod.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Kernel compilation: assembled DAG → fast executable kernel.
5//!
6//! Everything in this module is on the path between
7//! [`assembly::PolydatAssembler`] and an executable kernel. The
8//! pipeline:
9//!
10//! ```text
11//! PolydatAssembler ──resolve──▶ ResolvedDag ──compile_with(Engine)──┐
12//!   (fusion, adapters,                                              │
13//!    round-trip lint,          ┌────────────────────────────────────┤
14//!    topo sort)                ▼                  ▼                 ▼
15//!                  Interpreter(JitMode)  Closures(Provenance)  Native(Provenance)
16//!                  cone::extract_jit_cones  closures::           hybrid::
17//!                  → PolydatKernel          CompiledKernel*      HybridKernel*
18//! ```
19//!
20//! The host names the engine ([`select::Engine`]); under
21//! `Provenance::Auto` the selector picks the provenance mode from the
22//! graph's shape. `Engine::PureNative` builds the pure native kernels
23//! (`jit::JitKernel*`): Cranelift code for the whole program, with no
24//! closure fallback (engines.md §1).
25//!
26//! - [`assembly`]: the public construction surface
27//!   ([`assembly::PolydatAssembler`] + [`assembly::WireRef`]) and
28//!   the per-engine compile paths.
29//! - [`fusion`]: graph-level subgraph fusion pass; runs during
30//!   assembly after wiring resolution.
31//! - [`roundtrip_lint`]: the structural type-round-trip lint run at
32//!   resolution.
33//! - [`cone`]: cone-level JIT inside the interpreter kernel
34//!   (engines.md §2), under a [`cone::JitMode`].
35//! - [`lattice`]: the engine-mix report of a compiled program.
36//! - [`select`]: the engine and provenance enums, and the heuristic
37//!   that picks a provenance mode under `Provenance::Auto`.
38//! - [`closures`]: the closure tier, one generated op per node over
39//!   a flat u64 slot buffer, by-reference outputs as `Ref2` pairs.
40//! - [`hybrid`]: the native engine (native segments + closure steps
41//!   sharing a flat u64 buffer).
42//! - [`marshal`]: the boundary marshalling between slots and `Value`s.
43//! - `externs`: extern inputs and `shared` cells on the compiled
44//!   engines.
45//! - [`simd_plan`], `simd_tier1`: scalar-flow SIMD promotion.
46//! - `jit`: Cranelift lowering and the pure native kernels
47//!   (feature-gated on `jit`).
48
49pub mod assembly;
50pub mod closures;
51pub mod cone;
52#[cfg(all(test, feature = "jit"))]
53mod cone_tests;
54pub(crate) mod externs;
55pub mod fusion;
56#[cfg(feature = "jit")]
57pub(crate) mod fusion_units;
58pub mod hybrid;
59#[cfg(feature = "jit")]
60pub mod jit;
61pub mod lattice;
62/// The boundary marshalling a compiled node kit reads its arguments
63/// and writes its outputs through (compiled_handles.md §4): a node
64/// crate's kits use it as the core's own do.
65pub mod marshal;
66pub mod roundtrip_lint;
67pub mod select;
68pub mod simd_plan;
69#[cfg(feature = "jit")]
70pub mod simd_tier1;
71
72/// Axiom S2 typed accessors, shared by the P2 and hybrid kernel
73/// types (both expose `self.core.ref_entry(slot)`). Each returns
74/// a borrow whose lifetime ties to `&self`, so the borrow checker
75/// statically prevents holding a slice across the next
76/// `eval(&mut self)` — stale Ref reads are compile errors.
77macro_rules! ref_readers {
78    () => {
79        /// Borrow a `vec_f32` output's current contents.
80        pub fn read_vec_f32(&self, slot: usize) -> &[f32] {
81            match self.core.ref_entry(slot) {
82                crate::ast::ScratchBuf::F32(v) => v,
83                other => panic!("slot {slot} is not f32-lane scratch: {other:?}"),
84            }
85        }
86        /// Borrow a `vec_f64` output's current contents.
87        pub fn read_vec_f64(&self, slot: usize) -> &[f64] {
88            match self.core.ref_entry(slot) {
89                crate::ast::ScratchBuf::F64(v) => v,
90                other => panic!("slot {slot} is not f64-lane scratch: {other:?}"),
91            }
92        }
93        /// Borrow a `vec_f16` output's current contents.
94        pub fn read_vec_f16(&self, slot: usize) -> &[half::f16] {
95            match self.core.ref_entry(slot) {
96                crate::ast::ScratchBuf::F16(v) => v,
97                other => panic!("slot {slot} is not f16-lane scratch: {other:?}"),
98            }
99        }
100        /// Borrow a `vec_i8` output's current contents.
101        pub fn read_vec_i8(&self, slot: usize) -> &[i8] {
102            match self.core.ref_entry(slot) {
103                crate::ast::ScratchBuf::I8(v) => v,
104                other => panic!("slot {slot} is not i8-lane scratch: {other:?}"),
105            }
106        }
107        /// Borrow a `vec_i16` output's current contents.
108        pub fn read_vec_i16(&self, slot: usize) -> &[i16] {
109            match self.core.ref_entry(slot) {
110                crate::ast::ScratchBuf::I16(v) => v,
111                other => panic!("slot {slot} is not i16-lane scratch: {other:?}"),
112            }
113        }
114        /// Borrow a `vec_i32` output's current contents.
115        pub fn read_vec_i32(&self, slot: usize) -> &[i32] {
116            match self.core.ref_entry(slot) {
117                crate::ast::ScratchBuf::I32(v) => v,
118                other => panic!("slot {slot} is not i32-lane scratch: {other:?}"),
119            }
120        }
121        /// Borrow a `vec_i64` output's current contents.
122        pub fn read_vec_i64(&self, slot: usize) -> &[i64] {
123            match self.core.ref_entry(slot) {
124                crate::ast::ScratchBuf::I64(v) => v,
125                other => panic!("slot {slot} is not i64-lane scratch: {other:?}"),
126            }
127        }
128    };
129}
130pub(crate) use ref_readers;
131
132/// The accessors every compiled kernel type carries, whichever tier it
133/// belongs to: reading an output by name or by slot, the externs and
134/// the cursors it declares, and applying the coordinates a `Kernel`
135/// caller left pending before a pull or an eval. Every one of them
136/// delegates to `self.core`, so none decides anything about evaluation
137/// — which is why seven types can share one copy.
138///
139/// `$set_coords` is the coordinate writer the type uses: the provenance
140/// modes that track a changed-input mask apply coordinates through
141/// `set_inputs`, the rest through `set_coords`. It is the only thing
142/// that varies, and the closure tier and the hybrid had a macro each to
143/// vary it.
144macro_rules! kernel_accessors {
145    ($set_coords:ident) => {
146        /// How many inputs are coordinates. (The core's `coord_count`
147        /// field counts the buffer slots all inputs occupy.)
148        pub fn coord_count(&self) -> usize {
149            self.core.externs.coordinate_count()
150        }
151
152        /// The slot of a named output.
153        pub fn resolve_output(&self, name: &str) -> Option<usize> {
154            self.core.output_map.get(name).copied()
155        }
156
157        /// Read an output by pre-resolved slot index. Panics on
158        /// Ref2-colored slots (axiom S2) — use `read_vec_*`.
159        #[inline]
160        pub fn get_slot(&self, slot: usize) -> u64 {
161            self.core.guard_ref_slot(slot);
162            self.core.buffer[slot]
163        }
164
165        /// Read a named output variate after `eval()`. Panics on
166        /// Ref2-colored outputs (axiom S2) — use `read_vec_*`.
167        #[inline]
168        pub fn get(&self, name: &str) -> u64 {
169            let slot = self.core.output_map[name];
170            self.core.guard_ref_slot(slot);
171            self.core.buffer[slot]
172        }
173
174        /// The named output as a typed `Value`, decoded by its port
175        /// type: a `Ref2` output is copied out through its pair
176        /// (compiled_handles.md §4), so the caller never holds a
177        /// pointer; a slot that holds `None` reads as `None`.
178        pub fn get_value(&self, name: &str) -> crate::ast::Value {
179            self.core.value_of(name)
180        }
181
182        /// A named output, its cone run if a write is pending.
183        pub fn pull_output(&mut self, name: &str) -> crate::ast::Value {
184            self.core.pull_named(name)
185        }
186
187        /// The named output through the `Kernel` trait: the pending
188        /// coordinates are applied, a round begins if a write is pending, and
189        /// only the output's cone runs.
190        fn pull_value(&mut self, name: &str) -> crate::ast::Value {
191            self.apply_pending_coords();
192            self.pull_output(name)
193        }
194
195        /// [`Self::pull_value`] by output index.
196        fn pull_value_at(&mut self, index: usize) -> crate::ast::Value {
197            self.apply_pending_coords();
198            self.core.pull_at(index)
199        }
200
201        /// The coordinates of a pending write, applied once: a pull
202        /// after the first in a round finds nothing written and skips
203        /// the comparison. The round itself begins in the core, which
204        /// clears the pending flag.
205        #[inline]
206        fn apply_pending_coords(&mut self) {
207            if self.core.drive.stale {
208                let coords = std::mem::take(&mut self.core.drive.coords);
209                self.$set_coords(&coords);
210                self.core.drive.coords = coords;
211            }
212        }
213
214        /// `eval` through the `Kernel` trait: the pending coordinates,
215        /// then every step.
216        fn eval_pending(&mut self) {
217            let coords = std::mem::take(&mut self.core.drive.coords);
218            self.eval(&coords);
219            self.core.drive.coords = coords;
220        }
221
222        /// The kernel's externs by name and declared type.
223        pub fn externs(&self) -> Vec<(&str, crate::ast::PortType)> {
224            self.core.externs.names()
225        }
226
227        /// The cursors the program declares, with the partitions the
228        /// compiler resolved where its `over` clause and extent were
229        /// constant, as `PolydatProgram::cursor_schemas` reports them.
230        pub fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
231            self.core.externs.cursor_schemas()
232        }
233
234        /// Narrow a cursor to one partition, as `narrow_cursor` does on
235        /// the interpreter: its `Ext` slot and six scalar projections
236        /// are set as externs.
237        pub fn set_cursor(
238            &mut self,
239            name: &str,
240            partition: &crate::iteration::cursor_partition::Partition,
241        ) -> Result<(), crate::kernel::WriteError> {
242            for (slot, value) in self.core.externs.cursor_writes(name, partition)? {
243                self.set_input(&slot, value)?;
244            }
245            Ok(())
246        }
247
248        crate::compile::ref_readers!();
249    };
250}
251pub(crate) use kernel_accessors;
252
253/// The None rule for fusion (engines.md §3.3): whether a node may join
254/// the run of fused code being formed, as far as `None` is concerned.
255/// The one predicate
256/// both fusers apply — the interpreter's cone planner and the hybrid's
257/// segment batcher — so that what one admits the other admits.
258///
259/// Fused code answers a `None` on a boundary input by making every one
260/// of its outputs `None`, because native code cannot carry one. That is
261/// none_semantics.md Rule 1 and it is the right answer for a node that propagates
262/// a `None`. It is the wrong answer for a node that *consumes* one and
263/// keeps going — `to_json` writes `null`, a `printf` with an `Option`
264/// argument writes its own text — so such a node may join only when
265/// every one of its inputs comes from inside, where a `None` cannot
266/// arrive: either no boundary input is `None` and the run proceeds
267/// normally, or one is and the whole run answers `None` without any
268/// member running at all.
269///
270/// `eligible` is indexed by node and filled in topological order, so a
271/// node's producers are decided before it is.
272#[cfg(feature = "jit")]
273pub(crate) fn none_rule_admits(
274    accepts_none: bool,
275    wiring: &[crate::kernel::WireSource],
276    eligible: &[bool],
277) -> bool {
278    !accepts_none
279        || wiring
280            .iter()
281            .all(|src| matches!(src, crate::kernel::WireSource::NodeOutput(j, _) if eligible[*j]))
282}
283
284/// The highest tier a node can reach, given the types of the wires
285/// feeding it: the one answer to a question four places were asking
286/// separately.
287///
288/// The order is the one every builder walks. Native first, since a node
289/// with a lowering joins a segment; then the compiled forms, in the
290/// order `assembly::node_step_op` tries them — a copy step, the scalar
291/// `compiled_u64`, the node's own slot kit; then the interpreter.
292///
293/// The wire types are not optional. `compiled_slot` is offered per call
294/// site with the types the kernel fixed, so a caller without them can
295/// only ask the first two questions, and the three callers that
296/// reported a tier rather than selecting one did exactly that — they
297/// asked `compiled_u64().is_some()` and called a node with a slot kit
298/// `Phase1`, which is what the binary printed for `printf`.
299pub fn node_tier(
300    node: &dyn crate::ast::PolydatNode,
301    wire_types: &[crate::ast::PortType],
302) -> crate::ast::CompileLevel {
303    #[cfg(feature = "jit")]
304    if !matches!(
305        crate::compile::jit::classify_node_typed(node, wire_types),
306        crate::compile::jit::JitOp::Fallback
307    ) {
308        return crate::ast::CompileLevel::Phase3;
309    }
310    let meta = node.meta();
311    let is_copy =
312        (meta.name == "identity" || meta.name.starts_with("__port_")) && meta.outs.len() == 1;
313    let has_kit = node
314        .compiled_slot(
315            wire_types,
316            crate::compile::select::Engine::Closures(crate::compile::select::Provenance::Auto),
317        )
318        .is_some();
319    if is_copy || node.compiled_u64().is_some() || has_kit {
320        crate::ast::CompileLevel::Phase2
321    } else {
322        crate::ast::CompileLevel::Phase1
323    }
324}
325
326/// The provenance of every buffer slot: which input slots reach it,
327/// as an exact multi-word mask, for the pull-side cone guard of every
328/// compiled kernel. `input_dependents` is indexed by input slot (a
329/// multi-slot input repeats its list per slot) and lists the steps
330/// downstream of that slot; `step_output_slots` gives each step's
331/// output slots, which all take the step's mask. A coordinate slot's
332/// provenance is itself.
333pub(crate) fn slot_provenance(
334    coord_count: usize,
335    total_slots: usize,
336    step_output_slots: &[&[usize]],
337    input_dependents: &[Vec<usize>],
338) -> Vec<crate::kernel::ProvMask> {
339    use crate::kernel::ProvMask;
340    let step_count = step_output_slots.len();
341    let mut step_prov: Vec<ProvMask> = (0..step_count).map(|_| ProvMask::empty()).collect();
342    for (input_slot, deps) in input_dependents.iter().enumerate() {
343        for &step in deps {
344            if step < step_count {
345                step_prov[step].set(input_slot);
346            }
347        }
348    }
349    let mut slots: Vec<ProvMask> = (0..total_slots).map(|_| ProvMask::empty()).collect();
350    for (i, slot) in slots.iter_mut().enumerate().take(coord_count) {
351        slot.set(i);
352    }
353    for (step, outs) in step_output_slots.iter().enumerate() {
354        for &slot in outs.iter() {
355            if slot < slots.len() {
356                slots[slot] = step_prov[step].clone();
357            }
358        }
359    }
360    slots
361}
362
363/// The coordinates a host set last on a compiled kernel and whether
364/// they have been evaluated: what the [`Kernel`](crate::kernel::Kernel)
365/// trait's `set_inputs` and `pull` keep between calls.
366#[derive(Clone, Default)]
367pub(crate) struct Drive {
368    pub(crate) coords: Vec<u64>,
369    pub(crate) stale: bool,
370}
371
372/// The slot surface of a compiled kernel: the extended API, over and
373/// above the [`Kernel`](crate::kernel::Kernel) trait every engine
374/// answers.
375///
376/// Every compiled engine lays its program out over one flat `u64` slot
377/// buffer (engines.md §6). That layout is an implementation detail, and
378/// this trait is where it is admitted: a slot index instead of an
379/// output name, a raw `u64` instead of a `Value`, a borrow into the
380/// scratch a by-reference output writes. The interpreter does not
381/// implement it and cannot — its buffers are typed `Value`s and it has
382/// no slot to name — which is the point: the shape of this trait *is*
383/// the thing the compiled tiers share and the interpreter does not.
384///
385/// **This is not the surface for running a program.** Driving a kernel
386/// is `Kernel`, on every engine, and a host that never names an engine
387/// never sees this trait. Reach for it when the implementation detail
388/// is the subject: a differential test asserting on what was laid out,
389/// a benchmark measuring a tier without the `Value` construction and
390/// the name lookup a `pull` pays, a diagnostic reporting on a slot.
391///
392/// It is a subtrait rather than a wider `Kernel`, so it is opt-in at
393/// the import: a caller who does not write `use SlotKernel` does not
394/// have these methods on their kernel at all. And it is reachable
395/// without naming a kernel type, through
396/// [`PolydatAssembler::compile_slots`](crate::compile::assembly::PolydatAssembler::compile_slots),
397/// which hands back a `Box<dyn SlotKernel>` that upcasts to
398/// `Box<dyn Kernel>` wherever the ordinary surface will do.
399pub trait SlotKernel: crate::kernel::Kernel {
400    /// The buffer slot a named output writes, resolved once so a
401    /// caller reading the same output every cycle pays no lookup.
402    fn resolve_output(&self, name: &str) -> Option<usize>;
403
404    /// The raw `u64` in `slot`, as it stands: no evaluation, no
405    /// decoding. Panics on a `Ref2` slot (axiom S2), which has no
406    /// scalar to read — use the `read_vec_*` borrows.
407    fn get_slot(&self, slot: usize) -> u64;
408
409    /// [`Self::get_slot`] by output name.
410    fn get(&self, name: &str) -> u64;
411
412    /// A named output decoded by its port type, a `Ref2` output copied
413    /// out through its pair so the caller never holds a pointer. Reads
414    /// what is there; [`Kernel::pull`](crate::kernel::Kernel::pull)
415    /// evaluates first.
416    fn get_value(&self, name: &str) -> crate::ast::Value;
417
418    /// Set the coordinates, evaluate what `slot` needs, and return its
419    /// raw `u64`. The whole read in one call and one `u64`, which is
420    /// what a tier benchmark wants: `pull_at` gives the same value
421    /// through a `Value` it has to construct.
422    fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64;
423
424    /// Set the coordinates and run every step, the whole program in
425    /// one call. [`Kernel::eval`](crate::kernel::Kernel::eval) is the
426    /// same evaluation over coordinates already written with
427    /// `set_inputs`; this is the form that takes them, which is what a
428    /// loop over a coordinate range wants.
429    fn eval_at(&mut self, coords: &[u64]);
430
431    /// Borrow a `vec_f32` output's current contents. The borrow ties to
432    /// `&self`, so holding one across the next evaluation is a compile
433    /// error rather than a stale read (axiom S2).
434    fn read_vec_f32(&self, slot: usize) -> &[f32];
435    /// Borrow a `vec_f64` output's current contents.
436    fn read_vec_f64(&self, slot: usize) -> &[f64];
437    /// Borrow a `vec_f16` output's current contents.
438    fn read_vec_f16(&self, slot: usize) -> &[half::f16];
439    /// Borrow a `vec_i8` output's current contents.
440    fn read_vec_i8(&self, slot: usize) -> &[i8];
441    /// Borrow a `vec_i16` output's current contents.
442    fn read_vec_i16(&self, slot: usize) -> &[i16];
443    /// Borrow a `vec_i32` output's current contents.
444    fn read_vec_i32(&self, slot: usize) -> &[i32];
445    /// Borrow a `vec_i64` output's current contents.
446    fn read_vec_i64(&self, slot: usize) -> &[i64];
447}
448
449/// [`SlotKernel`] for a compiled kernel, forwarding to the inherent
450/// methods the type already has. The trait is the surface; the
451/// inherent copies are what it forwards to and what this crate calls.
452macro_rules! impl_slot_kernel {
453    ($ty:ident) => {
454        impl crate::compile::SlotKernel for $ty {
455            fn resolve_output(&self, name: &str) -> Option<usize> {
456                $ty::resolve_output(self, name)
457            }
458            fn get_slot(&self, slot: usize) -> u64 {
459                $ty::get_slot(self, slot)
460            }
461            fn get(&self, name: &str) -> u64 {
462                $ty::get(self, name)
463            }
464            fn get_value(&self, name: &str) -> crate::ast::Value {
465                $ty::get_value(self, name)
466            }
467            fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
468                $ty::eval_for_slot(self, coords, slot)
469            }
470            fn eval_at(&mut self, coords: &[u64]) {
471                $ty::eval(self, coords)
472            }
473            fn read_vec_f32(&self, slot: usize) -> &[f32] {
474                $ty::read_vec_f32(self, slot)
475            }
476            fn read_vec_f64(&self, slot: usize) -> &[f64] {
477                $ty::read_vec_f64(self, slot)
478            }
479            fn read_vec_f16(&self, slot: usize) -> &[half::f16] {
480                $ty::read_vec_f16(self, slot)
481            }
482            fn read_vec_i8(&self, slot: usize) -> &[i8] {
483                $ty::read_vec_i8(self, slot)
484            }
485            fn read_vec_i16(&self, slot: usize) -> &[i16] {
486                $ty::read_vec_i16(self, slot)
487            }
488            fn read_vec_i32(&self, slot: usize) -> &[i32] {
489                $ty::read_vec_i32(self, slot)
490            }
491            fn read_vec_i64(&self, slot: usize) -> &[i64] {
492                $ty::read_vec_i64(self, slot)
493            }
494        }
495    };
496}
497pub(crate) use impl_slot_kernel;
498
499/// The [`Kernel`](crate::kernel::Kernel) impl every compiled kernel
500/// shares: the type's inherent `eval_pending`, `pull_value`,
501/// `pull_value_at`, `set_input`, `set_input_at`, `set_cursor`,
502/// `mark_all_dirty`, and a `core` with `drive`, `externs`,
503/// `coord_count`, `output_types`, `output_map`, `buffer`,
504/// `traversals`, and `plan`/`invalidate_all`/`attach_cell`/
505/// `slot_value`.
506macro_rules! impl_kernel_trait {
507    ($ty:ident) => {
508        impl crate::kernel::Kernel for $ty {
509            fn engine(&self) -> crate::compile::select::Engine {
510                self.core.engine
511            }
512            fn set_inputs(&mut self, coords: &[u64]) {
513                self.core.drive.coords.clear();
514                self.core.drive.coords.extend_from_slice(coords);
515                self.core.drive.stale = true;
516            }
517            fn set_input(
518                &mut self,
519                name: &str,
520                value: crate::ast::Value,
521            ) -> Result<(), crate::kernel::WriteError> {
522                if self.core.externs.is_const_name(name) {
523                    return Err(crate::kernel::WriteError::ConstSlot {
524                        slot: name.to_string(),
525                    });
526                }
527                self.core.drive.stale = true;
528                $ty::set_input(self, name, value)
529            }
530            fn const_inits(&self) -> &[crate::kernel::ConstInit] {
531                self.core.externs.const_inits()
532            }
533            fn init_input_at(
534                &mut self,
535                index: usize,
536                value: crate::ast::Value,
537            ) -> Result<(), crate::kernel::WriteError> {
538                self.core.drive.stale = true;
539                $ty::set_input_at(self, index, value)
540            }
541            fn set_cursor(
542                &mut self,
543                name: &str,
544                partition: &crate::iteration::cursor_partition::Partition,
545            ) -> Result<(), crate::kernel::WriteError> {
546                self.core.drive.stale = true;
547                $ty::set_cursor(self, name, partition)
548            }
549            fn eval(&mut self) {
550                self.eval_pending();
551                self.core.drive.stale = false;
552            }
553            fn pull(&mut self, name: &str) -> crate::ast::Value {
554                self.pull_value(name)
555            }
556            fn input_names(&self) -> Vec<String> {
557                self.core.externs.input_names().to_vec()
558            }
559            /// In declaration order, as the interpreter lists them: the
560            /// assembler sets them on every compiled kernel.
561            fn output_names(&self) -> Vec<String> {
562                self.core.externs.output_names().to_vec()
563            }
564            fn output_type(&self, name: &str) -> Option<crate::ast::PortType> {
565                self.core.output_types.get(name).copied()
566            }
567            /// As the assembler found them in the graph this kernel
568            /// was compiled from.
569            fn dataset_sources(&self, name: &str) -> Option<crate::kernel::DatasetSources> {
570                self.core.externs.dataset_sources(name)
571            }
572            fn externs(&self) -> Vec<(String, crate::ast::PortType)> {
573                self.core
574                    .externs
575                    .names()
576                    .into_iter()
577                    .map(|(n, t)| (n.to_string(), t))
578                    .collect()
579            }
580            fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
581                self.core.externs.cursor_schemas()
582            }
583            fn input_value(&self, name: &str) -> Option<crate::ast::Value> {
584                self.core.externs.value(name).or_else(|| {
585                    let i = self
586                        .core
587                        .externs
588                        .input_names()
589                        .iter()
590                        .position(|n| n == name)?;
591                    if i < self.core.externs.coordinate_count() {
592                        let pending = self.core.drive.coords.get(i).copied();
593                        Some(crate::ast::Value::U64(
594                            pending.unwrap_or(self.core.buffer[i]),
595                        ))
596                    } else {
597                        None
598                    }
599                })
600            }
601            fn traversals(&self) -> &[crate::dsl::traversal::Traversal] {
602                &self.core.traversals
603            }
604            fn plan(&self) -> crate::EnginePlan {
605                self.core.plan()
606            }
607            fn input_index(&self, name: &str) -> Option<usize> {
608                self.core
609                    .externs
610                    .input_names()
611                    .iter()
612                    .position(|n| n == name)
613            }
614            fn set_input_at(
615                &mut self,
616                index: usize,
617                value: crate::ast::Value,
618            ) -> Result<(), crate::kernel::WriteError> {
619                if self.core.externs.is_const_index(index) {
620                    return Err(crate::kernel::WriteError::ConstSlot {
621                        slot: self.core.externs.input_names()[index].clone(),
622                    });
623                }
624                self.core.drive.stale = true;
625                $ty::set_input_at(self, index, value)
626            }
627            fn output_index(&self, name: &str) -> Option<usize> {
628                self.core
629                    .externs
630                    .output_names()
631                    .iter()
632                    .position(|n| n == name)
633            }
634            fn pull_at(&mut self, index: usize) -> crate::ast::Value {
635                self.pull_value_at(index)
636            }
637            fn traverse(&mut self, index: usize) -> Result<crate::kernel::TraversalStream, String> {
638                let traversal = self.core.traversals.get(index).cloned().ok_or_else(|| {
639                    format!(
640                        "no traversal at index {index}; the program declares {}",
641                        self.core.traversals.len()
642                    )
643                })?;
644                crate::kernel::activation::open_traversal(self, traversal)
645            }
646            fn invalidate_all(&mut self) {
647                self.mark_all_dirty();
648                self.core.invalidate_all();
649            }
650            fn shared_cells(&self) -> Vec<crate::kernel::SharedCellEntry> {
651                self.core.externs.shared_cells()
652            }
653            fn output_cell(&self, name: &str) -> Option<crate::kernel::SharedCell> {
654                self.core.output_cell_for(name)
655            }
656            fn output_modifier(&self, name: &str) -> crate::dsl::ast::BindingModifier {
657                self.core.externs.output_modifier(name)
658            }
659            fn cells_in_scope(&self) -> Vec<crate::kernel::SharedCellEntry> {
660                self.core.externs.cells_in_scope()
661            }
662            fn set_transit_cells(&mut self, cells: Vec<crate::kernel::SharedCellEntry>) {
663                self.core.externs.set_transit_cells(cells);
664            }
665            fn input_port_type(&self, name: &str) -> Option<crate::ast::PortType> {
666                self.core.externs.input_port_type(name)
667            }
668            fn bind_input_cell(&mut self, name: &str, cell: crate::kernel::SharedCell) -> bool {
669                let Some(slot) = self.core.externs.bind_cell(name, cell) else {
670                    return false;
671                };
672                // The slot's value is the cell's from the next refresh,
673                // so everything downstream of it reruns.
674                self.core.dirty_input(slot);
675                true
676            }
677            fn attach_shared_cell(
678                &mut self,
679                name: &str,
680                cell: crate::kernel::SharedCell,
681            ) -> Result<(), String> {
682                self.core.attach_cell(name, cell)
683            }
684            fn into_program(
685                mut self: Box<Self>,
686            ) -> std::sync::Arc<dyn crate::kernel::KernelProgram> {
687                self.mark_all_dirty();
688                self.core.drive.stale = true;
689                std::sync::Arc::new(crate::kernel::SharedKernel(*self))
690            }
691            fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
692                self.core.externs.ledger()
693            }
694            fn resources(&self) -> &crate::resource::ResourceScope {
695                self.core.externs.resources()
696            }
697            fn canonical_hash(&self) -> [u8; 32] {
698                crate::kernel::program_identity(
699                    self.core.externs.graph_identity(),
700                    self.core.externs.inherited_outputs().iter(),
701                    crate::kernel::Kernel::cursor_schemas(self),
702                    crate::kernel::Kernel::traversals(self),
703                )
704            }
705            fn coord_count(&self) -> usize {
706                self.core.externs.coordinate_count()
707            }
708            fn input_value_at(&self, index: usize) -> Option<crate::ast::Value> {
709                if index < self.core.externs.coordinate_count() {
710                    let pending = self.core.drive.coords.get(index).copied();
711                    return Some(crate::ast::Value::U64(
712                        pending.unwrap_or(self.core.buffer[index]),
713                    ));
714                }
715                self.core.externs.value_at(index)
716            }
717            fn input_default_at(&self, index: usize) -> Option<crate::ast::Value> {
718                if index < self.core.externs.coordinate_count() {
719                    return Some(crate::ast::Value::U64(0));
720                }
721                self.core.externs.default_at(index)
722            }
723            fn input_is_cell_bound(&self, index: usize) -> bool {
724                self.core.externs.is_cell_bound_at(index)
725            }
726            fn reset_inputs(&mut self) {
727                let count = self.core.externs.input_names().len();
728                for index in self.core.externs.coordinate_count()..count {
729                    if self.core.externs.is_cell_bound_at(index) {
730                        continue;
731                    }
732                    let (Some(now), Some(default)) = (
733                        self.core.externs.value_at(index),
734                        self.core.externs.default_at(index),
735                    ) else {
736                        continue;
737                    };
738                    if now != default {
739                        // The typed write, so what depends on the input
740                        // is marked as any write marks it. A declared
741                        // default satisfies its own slot.
742                        let _ = crate::kernel::Kernel::set_input_at(self, index, default);
743                    }
744                }
745            }
746            fn fork(&self) -> Box<dyn crate::kernel::Kernel> {
747                // A clone is a new state of the same program with this
748                // one's values: shared slots keep their cells, transit
749                // cells travel, and broadcast cells stay with the
750                // original, which is what descendants are bound to.
751                Box::new(self.clone())
752            }
753            fn publish_broadcasts(&mut self) {
754                if !self.core.externs.broadcasts() {
755                    return;
756                }
757                let names: Vec<String> = self.core.externs.output_names().to_vec();
758                for name in names {
759                    let Some(&slot) = self.core.output_map.get(&name) else {
760                        continue;
761                    };
762                    if self.core.externs.published_output(slot).is_none() {
763                        continue;
764                    }
765                    // The pull by name publishes through the cell. A
766                    // failure is left for the pull that needs the value.
767                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
768                        self.pull_value(&name);
769                    }));
770                }
771            }
772            fn commit_write_throughs(&mut self) -> Result<(), String> {
773                let pairs = self.core.externs.write_throughs().to_vec();
774                let mut pending = Vec::with_capacity(pairs.len());
775                for (export, source) in &pairs {
776                    let Some(slot_type) = self.core.externs.input_port_type(export) else {
777                        continue;
778                    };
779                    let value = self.pull_value(source);
780                    let value =
781                        crate::kernel::check_write_through_type(export, source, slot_type, value)?;
782                    pending.push((export.clone(), value));
783                }
784                for (export, value) in pending {
785                    crate::kernel::Kernel::set_input(self, &export, value)
786                        .map_err(|e| format!("write-through into `{export}`: {e}"))?;
787                }
788                Ok(())
789            }
790            fn program_id(&self) -> crate::kernel::ProgramId {
791                crate::kernel::ProgramId(self.core.program_identity())
792            }
793            fn input_type_origin(&self, name: &str) -> Option<crate::kernel::TypeOrigin> {
794                self.core.externs.input_type_origin(name)
795            }
796        }
797
798        impl crate::kernel::KernelInternals for $ty {
799            fn set_write_throughs(&mut self, pairs: Vec<(String, String)>) {
800                self.core.externs.set_write_throughs(pairs);
801            }
802            fn set_inherited_outputs(&mut self, names: Vec<String>) {
803                self.core.externs.set_inherited_outputs(names);
804            }
805            /// A compiled kernel keeps the traversals; each carries the
806            /// comprehension its producer resolved to at compile time.
807            fn set_traversals(
808                &mut self,
809                traversals: Vec<crate::dsl::traversal::Traversal>,
810                _producers: Vec<crate::dsl::traversal::Producer>,
811            ) {
812                self.core.traversals = traversals.into();
813            }
814            fn slot_value(&self, slot: usize, ty: crate::ast::PortType) -> crate::ast::Value {
815                self.core.slot_value(slot, ty)
816            }
817            /// Only for an output fixed for the kernel's life, a const or
818            /// a value folded at build: a computed output's slot holds its
819            /// last evaluated value, which is not the scope's.
820            ///
821            /// A `const` captured at initialization answers from its slot,
822            /// which initialization writes, so its value is there before
823            /// anything evaluates its output.
824            fn folded_value(&self, name: &str) -> Option<crate::ast::Value> {
825                if !self.core.externs.is_fixed_output(name) {
826                    return None;
827                }
828                if let Some(c) = self
829                    .core
830                    .externs
831                    .const_inits()
832                    .iter()
833                    .find(|c| c.name == name)
834                {
835                    return crate::kernel::Kernel::input_value_at(self, c.slot_index);
836                }
837                let slot = *self.core.output_map.get(name)?;
838                let ty = *self.core.output_types.get(name)?;
839                Some(self.core.slot_value(slot, ty))
840            }
841            fn set_cursor_extent(&mut self, index: usize, extent: u64) {
842                self.core.externs.set_cursor_extent(index, extent);
843            }
844            fn reset_to_program(&mut self) {
845                self.core.externs.reset_to_program(&mut self.core.buffer);
846                self.mark_all_dirty();
847            }
848        }
849    };
850}
851pub(crate) use impl_kernel_trait;
852
853/// The bookkeeping every compiled engine keeps, whatever its steps
854/// are: the evaluation round and what ran in it, the clean flags and
855/// what a write dirties, the extern writes and the cell refresh, the
856/// reference pairs a step publishes, and reading an output back.
857///
858/// Both compiled cores carry the same fields for these, and this macro
859/// gives them one copy of the methods. None of them touches the step
860/// list, which is the one thing the two tiers genuinely differ about:
861/// a step on the closure tier is always a closure, and on the native
862/// tier it is a closure or a run of native code. That difference lives
863/// in the run loops, which stay per tier (engines.md §8).
864macro_rules! shared_core_methods {
865    () => {
866        /// Axiom S2 typed accessor core: resolve a Ref pair's first
867        /// slot to its kernel-owned scratch entry. The returned
868        /// borrow ties to `&self`, so holding it across the next
869        /// `eval(&mut self)` is a compile error — stale reads are
870        /// statically impossible.
871        fn ref_entry(&self, slot: usize) -> &crate::ast::ScratchBuf {
872            match self.ref_scratch.iter().find(|(s, _)| *s == slot) {
873                Some(&(_, idx)) => &self.scratch[idx],
874                None if self.ref_slots.get(slot).copied().unwrap_or(false) => panic!(
875                    "slot {slot} is a Ref pair owned by the CALLER (a kernel \
876                     input) — read it on the caller side"
877                ),
878                None => panic!("slot {slot} is not a Ref2-colored slot"),
879            }
880        }
881
882        /// Run `body` with the failure path armed: a panic inside a
883        /// step is recorded quietly and re-raised enriched, as the
884        /// interpreter re-raises a node's (engines.md §3.4), and every
885        /// reference pair is checked afterwards in a debug build.
886        ///
887        /// `#[inline]` is load-bearing: this wraps every `eval`, and
888        /// without it the native rung of the ladder pays a call and
889        /// about seven percent.
890        #[inline]
891        fn run_guarded(&mut self, body: impl FnOnce(&mut Self)) {
892            let capture = crate::kernel::engines::EvalPanicCaptureGuard::arm();
893            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(self)));
894            drop(capture);
895            if let Err(payload) = outcome {
896                let sites = std::sync::Arc::clone(&self.sites);
897                let node = self.failing_node();
898                sites.reraise(payload, node, &self.buffer, Some(&self.none));
899            }
900            #[cfg(debug_assertions)]
901            self.validate_refs();
902        }
903
904        /// Axiom S9: every reference pair in the buffer names the
905        /// scratch entry that owns it. A slot is skipped when nothing
906        /// has been published into it — its step has not run, or it
907        /// carries `None`.
908        ///
909        /// Gated to `debug_assertions` to match its call sites, which
910        /// compile out in release.
911        #[cfg(debug_assertions)]
912        fn validate_refs(&self) {
913            for &(slot, idx) in &self.ref_scratch {
914                let unpublished = self.none[slot]
915                    || matches!(self.slot_step.get(slot), Some(Some(step)) if self.ran[*step] == 0);
916                if unpublished {
917                    continue;
918                }
919                let (p, l) = self.scratch[idx].ptr_len();
920                assert!(
921                    self.buffer[slot] == p && self.buffer[slot + 1] == l,
922                    "S9 ref-validator: slot pair ({slot}, {}) = ({:#x}, {}) \
923                     does not match scratch[{idx}] = ({p:#x}, {l}) — a slot \
924                     op failed to republish or wrote the wrong slots",
925                    slot + 1,
926                    self.buffer[slot],
927                    self.buffer[slot + 1],
928                );
929            }
930        }
931
932        fn attach_cell(
933            &mut self,
934            name: &str,
935            cell: crate::kernel::SharedCell,
936        ) -> Result<(), String> {
937            let slot = self.externs.attach_cell(name, cell)?;
938            self.dirty_input(slot);
939            self.drive.stale = true;
940            Ok(())
941        }
942
943        #[inline]
944        fn begin_epoch(&mut self) {
945            if self.externs.cells_dirty() {
946                self.externs.refresh_cells(&mut self.buffer);
947            }
948            self.dirty_refreshed();
949            self.epoch += 1;
950            self.all_ran = false;
951            for &i in self.volatile_steps.iter() {
952                self.clean[i] = false;
953            }
954            self.drive.stale = false;
955        }
956
957        /// A read that begins no round still re-evaluates every volatile
958        /// step its cone reaches, once, and the steps downstream of it
959        /// (runtime_model.md R1.v); steps upstream of a volatile step
960        /// keep their currency. A new round already leaves every
961        /// volatile step unrun. Most programs have no volatile step and
962        /// pay the emptiness check.
963        #[inline]
964        fn rearm_volatile(&mut self) {
965            if self.volatile_steps.is_empty() {
966                return;
967            }
968            for &i in self.volatile_steps.iter() {
969                self.ran[i] = 0;
970            }
971            self.all_ran = false;
972        }
973
974        #[inline]
975        fn dirty_input(&mut self, slot: usize) {
976            if let Some(deps) = self.dirty.get(slot) {
977                for &i in deps {
978                    self.clean[i] = false;
979                }
980            }
981        }
982
983        /// Inlined into every evaluation, so only the check lives here:
984        /// a cell refresh changing a slot is rare, and its work is kept
985        /// out of line where it does not grow the hot path.
986        #[inline]
987        fn dirty_refreshed(&mut self) {
988            if self.externs.has_changed() {
989                self.dirty_refreshed_slots();
990            }
991        }
992
993        #[cold]
994        #[inline(never)]
995        fn dirty_refreshed_slots(&mut self) {
996            let changed = self.externs.take_changed();
997            for &slot in &changed {
998                // The cell's value is the slot's now: a slot that was
999                // unset (an extern with no default, bound to a parent's
1000                // cell) holds a value, and one the cell cleared holds
1001                // none, as a direct write would leave it.
1002                if let Some(mask) = self.none.get_mut(slot) {
1003                    *mask = self.externs.slot_is_unset(slot);
1004                }
1005                if let Some(deps) = self.plan.input_dependents.get(slot) {
1006                    for &i in deps {
1007                        self.ran[i] = 0;
1008                        self.clean[i] = false;
1009                    }
1010                    self.all_ran = false;
1011                }
1012            }
1013            self.externs.return_changed(changed);
1014            let was = self.any_none;
1015            self.any_none = self.externs.any_unset();
1016            if was && !self.any_none {
1017                self.none.fill(false);
1018            }
1019        }
1020
1021        #[inline]
1022        fn eval_all(&mut self) {
1023            let fresh = self.drive.stale;
1024            if fresh {
1025                self.begin_epoch();
1026            } else {
1027                self.refresh_cells();
1028                self.rearm_volatile();
1029            }
1030            if fresh && !self.use_clean && !self.any_none {
1031                self.run_guarded(|core| core.run_fresh());
1032            } else {
1033                let all = std::sync::Arc::clone(&self.all);
1034                self.run_steps(&all);
1035            }
1036        }
1037
1038        fn extern_written(&mut self, slot: usize, unset: bool) {
1039            self.none[slot] = unset;
1040            let was = self.any_none;
1041            self.any_none = self.externs.any_unset();
1042            if was && !self.any_none {
1043                self.none.fill(false);
1044            }
1045            self.dirty_input(slot);
1046            self.drive.stale = true;
1047        }
1048
1049        #[inline]
1050        fn guard_ref_slot(&self, slot: usize) {
1051            if self.ref_slots.get(slot).copied().unwrap_or(false) {
1052                panic!(
1053                    "S2 pointer containment: slot {slot} is Ref2-colored; raw u64 readers \
1054                     would leak an interior address. Use the typed borrow-checked accessor \
1055                     (read_vec_*), the boundary decode, or copy out."
1056                );
1057            }
1058        }
1059
1060        fn invalidate_all(&mut self) {
1061            self.clean.fill(false);
1062            self.all_ran = false;
1063            self.drive.stale = true;
1064        }
1065
1066        /// A pull by index publishes as a pull by name does, so a child
1067        /// bound to this output reads what the parent computed. The flag
1068        /// is checked before the pull rather than after it: holding the
1069        /// value across the check cost the native rungs 6 percent.
1070        #[inline]
1071        fn pull_at(&mut self, index: usize) -> crate::ast::Value {
1072            if self.externs.broadcasts() {
1073                return self.pull_at_publishing(index);
1074            }
1075            self.pull_at_value(index)
1076        }
1077
1078        /// `pull_at` under a descendant: the pull, then the publish.
1079        #[cold]
1080        #[inline(never)]
1081        fn pull_at_publishing(&mut self, index: usize) -> crate::ast::Value {
1082            let value = self.pull_at_value(index);
1083            let slot = self.resolved_outputs[index]
1084                .as_ref()
1085                .expect("resolved by the pull")
1086                .0;
1087            self.publish_slot(slot, &value);
1088            value
1089        }
1090
1091        #[inline(always)]
1092        fn pull_at_value(&mut self, index: usize) -> crate::ast::Value {
1093            if self.resolved_outputs.len() <= index {
1094                self.resolved_outputs.resize(index + 1, None);
1095            }
1096            if self.resolved_outputs[index].is_none() {
1097                let name = self
1098                    .externs
1099                    .output_names()
1100                    .get(index)
1101                    .cloned()
1102                    .unwrap_or_else(|| {
1103                        panic!(
1104                            "no output at index {index}; this kernel declares {}",
1105                            self.externs.output_names().len()
1106                        )
1107                    });
1108                let slot = self.output_map[&name];
1109                let ty = self
1110                    .output_types
1111                    .get(&name)
1112                    .copied()
1113                    .unwrap_or(crate::ast::PortType::U64);
1114                let cone = self
1115                    .plan
1116                    .cones
1117                    .get(&name)
1118                    .map(|c| std::sync::Arc::<[usize]>::from(c.as_slice()));
1119                let can_fail = cone
1120                    .as_ref()
1121                    .is_some_and(|c| c.iter().any(|&i| self.step_can_fail(i)));
1122                self.resolved_outputs[index] = Some((slot, ty, cone, can_fail));
1123            }
1124            if self.drive.stale {
1125                self.begin_epoch();
1126            } else {
1127                self.refresh_cells();
1128                self.rearm_volatile();
1129            }
1130            let resolved = self.resolved_outputs[index]
1131                .as_ref()
1132                .expect("resolved above");
1133            let (slot, ty, can_fail) = (resolved.0, resolved.1, resolved.3);
1134            if let Some(order) = &resolved.2 {
1135                // Borrowed across the run rather than cloned: the order
1136                // lives behind an `Arc` this state holds, and running
1137                // steps never touches the resolved outputs.
1138                let order: *const [usize] = &**order;
1139                let order = unsafe { &*order };
1140                if can_fail {
1141                    self.run_steps(order);
1142                } else {
1143                    // No step of the cone can fail, so there is no
1144                    // failure to capture and attribute.
1145                    self.run_order(order);
1146                }
1147            }
1148            self.slot_value(slot, ty)
1149        }
1150
1151        /// Publish the value at `slot` through its broadcast cell, if a
1152        /// descendant asked for one.
1153        fn publish_slot(&self, slot: usize, value: &crate::ast::Value) {
1154            if let Some(cell) = self.externs.published_output(slot) {
1155                cell.publish(value.clone());
1156            }
1157        }
1158
1159        fn pull_named(&mut self, name: &str) -> crate::ast::Value {
1160            if self.drive.stale {
1161                self.begin_epoch();
1162            } else {
1163                self.refresh_cells();
1164                self.rearm_volatile();
1165            }
1166            let plan = std::sync::Arc::clone(&self.plan);
1167            if let Some(order) = plan.cones.get(name) {
1168                self.run_steps(order);
1169            }
1170            let value = self.value_of(name);
1171            self.broadcast(name, &value);
1172            value
1173        }
1174
1175        /// Publish a freshly computed output through its broadcast cell,
1176        /// if a descendant asked for one, so a child that bound its
1177        /// matching input slot to the same cell reads the new value
1178        /// (cross_fiber_invalidation.md §3.1, "broadcast outputs").
1179        ///
1180        /// A program nobody built a subscope under has no cells at all,
1181        /// and pays the emptiness check.
1182        #[inline]
1183        fn broadcast(&mut self, name: &str, value: &crate::ast::Value) {
1184            if !self.externs.broadcasts() {
1185                return;
1186            }
1187            if let Some(&slot) = self.output_map.get(name) {
1188                self.publish_slot(slot, value);
1189            }
1190        }
1191
1192        /// The broadcast cell for a named output, created on the first
1193        /// ask. The interpreter seeds one per output at construction;
1194        /// a compiled kernel makes them only when a descendant binds to
1195        /// one, so a program with no subscope under it allocates none.
1196        ///
1197        /// Keyed by the output's slot, which is what `output_map`
1198        /// answers and what the buffer is indexed by, so the vector is
1199        /// as long as the buffer rather than as long as the output list.
1200        fn output_cell_for(&self, name: &str) -> Option<crate::kernel::SharedCell> {
1201            let slot = *self.output_map.get(name)?;
1202            // An output no step has computed yet holds its type's zero
1203            // in the buffer; the cell starts at `None`, as the
1204            // interpreter's does, until the first pull publishes.
1205            let uncomputed = !self.all_ran
1206                && matches!(self.slot_step.get(slot), Some(Some(step)) if self.ran[*step] == 0);
1207            let initial = if uncomputed {
1208                crate::ast::Value::None
1209            } else {
1210                self.value_of(name)
1211            };
1212            Some(self.externs.output_cell(slot, initial))
1213        }
1214
1215        #[inline]
1216        fn refresh_cells(&mut self) {
1217            if self.externs.cells_dirty() {
1218                self.externs.refresh_cells(&mut self.buffer);
1219                self.dirty_refreshed();
1220            }
1221        }
1222
1223        fn republish_refs(&mut self) {
1224            for &(slot, idx) in &self.ref_scratch {
1225                let (p, l) = self.scratch[idx].ptr_len();
1226                self.buffer[slot] = p;
1227                self.buffer[slot + 1] = l;
1228            }
1229            self.externs.seed(&mut self.buffer, None);
1230        }
1231
1232        #[inline]
1233        fn run_steps(&mut self, order: &[usize]) {
1234            self.run_guarded(|core| core.run_order(order));
1235        }
1236
1237        /// `run_steps` for the build-time constant fold: the same steps
1238        /// under the same guard, but a failure comes back as the
1239        /// message [`Attribution::reraise`] would have raised. A step
1240        /// that fails here fails before any kernel exists, so it is an
1241        /// error the builder returns rather than a panic out of a
1242        /// constructor.
1243        fn fold_steps(&mut self, order: &[usize]) -> Result<(), crate::KernelError> {
1244            let capture = crate::kernel::engines::EvalPanicCaptureGuard::arm();
1245            let outcome =
1246                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_order(order)));
1247            drop(capture);
1248            if let Err(payload) = outcome {
1249                let sites = std::sync::Arc::clone(&self.sites);
1250                let node = self.failing_node();
1251                return Err(crate::KernelError::ConstantFold {
1252                    reason: sites.describe(payload, node, &self.buffer, Some(&self.none)),
1253                });
1254            }
1255            Ok(())
1256        }
1257
1258        fn set_extern(
1259            &mut self,
1260            name: &str,
1261            value: crate::ast::Value,
1262        ) -> Result<usize, crate::kernel::WriteError> {
1263            let (slot, unset) = self.externs.set(name, value, &mut self.buffer)?;
1264            self.extern_written(slot, unset);
1265            Ok(slot)
1266        }
1267
1268        fn set_extern_at(
1269            &mut self,
1270            index: usize,
1271            value: crate::ast::Value,
1272        ) -> Result<usize, crate::kernel::WriteError> {
1273            let (slot, unset) = self.externs.set_at(index, value, &mut self.buffer)?;
1274            self.extern_written(slot, unset);
1275            Ok(slot)
1276        }
1277
1278        fn slot_value(&self, slot: usize, ty: crate::ast::PortType) -> crate::ast::Value {
1279            if self.none.get(slot).copied().unwrap_or(false) {
1280                return crate::ast::Value::None;
1281            }
1282            crate::compile::marshal::decode_output(&self.buffer, slot, ty)
1283        }
1284
1285        fn value_of(&self, name: &str) -> crate::ast::Value {
1286            let slot = self.output_map[name];
1287            let ty = self
1288                .output_types
1289                .get(name)
1290                .copied()
1291                .unwrap_or(crate::ast::PortType::U64);
1292            self.slot_value(slot, ty)
1293        }
1294    };
1295}
1296pub(crate) use shared_core_methods;
1297
1298/// The dirty-register plan of a compiled kernel: which steps each input
1299/// slot invalidates when it changes, and which steps each named output
1300/// needs. The evaluation loops consume only this, and provenance derives
1301/// it, so a narrower plan would need no change to the loops
1302/// (engines.md §3.1).
1303pub(crate) struct Invalidation {
1304    /// Per input slot (coordinates and externs alike), the steps that
1305    /// depend on it, transitively.
1306    pub(crate) input_dependents: Vec<Vec<usize>>,
1307    /// Per named output, the steps of its cone in evaluation order.
1308    pub(crate) cones: std::collections::HashMap<String, Vec<usize>>,
1309}
1310
1311impl Invalidation {
1312    /// The plan provenance gives: every step downstream of an input is
1313    /// invalidated by it, and every step upstream of an output is in
1314    /// its cone. `inputs` and `outputs` are each step's slots;
1315    /// `output_slots` names the outputs.
1316    pub(crate) fn from_provenance(
1317        input_dependents: Vec<Vec<usize>>,
1318        step_inputs: &[&[usize]],
1319        step_outputs: &[&[usize]],
1320        output_slots: &std::collections::HashMap<String, usize>,
1321        total_slots: usize,
1322    ) -> Self {
1323        let step_count = step_inputs.len();
1324        let mut slot_step: Vec<Option<usize>> = vec![None; total_slots];
1325        for (i, outs) in step_outputs.iter().enumerate() {
1326            for &s in outs.iter() {
1327                slot_step[s] = Some(i);
1328            }
1329        }
1330        let cones = output_slots
1331            .iter()
1332            .map(|(name, &slot)| {
1333                let mut wanted = vec![false; step_count];
1334                let mut stack: Vec<usize> = slot_step[slot].into_iter().collect();
1335                while let Some(i) = stack.pop() {
1336                    if wanted[i] {
1337                        continue;
1338                    }
1339                    wanted[i] = true;
1340                    stack.extend(step_inputs[i].iter().filter_map(|&s| slot_step[s]));
1341                }
1342                (
1343                    name.clone(),
1344                    (0..step_count).filter(|&i| wanted[i]).collect(),
1345                )
1346            })
1347            .collect();
1348        Self {
1349            input_dependents,
1350            cones,
1351        }
1352    }
1353}
1354
1355/// Where each compiled step came from, for the failure path only
1356/// (engines.md §3.4). A step's panic is caught at the step
1357/// boundary and re-raised enriched exactly as the interpreter enriches
1358/// a node's: the node's name, the outputs it feeds, the program's
1359/// diagnostic context, and its input values decoded from the buffer
1360/// where the slot types allow. `sites` is indexed by program node:
1361/// the closure and pure-native kernels have one step per node, and
1362/// the hybrid kernel names the failing member of a segment through
1363/// its tracker slot.
1364#[derive(Default)]
1365pub(crate) struct Attribution {
1366    pub(crate) sites: Vec<NodeSite>,
1367    /// The program's diagnostic context (`PolydatProgram::context`).
1368    pub(crate) context: String,
1369}
1370
1371/// One node's identity for the failure path.
1372pub(crate) struct NodeSite {
1373    pub(crate) name: String,
1374    /// The declared outputs the node feeds, sorted.
1375    pub(crate) outputs: Vec<String>,
1376    /// `(first slot, port type)` of every input port, in port order.
1377    pub(crate) inputs: Vec<(usize, crate::ast::PortType)>,
1378}
1379
1380impl Attribution {
1381    /// The inputs of `step` as diagnostic text, from the buffer, each
1382    /// copied out and printed as the interpreter prints the same value:
1383    /// `None` where the mask says so, and the port type alone where the
1384    /// slot cannot be decoded, so the report itself never fails.
1385    fn inputs_of(&self, step: usize, buffer: &[u64], none: Option<&[bool]>) -> Vec<String> {
1386        let Some(site) = self.sites.get(step) else {
1387            return Vec::new();
1388        };
1389        let _quiet = crate::kernel::engines::EvalPanicCaptureGuard::arm();
1390        site.inputs
1391            .iter()
1392            .map(|&(slot, ty)| {
1393                if none.is_some_and(|m| m.get(slot).copied().unwrap_or(false)) {
1394                    return "None".to_string();
1395                }
1396                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1397                    crate::kernel::engines::format_value_for_diag(&marshal::decode_output(
1398                        buffer, slot, ty,
1399                    ))
1400                }))
1401                .unwrap_or_else(|_| format!("{ty:?}"))
1402            })
1403            .collect()
1404    }
1405
1406    /// Re-raise a step's panic enriched as the interpreter enriches a
1407    /// node's (`kernel::engines::enrich_panic`). `step` beyond the
1408    /// sites (native code that failed before naming a step) reports an
1409    /// unknown node, as the interpreter does for an index it lacks.
1410    pub(crate) fn reraise(
1411        &self,
1412        payload: Box<dyn std::any::Any + Send>,
1413        step: usize,
1414        buffer: &[u64],
1415        none: Option<&[bool]>,
1416    ) -> ! {
1417        crate::kernel::engines::reraise_enriched(self.describe(payload, step, buffer, none))
1418    }
1419
1420    /// The same message [`Self::reraise`] raises, returned instead. The
1421    /// build-time constant fold uses it: a step that fails there fails
1422    /// before any kernel exists, so it is an error the builder returns
1423    /// and not a panic out of a constructor.
1424    pub(crate) fn describe(
1425        &self,
1426        payload: Box<dyn std::any::Any + Send>,
1427        step: usize,
1428        buffer: &[u64],
1429        none: Option<&[bool]>,
1430    ) -> String {
1431        let site = self.sites.get(step);
1432        let name = site
1433            .map(|s| s.name.clone())
1434            .unwrap_or_else(|| format!("<unknown node #{step}>"));
1435        let outputs: Vec<&str> = site
1436            .map(|s| s.outputs.iter().map(String::as_str).collect())
1437            .unwrap_or_default();
1438        let inputs = self.inputs_of(step, buffer, none);
1439        crate::kernel::engines::enrich_panic(payload, &name, &outputs, &self.context, &inputs)
1440    }
1441}