Skip to main content

polydat_core/library/
assertions.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Type and value assertion nodes.
5//!
6//! Polydat's runtime contract: node `eval` trusts its inputs. Bad input
7//! panics, by design, because the hot path stays branch-free. The
8//! "guarded" version of a node that would otherwise panic is built
9//! as an *assembly* of two functions — the original node, and an
10//! assertion node spliced in front of one of its inputs. The assertion runs the
11//! check; the downstream node still trusts its inputs.
12//!
13//! Two families:
14//!
15//! * **Type assertions** — one per supported [`PortType`]. They
16//!   confirm the runtime [`Value`] variant matches the static
17//!   port type and pass it through. The compiler inserts none:
18//!   wires are statically typed, and a resolved wire's type is the
19//!   sink port's type, so a runtime type check has nothing to catch.
20//!
21//! * **Value assertions** — one per `PortType`, parameterised by
22//!   a [`ConstConstraint`]. Pass the value through if the
23//!   constraint holds, otherwise panic with a structured message.
24//!   The same vocabulary the const-constraint metadata uses on
25//!   `ParamSpec` is reused on `Port` and on these nodes.
26//!
27//! The compiler inserts value assertions under `pragma strict_values`
28//! (graph_compiler.md §2). Neither family is callable from Polydat
29//! source (library_catalog.md, the hand-written-impl carve-outs).
30
31use crate::ast::SlotShape;
32use crate::ast::{NodeMeta, PolydatNode, Port, PortType, Slot, Value};
33use crate::dsl::const_constraints::ConstConstraint;
34
35// =========================================================================
36// Type assertions: one per PortType
37// =========================================================================
38
39/// Pass-through guard that confirms the runtime value variant
40/// matches a declared `PortType`. Panics on mismatch.
41///
42/// Constructed with [`assert_type_node`]. The compiler inserts none,
43/// under `strict_types` or otherwise: a resolved wire's type is the
44/// sink port's type (graph_compiler.md §2).
45pub struct AssertType {
46    meta: NodeMeta,
47    expected: PortType,
48}
49
50impl AssertType {
51    /// A type assertion for `typ`, named `assert_<type>`.
52    pub fn new(typ: PortType) -> Self {
53        let name = match typ {
54            PortType::U64 => "assert_u64",
55            PortType::F64 => "assert_f64",
56            PortType::Bool => "assert_bool",
57            PortType::Str => "assert_str",
58            PortType::Bytes => "assert_bytes",
59            PortType::Json => "assert_json",
60            PortType::U32 => "assert_u32",
61            PortType::I32 => "assert_i32",
62            PortType::I64 => "assert_i64",
63            PortType::F32 => "assert_f32",
64            PortType::U8 => "assert_u8",
65            PortType::I8 => "assert_i8",
66            PortType::U16 => "assert_u16",
67            PortType::I16 => "assert_i16",
68            PortType::F16 => "assert_f16",
69            PortType::U128 => "assert_u128",
70            PortType::I128 => "assert_i128",
71            PortType::Reg128 => "assert_reg128",
72            PortType::RegI8x16 => "assert_reg_i8x16",
73            PortType::RegI16x8 => "assert_reg_i16x8",
74            PortType::RegI32x4 => "assert_reg_i32x4",
75            PortType::RegI64x2 => "assert_reg_i64x2",
76            PortType::RegF16x8 => "assert_reg_f16x8",
77            PortType::RegF32x4 => "assert_reg_f32x4",
78            PortType::RegF64x2 => "assert_reg_f64x2",
79            PortType::Ext => "assert_ext",
80            PortType::Handle => "assert_handle",
81            PortType::VecF32 => "assert_vec_f32",
82            PortType::VecI32 => "assert_vec_i32",
83            PortType::VecF64 => "assert_vec_f64",
84            PortType::VecI64 => "assert_vec_i64",
85            PortType::VecF16 => "assert_vec_f16",
86            PortType::VecI16 => "assert_vec_i16",
87            PortType::VecI8 => "assert_vec_i8",
88            PortType::Forms => "assert_forms",
89            PortType::Fragment => "assert_fragment",
90            PortType::AdmittedRows => "assert_admitted_rows",
91            PortType::Dyn => "assert_dyn",
92        };
93        Self {
94            meta: NodeMeta {
95                name: name.into(),
96                outs: vec![Port::new("output", typ)],
97                ins: vec![Slot::Wire(Port::new("input", typ))],
98            },
99            expected: typ,
100        }
101    }
102
103    /// Returns the `PortType` this node asserts against.
104    pub fn expected(&self) -> PortType {
105        self.expected
106    }
107}
108
109impl PolydatNode for AssertType {
110    fn meta(&self) -> &NodeMeta {
111        &self.meta
112    }
113
114    fn eval(&self, inputs: &[Value], outputs: &mut [Value]) {
115        let v = &inputs[0];
116        if !value_matches(v, self.expected) {
117            panic!(
118                "{}: expected runtime value of type {:?}, got {:?}",
119                self.meta.name, self.expected, v
120            );
121        }
122        outputs[0] = v.clone();
123    }
124
125    /// The compiled form. In a slot buffer a wire's color is its type,
126    /// so the variant check the interpreter makes has nothing to
127    /// observe there; the compiled step is the copy `identity` makes:
128    /// an immediate copied, a `Ref2` value copied into this step's own
129    /// scratch, since a pair is never forwarded (axiom S3).
130    fn compiled_u64(&self) -> Option<crate::ast::CompiledU64Op> {
131        if self.expected.slot_color() == crate::ast::SlotColor::Ref2 {
132            return None;
133        }
134        Some(Box::new(|inputs: &[u64], outputs: &mut [u64]| {
135            outputs.copy_from_slice(inputs)
136        }))
137    }
138
139    fn compiled_slot(
140        &self,
141        _wire_types: &[PortType],
142        _engine: crate::compile::select::Engine,
143    ) -> Option<crate::ast::CompiledSlotKit> {
144        crate::compile::assembly::ref_copy_kit(self.expected)
145    }
146}
147
148fn value_matches(v: &Value, typ: PortType) -> bool {
149    match (v, typ) {
150        (Value::U64(_), PortType::U64) => true,
151        (Value::F64(_), PortType::F64) => true,
152        (Value::Bool(_), PortType::Bool) => true,
153        (Value::Str(_), PortType::Str) => true,
154        (Value::Bytes(_), PortType::Bytes) => true,
155        (Value::Json(_), PortType::Json) => true,
156        // Narrow-int variants ride in the wider variant per the
157        // PortType doc on `node.rs` — accept the natural carrier.
158        (Value::U64(_), PortType::U32) => true,
159        (Value::U64(_), PortType::I32) => true,
160        (Value::U64(_), PortType::I64) => true,
161        (Value::F64(_), PortType::F32) => true,
162        (Value::U64(_), PortType::U8 | PortType::U16) => true,
163        // F16 rides its bit pattern in U64 (same stuffing as F32
164        // node outputs); host-written F64 also satisfies F16.
165        (Value::U64(_), PortType::F16) => true,
166        (Value::F64(_), PortType::F16) => true,
167        // Honest signed carrier serves all signed widths; the
168        // bit-stuffed U64 forms of the narrow signed projections are
169        // accepted too.
170        (Value::I64(_), PortType::I64 | PortType::I32 | PortType::I8 | PortType::I16) => true,
171        (Value::U64(_), PortType::I8 | PortType::I16) => true,
172        (Value::U128(_), PortType::U128) => true,
173        (Value::I128(_), PortType::I128) => true,
174        // Register views are free bitcasts of one another.
175        (
176            Value::Reg128(_, _),
177            PortType::Reg128
178            | PortType::RegI8x16
179            | PortType::RegI16x8
180            | PortType::RegI32x4
181            | PortType::RegI64x2
182            | PortType::RegF16x8
183            | PortType::RegF32x4
184            | PortType::RegF64x2,
185        ) => true,
186        // Ext is opaque; we accept any concrete reflection.
187        (Value::Ext(_), PortType::Ext) => true,
188        // A dataset value states its own port type.
189        (Value::Dataset(d), PortType::Forms | PortType::Fragment | PortType::AdmittedRows) => {
190            d.port_type() == typ
191        }
192        _ => false,
193    }
194}
195
196// =========================================================================
197// Value assertions: type + constraint pair
198// =========================================================================
199
200/// Runtime value-constraint guard. Holds a [`ConstConstraint`]
201/// the value must satisfy each cycle. Panics with a structured
202/// message on violation; passes the value through otherwise.
203///
204/// Constructed with [`assert_value_node`] from the compiler when
205/// the source can't statically be proven to deliver a value
206/// satisfying the sink's constraint. Reuses the same
207/// `ConstConstraint` vocabulary the const-validator uses, so the
208/// two layers speak one language.
209pub struct AssertValue {
210    meta: NodeMeta,
211    typ: PortType,
212    constraint: ConstConstraint,
213}
214
215impl AssertValue {
216    /// A value assertion for `typ` under `constraint`, named by the pair.
217    pub fn new(typ: PortType, constraint: ConstConstraint) -> Self {
218        let name = match (&typ, &constraint) {
219            (PortType::U64, ConstConstraint::NonZeroU64) => "assert_u64_nonzero",
220            (PortType::U64, ConstConstraint::RangeU64 { .. }) => "assert_u64_range",
221            (PortType::U64, ConstConstraint::AllowedU64(_)) => "assert_u64_allowed",
222            (PortType::F64, ConstConstraint::RangeF64 { .. }) => "assert_f64_range",
223            (PortType::Str, ConstConstraint::NonEmptyStr) => "assert_str_non_empty",
224            (PortType::Str, ConstConstraint::StrParser(_)) => "assert_str_parses",
225            // Catch-all for combinations we haven't dedicated a
226            // distinct DSL name to yet.
227            _ => "assert_value",
228        };
229        Self {
230            meta: NodeMeta {
231                name: name.into(),
232                outs: vec![Port::new("output", typ)],
233                ins: vec![Slot::Wire(Port::new("input", typ))],
234            },
235            typ,
236            constraint,
237        }
238    }
239
240    /// The constraint asserted.
241    pub fn constraint(&self) -> &ConstConstraint {
242        &self.constraint
243    }
244
245    /// The type asserted.
246    pub fn port_type(&self) -> PortType {
247        self.typ
248    }
249}
250
251impl PolydatNode for AssertValue {
252    fn meta(&self) -> &NodeMeta {
253        &self.meta
254    }
255
256    fn eval(&self, inputs: &[Value], outputs: &mut [Value]) {
257        // Re-route the constraint check through `ConstConstraint::check`
258        // by lifting the value into a `ConstArg` shaped tuple. Avoids
259        // duplicating the per-variant logic between assembly and
260        // runtime.
261        match check_value(&self.constraint, &inputs[0], "value") {
262            Some(Ok(())) => {}
263            Some(Err(msg)) => panic!("{}: {msg}", self.meta.name),
264            None => panic!(
265                "{}: unsupported runtime value variant {:?}",
266                self.meta.name, inputs[0]
267            ),
268        }
269        outputs[0] = inputs[0].clone();
270    }
271
272    /// The compiled form: the same constraint checked against the slot,
273    /// decoded by the asserted type, with the same message on failure.
274    /// A carrier reads as its integer, a float from its bits; the
275    /// other shapes have no u64 form.
276    fn compiled_u64(&self) -> Option<crate::ast::CompiledU64Op> {
277        use crate::dsl::factory::ConstArg;
278        let lift: fn(u64) -> ConstArg = match self.typ {
279            PortType::U64 | PortType::U32 | PortType::U16 | PortType::U8 => ConstArg::Int,
280            PortType::F64 => |slot| ConstArg::Float(f64::from_bits(slot)),
281            _ => return None,
282        };
283        let name = self.meta.name.clone();
284        let constraint = self.constraint;
285        Some(Box::new(move |inputs: &[u64], outputs: &mut [u64]| {
286            if let Err(msg) = constraint.check(&lift(inputs[0]), "value") {
287                panic!("{name}: {msg}");
288            }
289            outputs[0] = inputs[0];
290        }))
291    }
292
293    /// A string reads through its pair, is checked, and is copied into
294    /// this step's own scratch (axiom S3).
295    fn compiled_slot(
296        &self,
297        _wire_types: &[PortType],
298        _engine: crate::compile::select::Engine,
299    ) -> Option<crate::ast::CompiledSlotKit> {
300        use crate::dsl::factory::ConstArg;
301        if self.typ != PortType::Str {
302            return None;
303        }
304        let name = self.meta.name.clone();
305        let constraint = self.constraint;
306        let copy = crate::compile::assembly::ref_copy_kit(PortType::Str)?;
307        Some(crate::ast::CompiledSlotKit {
308            scratch: copy.scratch,
309            op: Box::new(
310                move |inputs: &[u64],
311                      outputs: &mut [u64],
312                      scratch: &mut [crate::ast::ScratchBuf]| {
313                    // SAFETY: the pair was published by the producing
314                    // step into storage alive until it reruns (S3, S4).
315                    let text = unsafe {
316                        std::str::from_utf8_unchecked(std::slice::from_raw_parts(
317                            inputs[0] as usize as *const u8,
318                            inputs[1] as usize,
319                        ))
320                    };
321                    if let Err(msg) = constraint.check(&ConstArg::Str(text.to_string()), "value") {
322                        panic!("{name}: {msg}");
323                    }
324                    (copy.op)(inputs, outputs, scratch);
325                },
326            ),
327        })
328    }
329}
330
331// =========================================================================
332// Helpers used by the compiler when auto-wiring assertions
333// =========================================================================
334
335/// Check `value` against `constraint`, naming the checked value
336/// `name` in the message. `None` when the value's variant is one the
337/// constraint vocabulary has no reading of (anything but `U64`, `F64`
338/// and `Str`).
339pub fn check_value(
340    constraint: &ConstConstraint,
341    value: &Value,
342    name: &str,
343) -> Option<Result<(), String>> {
344    use crate::dsl::factory::ConstArg;
345    let arg = match value {
346        Value::U64(v) => ConstArg::Int(*v),
347        Value::F64(v) => ConstArg::Float(*v),
348        Value::Str(s) => ConstArg::Str(s.to_string()),
349        _ => return None,
350    };
351    Some(constraint.check(&arg, name))
352}
353
354/// The condition `constraint` states, in words, for diagnostics.
355pub fn describe_constraint(constraint: &ConstConstraint) -> String {
356    match constraint {
357        ConstConstraint::RangeU64 { min, max } => format!("in [{min}, {max}]"),
358        ConstConstraint::RangeF64 { min, max } => format!("in [{min}, {max}]"),
359        ConstConstraint::AllowedU64(allowed) => format!("one of {allowed:?}"),
360        ConstConstraint::NonZeroU64 => "non-zero".into(),
361        ConstConstraint::NonEmptyStr => "non-empty".into(),
362        ConstConstraint::StrParser(_) => "accepted by the port's parser".into(),
363        ConstConstraint::PositiveFiniteF64 => "positive and finite".into(),
364        ConstConstraint::FiniteF64 => "finite".into(),
365    }
366}
367
368/// Whether two constraints state the same condition. A parser
369/// constraint equals another only when both name the same function.
370pub fn same_constraint(a: &ConstConstraint, b: &ConstConstraint) -> bool {
371    use ConstConstraint as C;
372    match (a, b) {
373        (C::RangeU64 { min: a0, max: a1 }, C::RangeU64 { min: b0, max: b1 }) => {
374            a0 == b0 && a1 == b1
375        }
376        (C::RangeF64 { min: a0, max: a1 }, C::RangeF64 { min: b0, max: b1 }) => {
377            a0.to_bits() == b0.to_bits() && a1.to_bits() == b1.to_bits()
378        }
379        (C::AllowedU64(a), C::AllowedU64(b)) => a == b,
380        (C::StrParser(a), C::StrParser(b)) => std::ptr::fn_addr_eq(*a, *b),
381        (C::NonZeroU64, C::NonZeroU64)
382        | (C::NonEmptyStr, C::NonEmptyStr)
383        | (C::PositiveFiniteF64, C::PositiveFiniteF64)
384        | (C::FiniteF64, C::FiniteF64) => true,
385        _ => false,
386    }
387}
388
389/// Construct the right type assertion node for a given `PortType`.
390/// The compiler inserts none: a resolved wire's type is the sink
391/// port's type (graph_compiler.md §2).
392pub fn assert_type_node(typ: PortType) -> Box<dyn PolydatNode> {
393    Box::new(AssertType::new(typ))
394}
395
396/// Construct a value assertion node for the given (type, constraint) pair.
397pub fn assert_value_node(typ: PortType, constraint: ConstConstraint) -> Box<dyn PolydatNode> {
398    Box::new(AssertValue::new(typ, constraint))
399}
400
401// =========================================================================
402// Tests
403// =========================================================================
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    fn assert_u64_passes_u64_through() {
411        let node = AssertType::new(PortType::U64);
412        let mut out = [Value::None];
413        node.eval(&[Value::U64(42)], &mut out);
414        assert_eq!(out[0].as_u64(), 42);
415    }
416
417    #[test]
418    #[should_panic(expected = "expected runtime value of type U64")]
419    fn assert_u64_panics_on_string() {
420        let node = AssertType::new(PortType::U64);
421        let mut out = [Value::None];
422        node.eval(&[Value::Str("not a number".into())], &mut out);
423    }
424
425    #[test]
426    fn assert_value_nonzero_passes_nonzero() {
427        let node = AssertValue::new(PortType::U64, ConstConstraint::NonZeroU64);
428        let mut out = [Value::None];
429        node.eval(&[Value::U64(7)], &mut out);
430        assert_eq!(out[0].as_u64(), 7);
431    }
432
433    #[test]
434    #[should_panic(expected = "must be non-zero")]
435    fn assert_value_nonzero_panics_on_zero() {
436        let node = AssertValue::new(PortType::U64, ConstConstraint::NonZeroU64);
437        let mut out = [Value::None];
438        node.eval(&[Value::U64(0)], &mut out);
439    }
440
441    #[test]
442    fn assert_value_range_f64_passes_unit_interval() {
443        let node = AssertValue::new(
444            PortType::F64,
445            ConstConstraint::RangeF64 { min: 0.0, max: 1.0 },
446        );
447        let mut out = [Value::None];
448        node.eval(&[Value::F64(0.5)], &mut out);
449        assert_eq!(out[0].as_f64(), 0.5);
450    }
451
452    #[test]
453    #[should_panic(expected = "must be in [0, 1]")]
454    fn assert_value_range_f64_panics_on_out_of_range() {
455        let node = AssertValue::new(
456            PortType::F64,
457            ConstConstraint::RangeF64 { min: 0.0, max: 1.0 },
458        );
459        let mut out = [Value::None];
460        node.eval(&[Value::F64(1.5)], &mut out);
461    }
462}