Skip to main content

tonneau_build/codegen/
cel.rs

1use std::collections::HashMap;
2
3use anyhow::Context;
4use compiler::{CompiledExpr, CompilerCtx, ConstantCompiledExpr, RuntimeCompiledExpr};
5use functions::Function;
6use proc_macro2::TokenStream;
7use quote::{format_ident, quote};
8use tonneau_cel::CelValue;
9
10pub(crate) mod compiler;
11pub(crate) mod functions;
12pub(crate) mod types;
13
14pub(crate) fn eval_message_fmt(
15    field_full_name: &str,
16    msg: &str,
17    ctx: &compiler::Compiler<'_>,
18) -> anyhow::Result<TokenStream> {
19    let fmt = runtime_format::ParsedFmt::new(msg)
20        .map_err(|err| anyhow::anyhow!("failed to parse message format: {err}"))?;
21
22    let mut runtime_args = Vec::new();
23    let mut compile_time_args = HashMap::new();
24
25    // each key itself a cel expression
26    for key in fmt.keys() {
27        let expr = cel_parser::parse(key).context("failed to parse cel expression")?;
28        match functions::String.compile(CompilerCtx::new(
29            ctx.child(),
30            Some(ctx.resolve(&expr)?),
31            &[],
32        ))? {
33            CompiledExpr::Constant(ConstantCompiledExpr { value }) => {
34                // we need to escape the '{' & '}'
35                compile_time_args.insert(key, value);
36            }
37            CompiledExpr::Runtime(RuntimeCompiledExpr { expr, .. }) => {
38                let ident = format_ident!("arg_{}", runtime_args.len());
39                compile_time_args.insert(key, CelValue::String(format!("{{{ident}}}").into()));
40                runtime_args.push((key, ident, expr));
41            }
42        }
43    }
44
45    let fmt = fmt.with_args(&compile_time_args).to_string();
46
47    if runtime_args.is_empty() {
48        Ok(quote!(#fmt))
49    } else {
50        let args = runtime_args.iter().map(|(key, ident, expr)| {
51            quote! {
52                #ident = (
53                    || {
54                        ::core::result::Result::Ok::<_, ::tonneau::__private::cel::CelError>(#expr)
55                    }
56                )().map_err(|err| {
57                    ::tonneau::__private::ValidationError::Expression {
58                        error: err.to_string().into_boxed_str(),
59                        field: #field_full_name,
60                        expression: #key,
61                    }
62                })?
63            }
64        });
65
66        Ok(quote!(format!(#fmt, #(#args),*)))
67    }
68}
69
70#[derive(Debug, Clone, PartialEq)]
71pub(crate) struct CelExpression {
72    pub message: String,
73    pub expression: String,
74    pub jsonschemas: Vec<String>,
75    pub this: Option<CelValue<'static>>,
76}
77
78#[derive(Debug, PartialEq, Clone, Default)]
79pub(crate) struct CelExpressions {
80    pub field: Vec<CelExpression>,
81    pub map_key: Vec<CelExpression>,
82    pub map_value: Vec<CelExpression>,
83    pub repeated_item: Vec<CelExpression>,
84}