Skip to main content

tonneau_build/codegen/cel/functions/
ends_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 EndsWith;
13
14// this.endsWith(arg) -> arg in this
15impl Function for EndsWith {
16    fn name(&self) -> &'static str {
17        "endsWith"
18    }
19
20    fn syntax(&self) -> &'static str {
21        "<this>.endsWith(<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_ends_with(this, arg)?)),
41            (this, arg) => Ok(CompiledExpr::runtime(
42                CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
43                parse_quote! {
44                    ::tonneau::__private::cel::CelValue::cel_ends_with(
45                        #this,
46                        #arg,
47                    )?
48                },
49            )),
50        }
51    }
52}
53
54#[cfg(test)]
55#[cfg(feature = "prost")]
56#[cfg_attr(coverage_nightly, coverage(off))]
57mod tests {
58    use syn::parse_quote;
59    use tonneau_cel::CelValue;
60
61    use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
62    use crate::codegen::cel::functions::{EndsWith, Function};
63    use crate::codegen::cel::types::CelType;
64    use crate::extern_paths::ExternPaths;
65    use crate::path_set::PathSet;
66    use crate::types::{ProtoType, ProtoTypeRegistry, ProtoValueType};
67
68    #[test]
69    fn test_ends_with_syntax() {
70        let registry = ProtoTypeRegistry::new(
71            crate::Mode::Prost,
72            ExternPaths::new(crate::Mode::Prost),
73            PathSet::default(),
74        );
75        let compiler = Compiler::new(&registry);
76        insta::assert_debug_snapshot!(EndsWith.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
77        Err(
78            InvalidSyntax {
79                message: "missing this",
80                syntax: "<this>.endsWith(<arg>)",
81            },
82        )
83        "#);
84
85        insta::assert_debug_snapshot!(EndsWith.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("13.2".into()))), &[])), @r#"
86        Err(
87            InvalidSyntax {
88                message: "takes exactly one argument",
89                syntax: "<this>.endsWith(<arg>)",
90            },
91        )
92        "#);
93
94        insta::assert_debug_snapshot!(EndsWith.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant("some string")), &[
95            cel_parser::parse("'ing'").unwrap(), // not an ident
96        ])), @r"
97        Ok(
98            Constant(
99                ConstantCompiledExpr {
100                    value: Bool(
101                        true,
102                    ),
103                },
104            ),
105        )
106        ");
107    }
108
109    #[test]
110    #[cfg(not(valgrind))]
111    fn test_ends_with_runtime() {
112        let registry = ProtoTypeRegistry::new(
113            crate::Mode::Prost,
114            ExternPaths::new(crate::Mode::Prost),
115            PathSet::default(),
116        );
117        let compiler = Compiler::new(&registry);
118
119        let string_value = CompiledExpr::runtime(
120            CelType::Proto(ProtoType::Value(ProtoValueType::String)),
121            parse_quote!(input),
122        );
123
124        let output = EndsWith
125            .compile(CompilerCtx::new(
126                compiler.child(),
127                Some(string_value),
128                &[
129                    cel_parser::parse("'ing'").unwrap(), // not an ident
130                ],
131            ))
132            .unwrap();
133
134        insta::assert_snapshot!(postcompile::compile_str!(
135            postcompile::config! {
136                test: true,
137                dependencies: vec![
138                    postcompile::Dependency::path("tonneau", "../tonneau"),
139                ],
140            },
141            quote::quote! {
142                fn ends_with(input: &str) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
143                    Ok(#output)
144                }
145
146                #[test]
147                fn test_to_double() {
148                    assert_eq!(ends_with("testing").unwrap(), true);
149                    assert_eq!(ends_with("smile").unwrap(), false);
150                }
151            },
152        ));
153    }
154}