dfir_lang/graph/ops/
assert.rs

1use syn::parse_quote_spanned;
2
3use super::{
4    OperatorCategory, OperatorConstraints, WriteContextArgs, RANGE_0, RANGE_1,
5};
6
7/// > 1 input stream, 1 optional output stream
8/// > Arguments: a predicate function that will be applied to each item in the stream
9///
10/// If the predicate returns false for any input item then the operator will panic at runtime.
11///
12/// ```dfir
13/// source_iter([1, 2, 3])
14///     -> assert(|x| *x > 0)
15///     -> assert_eq([1, 2, 3]);
16/// ```
17pub const ASSERT: OperatorConstraints = OperatorConstraints {
18    name: "assert",
19    categories: &[OperatorCategory::Control],
20    hard_range_inn: RANGE_1,
21    soft_range_inn: RANGE_1,
22    hard_range_out: &(0..=1),
23    soft_range_out: &(0..=1),
24    num_args: 1,
25    persistence_args: RANGE_0,
26    type_args: RANGE_0,
27    is_external_input: false,
28    has_singleton_output: false,
29    flo_type: None,
30    ports_inn: None,
31    ports_out: None,
32    input_delaytype_fn: |_| None,
33    write_fn: |wc @ &WriteContextArgs {
34                   op_span, arguments, ..
35               },
36               diagnostics| {
37        let arg = &arguments[0];
38
39        let arguments = &parse_quote_spanned! {op_span=>
40            |x| {
41                // This is to help constrain the types so that type inference works nicely.
42                fn __constrain_types<T>(f: impl Fn(&T) -> bool, x: &T) -> bool {
43                    (f)(x)
44                }
45                assert!(__constrain_types(#arg, x));
46            }
47        };
48
49        let wc = WriteContextArgs {
50            arguments,
51            ..wc.clone()
52        };
53
54        (super::inspect::INSPECT.write_fn)(&wc, diagnostics)
55    },
56};