1use crate::ast::SlotShape;
32use crate::ast::{NodeMeta, PolydatNode, Port, PortType, Slot, Value};
33use crate::dsl::const_constraints::ConstConstraint;
34
35pub struct AssertType {
46 meta: NodeMeta,
47 expected: PortType,
48}
49
50impl AssertType {
51 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 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 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 (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 (Value::U64(_), PortType::F16) => true,
166 (Value::F64(_), PortType::F16) => true,
167 (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 (
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 (Value::Ext(_), PortType::Ext) => true,
188 (Value::Dataset(d), PortType::Forms | PortType::Fragment | PortType::AdmittedRows) => {
190 d.port_type() == typ
191 }
192 _ => false,
193 }
194}
195
196pub struct AssertValue {
210 meta: NodeMeta,
211 typ: PortType,
212 constraint: ConstConstraint,
213}
214
215impl AssertValue {
216 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 _ => "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 pub fn constraint(&self) -> &ConstConstraint {
242 &self.constraint
243 }
244
245 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 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 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 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 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
331pub 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
354pub 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
368pub 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
389pub fn assert_type_node(typ: PortType) -> Box<dyn PolydatNode> {
393 Box::new(AssertType::new(typ))
394}
395
396pub fn assert_value_node(typ: PortType, constraint: ConstConstraint) -> Box<dyn PolydatNode> {
398 Box::new(AssertValue::new(typ, constraint))
399}
400
401#[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}