tonneau_build/codegen/cel/functions/
contains.rs1use quote::quote;
2use syn::parse_quote;
3use tonneau_cel::CelValue;
4
5use super::Function;
6use crate::codegen::cel::compiler::{
7 CompileError, CompiledExpr, CompilerCtx, ConstantCompiledExpr, RuntimeCompiledExpr,
8};
9use crate::codegen::cel::types::CelType;
10use crate::types::{ProtoModifiedValueType, ProtoType, ProtoValueType};
11
12#[derive(Debug, Clone, Default)]
13pub(crate) struct Contains;
14
15impl Function for Contains {
18 fn name(&self) -> &'static str {
19 "contains"
20 }
21
22 fn syntax(&self) -> &'static str {
23 "<this>.contains(<arg>)"
24 }
25
26 fn compile(&self, mut ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
27 let Some(this) = ctx.this.take() else {
28 return Err(CompileError::syntax("missing this", self));
29 };
30
31 if ctx.args.len() != 1 {
32 return Err(CompileError::syntax("takes exactly one argument", self));
33 }
34
35 let arg = ctx.resolve(&ctx.args[0])?.into_cel()?;
36
37 if let CompiledExpr::Runtime(RuntimeCompiledExpr {
38 expr,
39 ty:
40 ty @ CelType::Proto(ProtoType::Modified(
41 ProtoModifiedValueType::Repeated(item) | ProtoModifiedValueType::Map(item, _),
42 )),
43 }) = &this
44 && !matches!(
45 item,
46 ProtoValueType::Message { .. } | ProtoValueType::Enum(_)
47 )
48 {
49 let op = match &ty {
50 CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Repeated(_))) => {
51 quote! { array_contains }
52 }
53 CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Map(_, _))) => {
54 quote! { map_contains }
55 }
56 _ => unreachable!(),
57 };
58
59 return Ok(CompiledExpr::runtime(
60 CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
61 parse_quote! {
62 ::tonneau::__private::cel::#op(
63 #expr,
64 #arg,
65 )
66 },
67 ));
68 }
69
70 let this = this.clone().into_cel()?;
71
72 match (this, arg) {
73 (
74 CompiledExpr::Constant(ConstantCompiledExpr { value: this }),
75 CompiledExpr::Constant(ConstantCompiledExpr { value: arg }),
76 ) => Ok(CompiledExpr::constant(CelValue::cel_contains(this, arg)?)),
77 (this, arg) => Ok(CompiledExpr::runtime(
78 CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
79 parse_quote! {
80 ::tonneau::__private::cel::CelValue::cel_contains(
81 #this,
82 #arg,
83 )?
84 },
85 )),
86 }
87 }
88}
89
90#[cfg(test)]
91#[cfg(feature = "prost")]
92#[cfg_attr(coverage_nightly, coverage(off))]
93mod tests {
94 use quote::quote;
95 use syn::parse_quote;
96 use tonneau_cel::CelValue;
97
98 use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
99 use crate::codegen::cel::functions::{Contains, Function};
100 use crate::codegen::cel::types::CelType;
101 use crate::extern_paths::ExternPaths;
102 use crate::path_set::PathSet;
103 use crate::types::{ProtoModifiedValueType, ProtoType, ProtoTypeRegistry, ProtoValueType};
104
105 #[test]
106 fn test_contains_syntax() {
107 let registry = ProtoTypeRegistry::new(
108 crate::Mode::Prost,
109 ExternPaths::new(crate::Mode::Prost),
110 PathSet::default(),
111 );
112 let compiler = Compiler::new(®istry);
113 insta::assert_debug_snapshot!(Contains.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
114 Err(
115 InvalidSyntax {
116 message: "missing this",
117 syntax: "<this>.contains(<arg>)",
118 },
119 )
120 "#);
121
122 insta::assert_debug_snapshot!(Contains.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("hi".into()))), &[])), @r#"
123 Err(
124 InvalidSyntax {
125 message: "takes exactly one argument",
126 syntax: "<this>.contains(<arg>)",
127 },
128 )
129 "#);
130
131 insta::assert_debug_snapshot!(Contains.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::List(Default::default()))), &[
132 cel_parser::parse("1 + 1").unwrap(),
133 ])), @r"
134 Ok(
135 Constant(
136 ConstantCompiledExpr {
137 value: Bool(
138 false,
139 ),
140 },
141 ),
142 )
143 ");
144 }
145
146 #[test]
147 #[cfg(not(valgrind))]
148 fn test_contains_runtime_string() {
149 let registry = ProtoTypeRegistry::new(
150 crate::Mode::Prost,
151 ExternPaths::new(crate::Mode::Prost),
152 PathSet::default(),
153 );
154 let compiler = Compiler::new(®istry);
155
156 let string_value = CompiledExpr::runtime(
157 CelType::Proto(ProtoType::Value(ProtoValueType::String)),
158 parse_quote!(input),
159 );
160
161 let output = Contains
162 .compile(CompilerCtx::new(
163 compiler.child(),
164 Some(string_value),
165 &[cel_parser::parse("(1 + 1).string()").unwrap()],
166 ))
167 .unwrap();
168
169 insta::assert_snapshot!(postcompile::compile_str!(
170 postcompile::config! {
171 test: true,
172 dependencies: vec![
173 postcompile::Dependency::path("tonneau", "../tonneau"),
174 ],
175 },
176 quote! {
177 fn contains(input: &String) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
178 Ok(#output)
179 }
180
181 #[test]
182 fn test_contains() {
183 assert_eq!(contains(&"in2dastring".into()).unwrap(), true);
184 assert_eq!(contains(&"in3dastring".into()).unwrap(), false);
185 }
186 },
187 ));
188 }
189
190 #[test]
191 #[cfg(not(valgrind))]
192 fn test_contains_runtime_map() {
193 let registry = ProtoTypeRegistry::new(
194 crate::Mode::Prost,
195 ExternPaths::new(crate::Mode::Prost),
196 PathSet::default(),
197 );
198 let compiler = Compiler::new(®istry);
199
200 let string_value = CompiledExpr::runtime(
201 CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Map(
202 ProtoValueType::String,
203 ProtoValueType::Bool,
204 ))),
205 parse_quote!(input),
206 );
207
208 let output = Contains
209 .compile(CompilerCtx::new(
210 compiler.child(),
211 Some(string_value),
212 &[cel_parser::parse("'value'").unwrap()],
213 ))
214 .unwrap();
215
216 insta::assert_snapshot!(postcompile::compile_str!(
217 postcompile::config! {
218 test: true,
219 dependencies: vec![
220 postcompile::Dependency::path("tonneau", "../tonneau"),
221 ],
222 },
223 quote! {
224 fn contains(input: &std::collections::HashMap<String, bool>) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
225 Ok(#output)
226 }
227
228 #[test]
229 fn test_contains() {
230 assert_eq!(contains(&{
231 let mut map = std::collections::HashMap::new();
232 map.insert("value".to_string(), true);
233 map
234 }).unwrap(), true);
235 assert_eq!(contains(&{
236 let mut map = std::collections::HashMap::new();
237 map.insert("not_value".to_string(), true);
238 map
239 }).unwrap(), false);
240 assert_eq!(contains(&{
241 let mut map = std::collections::HashMap::new();
242 map.insert("xd".to_string(), true);
243 map.insert("value".to_string(), true);
244 map
245 }).unwrap(), true);
246 }
247 },
248 ));
249 }
250
251 #[test]
252 #[cfg(not(valgrind))]
253 fn test_contains_runtime_repeated() {
254 let registry = ProtoTypeRegistry::new(
255 crate::Mode::Prost,
256 ExternPaths::new(crate::Mode::Prost),
257 PathSet::default(),
258 );
259 let compiler = Compiler::new(®istry);
260
261 let string_value = CompiledExpr::runtime(
262 CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Repeated(
263 ProtoValueType::String,
264 ))),
265 parse_quote!(input),
266 );
267
268 let output = Contains
269 .compile(CompilerCtx::new(
270 compiler.child(),
271 Some(string_value),
272 &[cel_parser::parse("'value'").unwrap()],
273 ))
274 .unwrap();
275
276 insta::assert_snapshot!(postcompile::compile_str!(
277 postcompile::config! {
278 test: true,
279 dependencies: vec![
280 postcompile::Dependency::path("tonneau", "../tonneau"),
281 ],
282 },
283 quote! {
284 fn contains(input: &Vec<String>) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
285 Ok(#output)
286 }
287
288 #[test]
289 fn test_contains() {
290 assert_eq!(contains(&vec!["value".into()]).unwrap(), true);
291 assert_eq!(contains(&vec!["not_value".into()]).unwrap(), false);
292 assert_eq!(contains(&vec!["xd".into(), "value".into()]).unwrap(), true);
293 }
294 },
295 ));
296 }
297}