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