Skip to main content

tonneau_build/codegen/cel/functions/
exists.rs

1use proc_macro2::TokenStream;
2use quote::{ToTokens, quote};
3use syn::parse_quote;
4use tonneau_cel::CelValue;
5
6use super::Function;
7use crate::codegen::cel::compiler::{
8    CompileError, CompiledExpr, CompilerCtx, ConstantCompiledExpr, RuntimeCompiledExpr,
9};
10use crate::codegen::cel::types::CelType;
11use crate::types::{ProtoModifiedValueType, ProtoType, ProtoValueType};
12
13#[derive(Debug, Clone, Default)]
14pub(crate) struct Exists;
15
16fn native_impl(iter: TokenStream, item_ident: syn::Ident, compare: impl ToTokens) -> syn::Expr {
17    parse_quote!({
18        let mut iter = (#iter).into_iter();
19        loop {
20            let Some(#item_ident) = iter.next() else {
21                break false;
22            };
23
24            if #compare {
25                break true;
26            }
27        }
28    })
29}
30
31// this.exists(<ident>, <expr>)
32impl Function for Exists {
33    fn name(&self) -> &'static str {
34        "exists"
35    }
36
37    fn syntax(&self) -> &'static str {
38        "<this>.exists(<ident>, <expr>)"
39    }
40
41    fn compile(&self, mut ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
42        let Some(this) = ctx.this.take() else {
43            return Err(CompileError::syntax("missing this", self));
44        };
45
46        if ctx.args.len() != 2 {
47            return Err(CompileError::syntax("invalid number of args", self));
48        }
49
50        let cel_parser::Expression::Ident(variable) = &ctx.args[0] else {
51            return Err(CompileError::syntax(
52                "first argument must be an ident",
53                self,
54            ));
55        };
56
57        match this {
58            CompiledExpr::Runtime(RuntimeCompiledExpr { expr, ty }) => {
59                let mut child_ctx = ctx.child();
60
61                match &ty {
62                    CelType::CelValue => {
63                        child_ctx.add_variable(
64                            variable,
65                            CompiledExpr::runtime(CelType::CelValue, parse_quote!(item)),
66                        );
67                    }
68                    CelType::Proto(ProtoType::Modified(
69                        ProtoModifiedValueType::Repeated(ty) | ProtoModifiedValueType::Map(ty, _),
70                    )) => {
71                        child_ctx.add_variable(
72                            variable,
73                            CompiledExpr::runtime(
74                                CelType::Proto(ProtoType::Value(ty.clone())),
75                                parse_quote!(item),
76                            ),
77                        );
78                    }
79                    v => {
80                        return Err(CompileError::TypeConversion {
81                            ty: Box::new(v.clone()),
82                            message: "type cannot be iterated over".to_string(),
83                        });
84                    }
85                };
86
87                let arg = child_ctx.resolve(&ctx.args[1])?.into_bool(&child_ctx);
88
89                Ok(CompiledExpr::runtime(
90                    CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
91                    match &ty {
92                        CelType::CelValue => parse_quote! {
93                            ::tonneau::__private::cel::CelValue::cel_exists(#expr, |item| {
94                                ::core::result::Result::Ok(
95                                    #arg
96                                )
97                            })?
98                        },
99                        CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Map(_, _))) => {
100                            native_impl(quote!((#expr).keys()), parse_quote!(item), arg)
101                        }
102                        CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Repeated(
103                            _,
104                        ))) => native_impl(quote!((#expr).iter()), parse_quote!(item), arg),
105                        _ => unreachable!(),
106                    },
107                ))
108            }
109            CompiledExpr::Constant(ConstantCompiledExpr {
110                value: value @ (CelValue::List(_) | CelValue::Map(_)),
111            }) => {
112                let compile_val = |value: CelValue<'static>| {
113                    let mut child_ctx = ctx.child();
114
115                    child_ctx.add_variable(variable, CompiledExpr::constant(value));
116
117                    child_ctx
118                        .resolve(&ctx.args[1])
119                        .map(|v| v.into_bool(&child_ctx))
120                };
121
122                let collected: Result<Vec<_>, _> = match value {
123                    CelValue::List(item) => item.iter().cloned().map(compile_val).collect(),
124                    CelValue::Map(item) => item
125                        .iter()
126                        .map(|(key, _)| key)
127                        .cloned()
128                        .map(compile_val)
129                        .collect(),
130                    _ => unreachable!(),
131                };
132
133                let collected = collected?;
134                if collected
135                    .iter()
136                    .any(|c| matches!(c, CompiledExpr::Runtime(_)))
137                {
138                    Ok(CompiledExpr::runtime(
139                        CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
140                        native_impl(quote!([#(#collected),*]), parse_quote!(item), quote!(item)),
141                    ))
142                } else {
143                    Ok(CompiledExpr::constant(CelValue::Bool(
144                        collected.into_iter().any(|c| match c {
145                            CompiledExpr::Constant(ConstantCompiledExpr { value }) => {
146                                value.to_bool()
147                            }
148                            _ => unreachable!("all values must be constant"),
149                        }),
150                    )))
151                }
152            }
153            CompiledExpr::Constant(ConstantCompiledExpr { value }) => {
154                Err(CompileError::TypeConversion {
155                    ty: Box::new(CelType::CelValue),
156                    message: format!("{value:?} cannot be iterated over"),
157                })
158            }
159        }
160    }
161}
162
163#[cfg(test)]
164#[cfg(feature = "prost")]
165#[cfg_attr(coverage_nightly, coverage(off))]
166mod tests {
167    use quote::quote;
168    use syn::parse_quote;
169    use tonneau_cel::{CelValue, CelValueConv};
170
171    use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
172    use crate::codegen::cel::functions::{Exists, Function};
173    use crate::codegen::cel::types::CelType;
174    use crate::extern_paths::ExternPaths;
175    use crate::path_set::PathSet;
176    use crate::types::{ProtoModifiedValueType, ProtoType, ProtoTypeRegistry, ProtoValueType};
177
178    #[test]
179    fn test_exists_syntax() {
180        let registry = ProtoTypeRegistry::new(
181            crate::Mode::Prost,
182            ExternPaths::new(crate::Mode::Prost),
183            PathSet::default(),
184        );
185        let compiler = Compiler::new(&registry);
186        insta::assert_debug_snapshot!(Exists.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
187        Err(
188            InvalidSyntax {
189                message: "missing this",
190                syntax: "<this>.exists(<ident>, <expr>)",
191            },
192        )
193        "#);
194
195        insta::assert_debug_snapshot!(Exists.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("hi".into()))), &[])), @r#"
196        Err(
197            InvalidSyntax {
198                message: "invalid number of args",
199                syntax: "<this>.exists(<ident>, <expr>)",
200            },
201        )
202        "#);
203
204        insta::assert_debug_snapshot!(Exists.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("hi".into()))), &[
205            cel_parser::parse("x").unwrap(),
206            cel_parser::parse("dyn(x >= 1)").unwrap(),
207        ])), @r#"
208        Err(
209            TypeConversion {
210                ty: CelValue,
211                message: "String(Borrowed(\"hi\")) cannot be iterated over",
212            },
213        )
214        "#);
215
216        insta::assert_debug_snapshot!(Exists.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::runtime(CelType::Proto(ProtoType::Value(ProtoValueType::Bool)), parse_quote!(input))), &[
217            cel_parser::parse("x").unwrap(),
218            cel_parser::parse("dyn(x >= 1)").unwrap(),
219        ])), @r#"
220        Err(
221            TypeConversion {
222                ty: Proto(
223                    Value(
224                        Bool,
225                    ),
226                ),
227                message: "type cannot be iterated over",
228            },
229        )
230        "#);
231
232        insta::assert_debug_snapshot!(Exists.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::List(Default::default()))), &[
233            cel_parser::parse("x").unwrap(),
234            cel_parser::parse("x == 'value'").unwrap(),
235        ])), @r"
236        Ok(
237            Constant(
238                ConstantCompiledExpr {
239                    value: Bool(
240                        false,
241                    ),
242                },
243            ),
244        )
245        ");
246    }
247
248    #[test]
249    #[cfg(not(valgrind))]
250    fn test_exists_runtime_map() {
251        let registry = ProtoTypeRegistry::new(
252            crate::Mode::Prost,
253            ExternPaths::new(crate::Mode::Prost),
254            PathSet::default(),
255        );
256        let compiler = Compiler::new(&registry);
257
258        let string_value = CompiledExpr::runtime(
259            CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Map(
260                ProtoValueType::String,
261                ProtoValueType::Bool,
262            ))),
263            parse_quote!(input),
264        );
265
266        let output = Exists
267            .compile(CompilerCtx::new(
268                compiler.child(),
269                Some(string_value),
270                &[
271                    cel_parser::parse("x").unwrap(),
272                    cel_parser::parse("x == 'value'").unwrap(),
273                ],
274            ))
275            .unwrap();
276
277        insta::assert_snapshot!(postcompile::compile_str!(
278            postcompile::config! {
279                test: true,
280                dependencies: vec![
281                    postcompile::Dependency::path("tonneau", "../tonneau"),
282                ],
283            },
284            quote! {
285                fn exists(input: &std::collections::HashMap<String, bool>) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
286                    Ok(#output)
287                }
288
289                #[test]
290                fn test_contains() {
291                    assert_eq!(exists(&{
292                        let mut map = std::collections::HashMap::new();
293                        map.insert("value".to_string(), true);
294                        map
295                    }).unwrap(), true);
296                    assert_eq!(exists(&{
297                        let mut map = std::collections::HashMap::new();
298                        map.insert("not_value".to_string(), true);
299                        map
300                    }).unwrap(), false);
301                    assert_eq!(exists(&{
302                        let mut map = std::collections::HashMap::new();
303                        map.insert("xd".to_string(), true);
304                        map.insert("value".to_string(), true);
305                        map
306                    }).unwrap(), true);
307                }
308            },
309        ));
310    }
311
312    #[test]
313    #[cfg(not(valgrind))]
314    fn test_exists_runtime_repeated() {
315        let registry = ProtoTypeRegistry::new(
316            crate::Mode::Prost,
317            ExternPaths::new(crate::Mode::Prost),
318            PathSet::default(),
319        );
320        let compiler = Compiler::new(&registry);
321
322        let string_value = CompiledExpr::runtime(
323            CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Repeated(
324                ProtoValueType::String,
325            ))),
326            parse_quote!(input),
327        );
328
329        let output = Exists
330            .compile(CompilerCtx::new(
331                compiler.child(),
332                Some(string_value),
333                &[
334                    cel_parser::parse("x").unwrap(),
335                    cel_parser::parse("x == 'value'").unwrap(),
336                ],
337            ))
338            .unwrap();
339
340        insta::assert_snapshot!(postcompile::compile_str!(
341            postcompile::config! {
342                test: true,
343                dependencies: vec![
344                    postcompile::Dependency::path("tonneau", "../tonneau"),
345                ],
346            },
347            quote! {
348                fn exists(input: &Vec<String>) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
349                    Ok(#output)
350                }
351
352                #[test]
353                fn test_exists() {
354                    assert_eq!(exists(&vec!["value".into()]).unwrap(), true);
355                    assert_eq!(exists(&vec!["not_value".into()]).unwrap(), false);
356                    assert_eq!(exists(&vec!["xd".into(), "value".into()]).unwrap(), true);
357                    assert_eq!(exists(&vec!["xd".into(), "value".into(), "value".into()]).unwrap(), true);
358                }
359            },
360        ));
361    }
362
363    #[test]
364    #[cfg(not(valgrind))]
365    fn test_exists_runtime_cel_value() {
366        let registry = ProtoTypeRegistry::new(
367            crate::Mode::Prost,
368            ExternPaths::new(crate::Mode::Prost),
369            PathSet::default(),
370        );
371        let compiler = Compiler::new(&registry);
372
373        let string_value = CompiledExpr::runtime(CelType::CelValue, parse_quote!(input));
374
375        let output = Exists
376            .compile(CompilerCtx::new(
377                compiler.child(),
378                Some(string_value),
379                &[
380                    cel_parser::parse("x").unwrap(),
381                    cel_parser::parse("x == 'value'").unwrap(),
382                ],
383            ))
384            .unwrap();
385
386        insta::assert_snapshot!(postcompile::compile_str!(
387            postcompile::config! {
388                test: true,
389                dependencies: vec![
390                    postcompile::Dependency::path("tonneau", "../tonneau"),
391                ],
392            },
393            quote! {
394                fn exists<'a>(input: &'a ::tonneau::__private::cel::CelValue<'a>) -> Result<bool, ::tonneau::__private::cel::CelError<'a>> {
395                    Ok(#output)
396                }
397
398                #[test]
399                fn test_exists() {
400                    assert_eq!(exists(&tonneau::__private::cel::CelValue::List([
401                        tonneau::__private::cel::CelValueConv::conv("value"),
402                    ].into_iter().collect())).unwrap(), true);
403                    assert_eq!(exists(&tonneau::__private::cel::CelValue::List([
404                        tonneau::__private::cel::CelValueConv::conv("not_value"),
405                    ].into_iter().collect())).unwrap(), false);
406                    assert_eq!(exists(&tonneau::__private::cel::CelValue::List([
407                        tonneau::__private::cel::CelValueConv::conv("xd"),
408                        tonneau::__private::cel::CelValueConv::conv("value"),
409                    ].into_iter().collect())).unwrap(), true);
410                    assert_eq!(exists(&tonneau::__private::cel::CelValue::List([
411                        tonneau::__private::cel::CelValueConv::conv("xd"),
412                        tonneau::__private::cel::CelValueConv::conv("value"),
413                        tonneau::__private::cel::CelValueConv::conv("value"),
414                    ].into_iter().collect())).unwrap(), true);
415                }
416            },
417        ));
418    }
419
420    #[test]
421    #[cfg(not(valgrind))]
422    fn test_exists_const_requires_runtime() {
423        let registry = ProtoTypeRegistry::new(
424            crate::Mode::Prost,
425            ExternPaths::new(crate::Mode::Prost),
426            PathSet::default(),
427        );
428        let compiler = Compiler::new(&registry);
429
430        let list_value = CompiledExpr::constant(CelValue::List(
431            [
432                CelValueConv::conv(5),
433                CelValueConv::conv(0),
434                CelValueConv::conv(1),
435            ]
436            .into_iter()
437            .collect(),
438        ));
439
440        let output = Exists
441            .compile(CompilerCtx::new(
442                compiler.child(),
443                Some(list_value),
444                &[
445                    cel_parser::parse("x").unwrap(),
446                    cel_parser::parse("dyn(x >= 1)").unwrap(),
447                ],
448            ))
449            .unwrap();
450
451        insta::assert_snapshot!(postcompile::compile_str!(
452            postcompile::config! {
453                test: true,
454                dependencies: vec![
455                    postcompile::Dependency::path("tonneau", "../tonneau"),
456                ],
457            },
458            quote! {
459                fn exists_one() -> Result<bool, ::tonneau::__private::cel::CelError<'static>> {
460                    Ok(#output)
461                }
462
463                #[test]
464                fn test_filter() {
465                    assert_eq!(exists_one().unwrap(), true);
466                }
467            },
468        ));
469    }
470}