Skip to main content

tonneau_build/codegen/cel/functions/
starts_with.rs

1use syn::parse_quote;
2use tonneau_cel::CelValue;
3
4use super::Function;
5use crate::codegen::cel::compiler::{
6    CompileError, CompiledExpr, CompilerCtx, ConstantCompiledExpr,
7};
8use crate::codegen::cel::types::CelType;
9use crate::types::{ProtoType, ProtoValueType};
10
11#[derive(Debug, Clone, Default)]
12pub(crate) struct StartsWith;
13
14// this.stratsWith(arg) -> arg in this
15impl Function for StartsWith {
16    fn name(&self) -> &'static str {
17        "startsWith"
18    }
19
20    fn syntax(&self) -> &'static str {
21        "<this>.startsWith(<arg>)"
22    }
23
24    fn compile(&self, ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
25        let Some(this) = &ctx.this else {
26            return Err(CompileError::syntax("missing this", self));
27        };
28
29        if ctx.args.len() != 1 {
30            return Err(CompileError::syntax("takes exactly one argument", self));
31        }
32
33        let arg = ctx.resolve(&ctx.args[0])?.into_cel()?;
34        let this = this.clone().into_cel()?;
35
36        match (this, arg) {
37            (
38                CompiledExpr::Constant(ConstantCompiledExpr { value: this }),
39                CompiledExpr::Constant(ConstantCompiledExpr { value: arg }),
40            ) => Ok(CompiledExpr::constant(CelValue::cel_starts_with(
41                this, arg,
42            )?)),
43            (this, arg) => Ok(CompiledExpr::runtime(
44                CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
45                parse_quote! {
46                    ::tonneau::__private::cel::CelValue::cel_starts_with(
47                        #this,
48                        #arg,
49                    )?
50                },
51            )),
52        }
53    }
54}
55
56#[cfg(test)]
57#[cfg(feature = "prost")]
58#[cfg_attr(coverage_nightly, coverage(off))]
59mod tests {
60    use syn::parse_quote;
61    use tonneau_cel::CelValue;
62
63    use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
64    use crate::codegen::cel::functions::{Function, StartsWith};
65    use crate::codegen::cel::types::CelType;
66    use crate::extern_paths::ExternPaths;
67    use crate::path_set::PathSet;
68    use crate::types::{ProtoType, ProtoTypeRegistry, ProtoValueType};
69
70    #[test]
71    fn test_starts_with_syntax() {
72        let registry = ProtoTypeRegistry::new(
73            crate::Mode::Prost,
74            ExternPaths::new(crate::Mode::Prost),
75            PathSet::default(),
76        );
77        let compiler = Compiler::new(&registry);
78        insta::assert_debug_snapshot!(StartsWith.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
79        Err(
80            InvalidSyntax {
81                message: "missing this",
82                syntax: "<this>.startsWith(<arg>)",
83            },
84        )
85        "#);
86
87        insta::assert_debug_snapshot!(StartsWith.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("13.2".into()))), &[])), @r#"
88        Err(
89            InvalidSyntax {
90                message: "takes exactly one argument",
91                syntax: "<this>.startsWith(<arg>)",
92            },
93        )
94        "#);
95
96        insta::assert_debug_snapshot!(StartsWith.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant("some string")), &[
97            cel_parser::parse("'som'").unwrap(), // not an ident
98        ])), @r"
99        Ok(
100            Constant(
101                ConstantCompiledExpr {
102                    value: Bool(
103                        true,
104                    ),
105                },
106            ),
107        )
108        ");
109    }
110
111    #[test]
112    #[cfg(not(valgrind))]
113    fn test_starts_with_runtime() {
114        let registry = ProtoTypeRegistry::new(
115            crate::Mode::Prost,
116            ExternPaths::new(crate::Mode::Prost),
117            PathSet::default(),
118        );
119        let compiler = Compiler::new(&registry);
120
121        let string_value = CompiledExpr::runtime(
122            CelType::Proto(ProtoType::Value(ProtoValueType::String)),
123            parse_quote!(input),
124        );
125
126        let output = StartsWith
127            .compile(CompilerCtx::new(
128                compiler.child(),
129                Some(string_value),
130                &[
131                    cel_parser::parse("'tes'").unwrap(), // not an ident
132                ],
133            ))
134            .unwrap();
135
136        insta::assert_snapshot!(postcompile::compile_str!(
137            postcompile::config! {
138                test: true,
139                dependencies: vec![
140                    postcompile::Dependency::path("tonneau", "../tonneau"),
141                ],
142            },
143            quote::quote! {
144                fn starts_with(input: &str) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
145                    Ok(#output)
146                }
147
148                #[test]
149                fn test_to_double() {
150                    assert_eq!(starts_with("testing").unwrap(), true);
151                    assert_eq!(starts_with("smile").unwrap(), false);
152                }
153            },
154        ));
155    }
156}