pub struct PolydatKernel {
pub constants_folded: usize,
/* private fields */
}Expand description
A compiled Polydat Kernel: an Arc<PolydatProgram> plus one PolydatState.
§Invariants
- Scope coordinates are always populated. After construction
scope_coordsreflects this kernel’s place in the comprehension chain: leaf-first list ofsuper::ScopeCoordfrom the kernel’s own scope up through every enclosing comprehension. Root-scope kernels (no parent) start with their own coords (or empty).Self::materialize_wiring_from_outerre-computes the path so post-bind it includes the outer’s chain. Consumers (presentation layer, inspector, scope-aware diagnostics) callSelf::scope_coordinateswithout needing to walk the scope tree themselves. See [super::scope_coords].
Fields§
§constants_folded: usizeNumber of init-time constants folded during compilation.
Implementations§
Source§impl PolydatKernel
impl PolydatKernel
Sourcepub fn mark_inherited_outputs<I>(&mut self, names: I)where
I: IntoIterator<Item = String>,
pub fn mark_inherited_outputs<I>(&mut self, names: I)where
I: IntoIterator<Item = String>,
Mark a set of output names as inherited (cascade-only)
on the program. Must be called immediately after
construction, before the Arc<PolydatProgram> is shared.
Panics if the Arc has other references.
Sourcepub fn program(&self) -> &Arc<PolydatProgram> ⓘ
pub fn program(&self) -> &Arc<PolydatProgram> ⓘ
The shared immutable program.
Sourcepub fn commit_write_throughs(&mut self) -> Result<(), String>
pub fn commit_write_throughs(&mut self) -> Result<(), String>
SRD-67 Phase 5 — per-cycle commit. Pulls each write- through’s synthetic source output and stores its value through the corresponding cell-bound input slot for the declared export name. Reads of that name in the parent or in sibling kernels share the same cell and observe the write on the next read.
TYPE-STABLE (scope_model.md §“Type stability”): a cell keeps
ONE type for life. Each pending value passes the same typed
boundary the named-write path (set_wire) already enforces —
matching types pass, a catalog adapter heals (e.g. the lossless
U64→F64 widening), and an UNHEALABLE mismatch (narrowing, kind
change) is an Err at THIS write site naming the cell, its
declared type, the incoming type, and the producing binding —
never a silent type flip that a compile-time-typed bridge trips
over tiers later. Explicit narrowing is the author’s job via
trunc_u64(...) / round_u64(...).
No-op when the kernel carries no write-throughs.
Sourcepub fn set_cursor_schemas(&mut self, schemas: Vec<SourceSchema>)
pub fn set_cursor_schemas(&mut self, schemas: Vec<SourceSchema>)
Set source schemas on the program (called by the compiler).
Sourcepub fn set_ast(&mut self, ast: Arc<PolydatFile>)
pub fn set_ast(&mut self, ast: Arc<PolydatFile>)
Attach the parsed AST as live program metadata. Called by every DSL compile entry point immediately after the assembler produces the kernel, while the program Arc is still uniquely owned. The subscope synthesizer (SRD-13f §“Wire-reference classification”) queries this to integrate parent bindings’ matter into child scopes.
Sourcepub fn state(&mut self) -> &mut PolydatState
pub fn state(&mut self) -> &mut PolydatState
The per-fiber mutable evaluation state.
Sourcepub fn state_ref(&self) -> &PolydatState
pub fn state_ref(&self) -> &PolydatState
Read-only access to the kernel’s evaluation state. Used by callers (e.g. the scope-init pass) that need to inspect pulled values without consuming the kernel.
Sourcepub fn set_inputs(&mut self, coords: &[u64])
pub fn set_inputs(&mut self, coords: &[u64])
Convenience: set coordinate inputs on the owned state.
Sourcepub fn get_input(&self, name: &str) -> Option<Value>
pub fn get_input(&self, name: &str) -> Option<Value>
Read an input value by name. Cell-aware: cell-bound slots return the cell’s current value.
Sourcepub fn pull_by_index(&mut self, output_idx: usize) -> &Value
pub fn pull_by_index(&mut self, output_idx: usize) -> &Value
Pull a program output by its output-list index, skipping the
name→index resolution pull does. Pair with
PolydatProgram::output_index resolved ONCE (at bind time) so a
per-cycle reader pays no name hash on the hot path.
Sourcepub fn propagate_inputs_into(&self, child: &mut PolydatKernel)
pub fn propagate_inputs_into(&self, child: &mut PolydatKernel)
Copy self’s currently-set input-slot values into child’s
input slots by name.
Companion to the internal materialize_wiring_from_outer
pass that runs as part of build_subscope. That pass
walks the parent’s outputs; this method walks the parent’s
inputs — so cascade-extern’d names that the parent
inherited from its parent reach child too, rather than
stopping at the parent and silently leaving child’s
matching slot at its default.
Value::None inputs are skipped (no point overwriting a
child’s possibly-set default with absence). Inputs whose
name has no matching slot on child are skipped silently
— they’re not the child’s concern.
This is the kernel-chain operation that lets cascade-extern
propagate transitively across multi-level scope chains. Each
scope builder calls it after build_subscope finishes.
Sourcepub fn input_names(&self) -> Vec<String>
pub fn input_names(&self) -> Vec<String>
Return the names of the inputs.
Sourcepub fn output_names(&self) -> Vec<&str>
pub fn output_names(&self) -> Vec<&str>
Return the names of all available output variates.
Sourcepub fn get_constant(&self, name: &str) -> Option<&Value>
pub fn get_constant(&self, name: &str) -> Option<&Value>
Read the value of a named output that was folded to a constant.
Underlying primitive — prefer Self::lookup for
scope-aware name resolution. This method only succeeds for
constant-folded outputs whose buffer is populated; it
returns None for auto-passthrough outputs (where the
value lives in the input slot) and for cycle-dependent
outputs that haven’t been pulled.
Sourcepub fn find_l2f_violations(&self) -> Vec<String>
pub fn find_l2f_violations(&self) -> Vec<String>
Find every const output whose Plan B materialisation
left the buffer as Value::None. The L2.f sub-axiom in
composition_substrate.md describes this case: an
intermediate-layer const X := <expr> whose RHS yields
None falls through silently to the outer scope’s X via
the conditional-shadow semantics in none_semantics.md.
This method is the substrate’s “did silent fall-through
occur” query — strict-mode callers (per L2.f’s
strict-mode hardening note) use it to escalate the
silent fall-through to a hard error.
Returns the const-output names whose buffers are
Value::None after the scope-init pull. Empty Vec
means every const materialised to a defined value.
Polydat itself does not implement the strict-mode
policy — it provides this query and the caller decides
whether to surface a diagnostic.
Call only after materialize_wiring_from_outer has run
(i.e., after the kernel is fully constructed and
scope-init pulls have completed). Calling before
scope-init returns a misleading result.
Sourcepub fn lookup(&self, name: &str) -> Option<Value>
pub fn lookup(&self, name: &str) -> Option<Value>
Look up a name in this kernel’s scope.
The canonical scope-aware read documented by SRD-16 §“Visibility Rules: Shadowing”: own-scope folded outputs shadow inherited extern values, with auto-passthrough outputs falling through to the input slot transparently.
Resolution order:
- Folded output buffer (compile-time constants).
- Cell-aware input read (covers extern values bound via
materialize_wiring_from_outer, auto-passthrough outputs frominput ...: u64/extern, andshared-cell-backed slots — the cell is queried on every read so reads pick up writes from sibling kernels intrinsically).
Returns None when the name doesn’t resolve in either
tier or when the resolved value is Value::None (unset).
Returns Value (owned, not borrowed) because shared-cell
reads acquire a Mutex and clone out — there’s no
long-lived borrow into the cell. For non-shared slots
the clone is cheap (Value’s Clone is Arc-based for
vectors, primitive copy otherwise).
This is the single read API for scope-aware name lookup and is cell-aware by default — callers don’t need to know whether a name is shared or not.
Sourcepub fn cell_scope_snapshot(&self) -> PolydatKernel
pub fn cell_scope_snapshot(&self) -> PolydatKernel
Public form of Self::snapshot_with_cells: a fresh kernel
mirroring this one’s program and full shared-cell view (own
input-slot cells + transit cells, Arc-shared — the snapshot
reads/writes the SAME cells as self). For holding a scope’s
cell cascade past the point where the kernel itself is consumed
(e.g. an executor keeping a phase-activation scope view alive
for later build_subscope binds, after OpBuilder has taken
the activation kernel by value). Non-cell state is fresh — this
is a SCOPE view, not a value snapshot.
Sourcepub fn advance_broadcasts(&mut self)
pub fn advance_broadcasts(&mut self)
SRD-13f Push B.2 — advance this kernel’s broadcast
state: pull every output that has an attached
broadcast cell, forcing the eval cone to recompute
against current inputs and writing the fresh value
through the cell. Descendant kernels with input slots
cell-attached to these outputs then observe the
current value on their next read_input without any
per-fiber-write coordination.
Intended to run once per cycle on each per-fiber outer kernel whose outputs are visible to inner scopes. The alternative — validity-bit + auto-pull-on-stale-read — would put the trigger fully inside the Polydat engine (so inner reads transparently fetch fresh values), but requires the engine to track upstream dependencies across the cell boundary. This eager-broadcast form is simpler and lives entirely within the kernel’s own surface: callers ask the kernel to advance its broadcasts; the kernel does the pulls; cells receive the values.
Every shared cell visible at this kernel’s scope —
own input slots’ attached cells unioned with the
transit cells inherited from ancestors. The typed
ScopeKernel::shared_cells_in_scope delegates here.
Used by materialize_wiring_from_outer to compute the parent’s
full visible cell set and propagate it to the child.
Public for the typed surface; semantics are the same
as the typed accessor.
Sourcepub fn for_iteration(
canonical: &Arc<PolydatKernel>,
parent: &Arc<PolydatKernel>,
bindings: &[(String, Value)],
) -> Arc<PolydatKernel> ⓘ
pub fn for_iteration( canonical: &Arc<PolydatKernel>, parent: &Arc<PolydatKernel>, bindings: &[(String, Value)], ) -> Arc<PolydatKernel> ⓘ
Construct a per-iteration kernel: clone canonical’s
program, bind it to parent’s scope, and pre-load every
(var, value) binding into the corresponding input slot.
§Cache-and-rehydrate pattern
for_iteration is the public entry point for the
cache-and-rehydrate pattern a host builds on:
compile a scope’s program once, then hydrate many
per-instance kernels from it — one per iteration tuple,
per fiber, per scenario-tree visit. The program is
immutable substance (the Arc<PolydatProgram>); each
hydrated kernel carries its own state (the input slot
values for this iteration).
The pattern’s three load-bearing properties:
- Compile cost amortizes. Polydat source → typed program
is paid once per canonical scope, not per iteration
or per fiber. The compiled
Arc<PolydatProgram>is shared via clone (cheap — refcount bump). - Each hydrated kernel is independent. Per-fiber
state means no synchronization between fibers running
the same iteration in parallel. Each
for_iterationcall produces a fresh kernel with its own input slots, output cells, and write-through bindings. - Parent-chain wiring is uniform. Every hydrated
kernel runs through the parent’s
materialize_subscope(and downstreammaterialize_wiring_from_outer) so cell propagation, shared-cell attach, and the SRD-13f read-invariant are byte-identical to any other parent → child path.
§When to use this
- Per-iteration kernel construction in scope
walkers and pre-map walkers. The runtime dispatcher
uses it before descending into a comprehension
iteration’s children; the pre-map walker uses it so
nested
for_eachclauses with outer-iter-var interpolation (vec_{profile}) resolve at pre-map time. - Cross-cutover migration paths. The walker rewrite
in PR 9c-1b (see
polydat/docs/design/comprehension_cutover_contact_surfaces.md) uses this method to hydrate per-iteration kernels from the canonical scope kernel thatbuild_for_each_scope_kernelproduced.
§Why one entry point
Owning the recipe here ensures both consumers (runtime
dispatcher + pre-map walker) produce identical kernels
for identical inputs. Pre-for_iteration, each site
reimplemented the three-step
from_program → materialize_wiring_from_outer →
set_input dance and could — and did — drift.
§See also
Self::from_program(internal) — the build-fresh-state primitivefor_iterationcomposes with parent-chain wiring.Self::propagate_inputs_into— the kernel-chain operation that extends cascade-extern values into a subkernel (called once afterfor_iterationfrom each scope walker so multi-level cascades reach the grandchild).
Sourcepub fn scope_coordinates(&self) -> &[ScopeCoord]
pub fn scope_coordinates(&self) -> &[ScopeCoord]
The leaf-first scope coordinate path — see the
[super::scope_coords] module doc for the formal
definition. Always reflects the current binding state:
after Self::materialize_wiring_from_outer the path includes the
outer kernel’s full chain; for root scopes the path is
just this kernel’s own coords (or empty).
Sourcepub fn scope_values(&self) -> Vec<(String, Value)>
pub fn scope_values(&self) -> Vec<(String, Value)>
Extract the scope values that were set via materialize_wiring_from_outer.
Returns [(name, value)] for inputs that are not at their
default. Used by OpBuilder to inject the same values into
every fiber’s state, including per-op-template kernels
whose input layout differs from this kernel’s. The name-
keyed shape is the cross-kernel-safe contract: an index
captured against this kernel’s layout is meaningless when
applied to a kernel synthesised from a different source
(different extern declaration order, lazy-cascade omissions,
etc.). Naming the binding makes the cross-scope write
unambiguous — a missing name on the target program is a
no-op rather than a silently mis-routed write.
Sourcepub fn into_program(self) -> Arc<PolydatProgram> ⓘ
pub fn into_program(self) -> Arc<PolydatProgram> ⓘ
Extract the program for concurrent use.
Source§impl PolydatKernel
impl PolydatKernel
Sourcepub fn build_subscope(
&self,
matter: PolydatMatter<'_>,
) -> Result<PolydatKernel, ContractViolation>
pub fn build_subscope( &self, matter: PolydatMatter<'_>, ) -> Result<PolydatKernel, ContractViolation>
THE subscope-construction path. Per the kernel-construction
invariant, this is the ONE method through which a parent
kernel produces a child. compile_polydat produces root
kernels; everything else is a subscope and routes here.
Cell propagation, scope-coordinate plumbing, and Rule 2
write-throughs flow from self (the parent) into the
returned child. Returns the child kernel plus any
write-through bindings finalize produced (empty for the
program-matter form, populated for the source-matter
form when a result-LHS collides with a parent shared
cell).
Trait Implementations§
Source§impl Construction for PolydatKernel
impl Construction for PolydatKernel
Source§type Error = ContractViolation
type Error = ContractViolation
Source§impl Dataflow for PolydatKernel
impl Dataflow for PolydatKernel
Source§fn set_wire_idx(&mut self, idx: usize, value: Value) -> Result<(), WriteError>
fn set_wire_idx(&mut self, idx: usize, value: Value) -> Result<(), WriteError>
idx with typed enforcement. Read moreSource§fn get_wire_idx(&self, idx: usize) -> Value
fn get_wire_idx(&self, idx: usize) -> Value
idx. Out-of-range
behaviour returns the slot’s default Value::None (the
read path is non-fallible; type information is structural
and reads cannot fail typewise).Source§impl Debug for PolydatKernel
impl Debug for PolydatKernel
Source§impl Metadata for PolydatKernel
impl Metadata for PolydatKernel
Source§fn find_input(&self, name: &str) -> Option<usize>
fn find_input(&self, name: &str) -> Option<usize>
Source§fn input_names(&self) -> Vec<String>
fn input_names(&self) -> Vec<String>
Source§fn output_names(&self) -> Vec<String>
fn output_names(&self) -> Vec<String>
Source§fn coord_count(&self) -> usize
fn coord_count(&self) -> usize
Source§fn input_port_type(&self, name: &str) -> Option<PortType>
fn input_port_type(&self, name: &str) -> Option<PortType>
Source§fn input_port_type_by_idx(&self, idx: usize) -> Option<PortType>
fn input_port_type_by_idx(&self, idx: usize) -> Option<PortType>
input_port_type] — used by
the typed-write fast path so Dataflow::set_wire_idx
can look up the slot’s expected type without first
reverse-resolving an index to a name.