tinc_build/codegen/cel/functions/
map.rs

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