Skip to main content

PolydatKernel

Struct PolydatKernel 

Source
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_coords reflects this kernel’s place in the comprehension chain: leaf-first list of super::ScopeCoord from 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_outer re-computes the path so post-bind it includes the outer’s chain. Consumers (presentation layer, inspector, scope-aware diagnostics) call Self::scope_coordinates without needing to walk the scope tree themselves. See [super::scope_coords].

Fields§

§constants_folded: usize

Number of init-time constants folded during compilation.

Implementations§

Source§

impl PolydatKernel

Source

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.

Source

pub fn program(&self) -> &Arc<PolydatProgram>

The shared immutable program.

Source

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.

Source

pub fn set_cursor_schemas(&mut self, schemas: Vec<SourceSchema>)

Set source schemas on the program (called by the compiler).

Source

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.

Source

pub fn state(&mut self) -> &mut PolydatState

The per-fiber mutable evaluation state.

Source

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.

Source

pub fn set_inputs(&mut self, coords: &[u64])

Convenience: set coordinate inputs on the owned state.

Source

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.

Source

pub fn pull(&mut self, output_name: &str) -> &Value

Convenience: pull from the owned state.

Source

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.

Source

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.

Source

pub fn input_names(&self) -> Vec<String>

Return the names of the inputs.

Source

pub fn output_names(&self) -> Vec<&str>

Return the names of all available output variates.

Source

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.

Source

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.

Source

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:

  1. Folded output buffer (compile-time constants).
  2. Cell-aware input read (covers extern values bound via materialize_wiring_from_outer, auto-passthrough outputs from input ...: u64 / extern, and shared-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.

Source

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.

Source

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.

Source

pub fn shared_cells_in_scope(&self) -> Vec<SharedCellEntry>

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.

Source

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:

  1. 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).
  2. Each hydrated kernel is independent. Per-fiber state means no synchronization between fibers running the same iteration in parallel. Each for_iteration call produces a fresh kernel with its own input slots, output cells, and write-through bindings.
  3. Parent-chain wiring is uniform. Every hydrated kernel runs through the parent’s materialize_subscope (and downstream materialize_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_each clauses 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 that build_for_each_scope_kernel produced.
§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_programmaterialize_wiring_from_outerset_input dance and could — and did — drift.

§See also
  • Self::from_program (internal) — the build-fresh-state primitive for_iteration composes with parent-chain wiring.
  • Self::propagate_inputs_into — the kernel-chain operation that extends cascade-extern values into a subkernel (called once after for_iteration from each scope walker so multi-level cascades reach the grandchild).
Source

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).

Source

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.

Source

pub fn into_program(self) -> Arc<PolydatProgram>

Extract the program for concurrent use.

Source§

impl PolydatKernel

Source

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

Source§

type Error = ContractViolation

Construction error type.
Source§

fn root(matter: PolydatMatter<'_>) -> Result<Self, Self::Error>

Path 1: build a root context from Polydat matter. No parent. Subscope-only fields on the matter (result-binding rewrites, inherited-output cascade, finalize-time contract checks) are not applicable here and are ignored.
Source§

fn subscope(&self, matter: PolydatMatter<'_>) -> Result<Self, Self::Error>

Path 2: build a subscope context against self from Polydat matter. The parent supervises: cell cascade, Rule 2 rewrites, scope-coordinate threading, init-binding contract checks all flow from self into the child.
Source§

impl Dataflow for PolydatKernel

Source§

fn set_wire_idx(&mut self, idx: usize, value: Value) -> Result<(), WriteError>

Write a value to wire idx with typed enforcement. Read more
Source§

fn get_wire_idx(&self, idx: usize) -> Value

Read the current value of wire 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§

fn set_wire<W: WireKey>( &mut self, key: W, value: Value, ) -> Result<(), WriteError>

Write a value to a wire identified by key (index or name). Returns Ok(()) on success, Err(WriteError) on failure (unknown wire or type mismatch the boundary cannot heal).
Source§

fn get_wire<W: WireKey>(&self, key: W) -> Option<Value>

Read the current value of a wire identified by key (index or name). Returns None when the wire is not found.
Source§

impl Debug for PolydatKernel

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Metadata for PolydatKernel

Source§

fn find_input(&self, name: &str) -> Option<usize>

Resolve an input name to its wire index, if present.
Source§

fn input_names(&self) -> Vec<String>

All declared input wire names, in declaration order.
Source§

fn output_names(&self) -> Vec<String>

All declared output wire names, in declaration order.
Source§

fn coord_count(&self) -> usize

Number of coordinate inputs (the leading prefix of the input slot vector — written via the cycle dispatcher).
Source§

fn input_port_type(&self, name: &str) -> Option<PortType>

Declared port type of an input wire, if known.
Source§

fn input_port_type_by_idx(&self, idx: usize) -> Option<PortType>

Declared port type of an input wire by index. The indexed counterpart of [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.
Source§

fn output_port_type(&self, name: &str) -> Option<PortType>

Declared port type of an output wire, if present. Symmetric counterpart to [input_port_type]. Used by the binder verification path (crate::binder::verify_against_kernel) to look up wire types for type-checking adapter binding shapes.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.