tinc_build/codegen/cel/functions/
bool.rs

1use super::Function;
2use crate::codegen::cel::compiler::{CompileError, CompiledExpr, CompilerCtx};
3
4#[derive(Debug, Clone, Default)]
5pub(crate) struct Bool;
6
7impl Function for Bool {
8    fn name(&self) -> &'static str {
9        "bool"
10    }
11
12    fn syntax(&self) -> &'static str {
13        "<this>.bool()"
14    }
15
16    fn compile(&self, mut ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
17        let Some(this) = ctx.this.take() else {
18            return Err(CompileError::syntax("missing this", self));
19        };
20
21        if !ctx.args.is_empty() {
22            return Err(CompileError::syntax("takes no arguments", self));
23        }
24
25        Ok(this.into_bool(&ctx))
26    }
27}
28
29#[cfg(test)]
30#[cfg(feature = "prost")]
31#[cfg_attr(coverage_nightly, coverage(off))]
32mod tests {
33    use tinc_cel::CelValue;
34
35    use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
36    use crate::codegen::cel::functions::{Bool, Function};
37    use crate::types::ProtoTypeRegistry;
38
39    #[test]
40    fn test_bool_syntax() {
41        let registry = ProtoTypeRegistry::new(crate::Mode::Prost, crate::extern_paths::ExternPaths::new(crate::Mode::Prost));
42        let compiler = Compiler::new(&registry);
43        insta::assert_debug_snapshot!(Bool.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
44        Err(
45            InvalidSyntax {
46                message: "missing this",
47                syntax: "<this>.bool()",
48            },
49        )
50        "#);
51
52        insta::assert_debug_snapshot!(Bool.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::List(Default::default()))), &[])), @r"
53        Ok(
54            Constant(
55                ConstantCompiledExpr {
56                    value: Bool(
57                        false,
58                    ),
59                },
60            ),
61        )
62        ");
63
64        insta::assert_debug_snapshot!(Bool.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::List(Default::default()))), &[
65            cel_parser::parse("1 + 1").unwrap(), // not an ident
66        ])), @r#"
67        Err(
68            InvalidSyntax {
69                message: "takes no arguments",
70                syntax: "<this>.bool()",
71            },
72        )
73        "#);
74    }
75}