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