Skip to main content

tonneau_build/codegen/cel/functions/
matches.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 Matches;
13
14// this.matches(arg) -> arg in this
15impl Function for Matches {
16    fn name(&self) -> &'static str {
17        "matches"
18    }
19
20    fn syntax(&self) -> &'static str {
21        "<this>.matches(<const regex>)"
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 CompiledExpr::Constant(ConstantCompiledExpr {
34            value: CelValue::String(regex),
35        }) = ctx.resolve(&ctx.args[0])?.into_cel()?
36        else {
37            return Err(CompileError::syntax(
38                "regex must be known at compile time string",
39                self,
40            ));
41        };
42
43        let regex = regex.as_ref();
44        if regex.is_empty() {
45            return Err(CompileError::syntax(
46                "regex cannot be an empty string",
47                self,
48            ));
49        }
50
51        let re = regex::Regex::new(regex)
52            .map_err(|err| CompileError::syntax(format!("bad regex {err}"), self))?;
53
54        let this = this.clone().into_cel()?;
55
56        match this {
57            CompiledExpr::Constant(ConstantCompiledExpr { value }) => {
58                Ok(CompiledExpr::constant(CelValue::cel_matches(value, &re)?))
59            }
60            this => Ok(CompiledExpr::runtime(
61                CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
62                parse_quote! {{
63                    static REGEX: ::std::sync::LazyLock<::tonneau::reexports::regex::Regex> = ::std::sync::LazyLock::new(|| {
64                        ::tonneau::reexports::regex::Regex::new(#regex).expect("failed to compile regex this is a bug in tonneau")
65                    });
66
67                    ::tonneau::__private::cel::CelValue::cel_matches(
68                        #this,
69                        &*REGEX,
70                    )?
71                }},
72            )),
73        }
74    }
75}
76
77#[cfg(test)]
78#[cfg(feature = "prost")]
79#[cfg_attr(coverage_nightly, coverage(off))]
80mod tests {
81    use quote::quote;
82    use syn::parse_quote;
83    use tonneau_cel::CelValue;
84
85    use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
86    use crate::codegen::cel::functions::{Function, Matches};
87    use crate::codegen::cel::types::CelType;
88    use crate::extern_paths::ExternPaths;
89    use crate::path_set::PathSet;
90    use crate::types::{ProtoType, ProtoTypeRegistry, ProtoValueType};
91
92    #[test]
93    fn test_matches_syntax() {
94        let registry = ProtoTypeRegistry::new(
95            crate::Mode::Prost,
96            ExternPaths::new(crate::Mode::Prost),
97            PathSet::default(),
98        );
99        let compiler = Compiler::new(&registry);
100        insta::assert_debug_snapshot!(Matches.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
101        Err(
102            InvalidSyntax {
103                message: "missing this",
104                syntax: "<this>.matches(<const regex>)",
105            },
106        )
107        "#);
108
109        insta::assert_debug_snapshot!(Matches.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("hi".into()))), &[])), @r#"
110        Err(
111            InvalidSyntax {
112                message: "takes exactly one argument",
113                syntax: "<this>.matches(<const regex>)",
114            },
115        )
116        "#);
117
118        insta::assert_debug_snapshot!(Matches.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("hi".into()))), &[
119            cel_parser::parse("dyn('^h')").unwrap(),
120        ])), @r#"
121        Err(
122            InvalidSyntax {
123                message: "regex must be known at compile time string",
124                syntax: "<this>.matches(<const regex>)",
125            },
126        )
127        "#);
128
129        insta::assert_debug_snapshot!(Matches.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("hi".into()))), &[
130            cel_parser::parse("'^h'").unwrap(),
131        ])), @r"
132        Ok(
133            Constant(
134                ConstantCompiledExpr {
135                    value: Bool(
136                        true,
137                    ),
138                },
139            ),
140        )
141        ");
142    }
143
144    #[test]
145    #[cfg(not(valgrind))]
146    fn test_matches_runtime_string() {
147        let registry = ProtoTypeRegistry::new(
148            crate::Mode::Prost,
149            ExternPaths::new(crate::Mode::Prost),
150            PathSet::default(),
151        );
152        let compiler = Compiler::new(&registry);
153
154        let string_value = CompiledExpr::runtime(
155            CelType::Proto(ProtoType::Value(ProtoValueType::String)),
156            parse_quote!(input),
157        );
158
159        let output = Matches
160            .compile(CompilerCtx::new(
161                compiler.child(),
162                Some(string_value),
163                &[cel_parser::parse("'\\\\d+'").unwrap()],
164            ))
165            .unwrap();
166
167        insta::assert_snapshot!(postcompile::compile_str!(
168            postcompile::config! {
169                test: true,
170                dependencies: vec![
171                    postcompile::Dependency::path("tonneau", "../tonneau"),
172                ],
173            },
174            quote! {
175                fn matches(input: &String) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
176                    Ok(#output)
177                }
178
179                #[test]
180                fn test_matches() {
181                    assert_eq!(matches(&"in2dastring".into()).unwrap(), true);
182                    assert_eq!(matches(&"in3dastring".into()).unwrap(), true);
183                    assert_eq!(matches(&"xd".into()).unwrap(), false);
184                }
185            },
186        ));
187    }
188}