Skip to main content

tonneau_build/codegen/cel/
compiler.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use quote::{ToTokens, quote};
5use syn::parse_quote;
6use tonneau_cel::{CelEnum, CelError, CelValue, CelValueConv};
7
8use super::functions::{Function, add_to_compiler};
9use super::types::CelType;
10use crate::types::{ProtoPath, ProtoTypeRegistry};
11
12mod helpers;
13mod resolve;
14
15#[derive(Clone, Debug)]
16#[allow(clippy::large_enum_variant)]
17pub(crate) enum CompiledExpr {
18    Runtime(RuntimeCompiledExpr),
19    Constant(ConstantCompiledExpr),
20}
21
22impl CompiledExpr {
23    pub(crate) fn constant(value: impl CelValueConv<'static>) -> Self {
24        Self::Constant(ConstantCompiledExpr {
25            value: value.conv(),
26        })
27    }
28
29    pub(crate) fn runtime(ty: CelType, expr: syn::Expr) -> Self {
30        Self::Runtime(RuntimeCompiledExpr { expr, ty })
31    }
32}
33
34#[derive(Clone)]
35pub(crate) struct RuntimeCompiledExpr {
36    pub expr: syn::Expr,
37    pub ty: CelType,
38}
39
40#[derive(Debug, Clone)]
41pub(crate) struct ConstantCompiledExpr {
42    pub value: tonneau_cel::CelValue<'static>,
43}
44
45impl std::fmt::Debug for RuntimeCompiledExpr {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.debug_struct("RuntimeCompiledExpr")
48            .field("ty", &self.ty)
49            .field(
50                "expr",
51                &fmtools::fmt(|fmt| {
52                    let expr = &self.expr;
53                    let tokens = parse_quote! {
54                        const _: Debug = #expr;
55                    };
56                    let pretty = prettyplease::unparse(&tokens);
57                    let pretty = pretty.trim();
58                    let pretty = pretty.strip_prefix("const _: Debug =").unwrap_or(pretty);
59                    let pretty = pretty.strip_suffix(';').unwrap_or(pretty);
60                    fmt.write_str(pretty.trim())
61                }),
62            )
63            .finish()
64    }
65}
66
67impl ToTokens for RuntimeCompiledExpr {
68    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
69        self.expr.to_tokens(tokens);
70    }
71}
72
73impl ToTokens for ConstantCompiledExpr {
74    fn to_tokens(&self, stream: &mut proc_macro2::TokenStream) {
75        fn value_to_tokens(value: &CelValue) -> proc_macro2::TokenStream {
76            match value {
77                CelValue::Bool(b) => quote! {
78                    ::tonneau::__private::cel::CelValue::Bool(#b)
79                },
80                CelValue::Bytes(b) => {
81                    let b = syn::LitByteStr::new(b.as_ref(), proc_macro2::Span::call_site());
82                    quote! {
83                        ::tonneau::__private::cel::CelValue::Bytes(
84                            ::tonneau::__private::cel::CelBytes::Borrowed(
85                                #b
86                            )
87                        )
88                    }
89                }
90                CelValue::Enum(CelEnum { tag, value }) => {
91                    let tag = tag.as_ref();
92                    quote! {
93                        ::tonneau::__private::cel::CelValue::Enum(
94                            ::tonneau::__private::cel::CelValue::CelEnum {
95                                tag: ::tonneau::__private::cel::CelValue::CelString::Borrowed(#tag),
96                                value: #value,
97                            }
98                        )
99                    }
100                }
101                CelValue::List(list) => {
102                    let list = list.iter().map(value_to_tokens);
103                    quote! {
104                        ::tonneau::__private::cel::CelValue::List([
105                            #(#list),*
106                        ].into_iter().collect())
107                    }
108                }
109                CelValue::Map(map) => {
110                    let map = map
111                        .iter()
112                        .map(|(key, value)| (value_to_tokens(key), value_to_tokens(value)))
113                        .map(|(key, value)| quote!((#key, #value)));
114                    quote! {
115                        ::tonneau::__private::cel::CelValue::List([
116                            #(#map),*
117                        ].into_iter().collect())
118                    }
119                }
120                CelValue::Null => quote!(::tonneau::__private::cel::CelValue::Null),
121                CelValue::Number(tonneau_cel::NumberTy::F64(f)) => {
122                    quote!(::tonneau::__private::cel::CelValue::Number(::tonneau::__private::cel::NumberTy::F64(#f)))
123                }
124                CelValue::Number(tonneau_cel::NumberTy::I64(i)) => {
125                    quote!(::tonneau::__private::cel::CelValue::Number(::tonneau::__private::cel::NumberTy::I64(#i)))
126                }
127                CelValue::Number(tonneau_cel::NumberTy::U64(u)) => {
128                    quote!(::tonneau::__private::cel::CelValue::Number(::tonneau::__private::cel::NumberTy::U64(#u)))
129                }
130                CelValue::String(s) => {
131                    let s = s.as_ref();
132                    quote!(::tonneau::__private::cel::CelValue::String(::tonneau::__private::cel::CelString::Borrowed(#s)))
133                }
134                CelValue::Duration(b) => {
135                    let secs = b.num_seconds();
136                    let nanos = b.subsec_nanos();
137                    quote! {
138                        ::tonneau::__private::cel::CelValue::Duration(
139                            ::tonneau::reexports::chrono::Duration::new(
140                                #secs,
141                                #nanos,
142                            ).expect("duration was valid at build")
143                        )
144                    }
145                }
146                CelValue::Timestamp(ts) => {
147                    let tz_offset = ts.offset().local_minus_utc();
148                    let utc = ts.to_utc();
149                    let ts_secs = utc.timestamp();
150                    let ts_nanos = utc.timestamp_subsec_nanos();
151                    quote! {
152                        ::tonneau::__private::cel::CelValue::Timestamp(
153                            ::tonneau::reexports::chrono::TimeZone::timestamp_opt(
154                                &::tonneau::reexports::chrono::offset::FixedOffset::east_opt(#tz_offset)
155                                    .expect("codegen from build"),
156                                #ts_secs,
157                                #ts_nanos,
158                            ).unwrap()
159                        )
160                    }
161                }
162            }
163        }
164
165        value_to_tokens(&self.value).to_tokens(stream);
166    }
167}
168
169impl ToTokens for CompiledExpr {
170    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
171        match self {
172            Self::Constant(c) => c.to_tokens(tokens),
173            Self::Runtime(r) => r.to_tokens(tokens),
174        }
175    }
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub(crate) enum CompilerTarget {
180    Serde,
181    #[allow(dead_code)]
182    Proto,
183}
184
185#[derive(Clone, Debug)]
186pub(crate) struct Compiler<'a> {
187    parent: Option<&'a Compiler<'a>>,
188    registry: &'a ProtoTypeRegistry,
189    target: Option<CompilerTarget>,
190    variables: BTreeMap<String, CompiledExpr>,
191    functions: BTreeMap<&'static str, DebugFunc>,
192}
193
194#[derive(Clone)]
195struct DebugFunc(Arc<dyn Function + Send + Sync + 'static>);
196impl std::fmt::Debug for DebugFunc {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198        f.write_str(self.0.name())
199    }
200}
201
202impl<'a> Compiler<'a> {
203    pub(crate) fn empty(registry: &'a ProtoTypeRegistry) -> Self {
204        Self {
205            parent: None,
206            registry,
207            target: None,
208            variables: BTreeMap::new(),
209            functions: BTreeMap::new(),
210        }
211    }
212
213    pub(crate) fn new(registry: &'a ProtoTypeRegistry) -> Self {
214        let mut compiler = Self::empty(registry);
215
216        add_to_compiler(&mut compiler);
217
218        compiler
219    }
220
221    pub(crate) fn set_target(&mut self, target: impl Into<Option<CompilerTarget>>) {
222        self.target = target.into()
223    }
224
225    pub(crate) fn target(&self) -> Option<CompilerTarget> {
226        self.target
227    }
228
229    pub(crate) fn child(&self) -> Compiler<'_> {
230        Compiler {
231            parent: Some(self),
232            registry: self.registry,
233            target: self.target,
234            variables: BTreeMap::new(),
235            functions: BTreeMap::new(),
236        }
237    }
238}
239
240#[derive(Debug, Clone)]
241pub(crate) struct CompilerCtx<'a> {
242    pub this: Option<CompiledExpr>,
243    pub args: &'a [cel_parser::Expression],
244    compiler: Compiler<'a>,
245}
246
247impl<'a> CompilerCtx<'a> {
248    pub(crate) fn new(
249        compiler: Compiler<'a>,
250        this: Option<CompiledExpr>,
251        args: &'a [cel_parser::Expression],
252    ) -> Self {
253        Self {
254            this,
255            args,
256            compiler,
257        }
258    }
259}
260
261impl<'a> std::ops::Deref for CompilerCtx<'a> {
262    type Target = Compiler<'a>;
263
264    fn deref(&self) -> &Self::Target {
265        &self.compiler
266    }
267}
268
269impl std::ops::DerefMut for CompilerCtx<'_> {
270    fn deref_mut(&mut self) -> &mut Self::Target {
271        &mut self.compiler
272    }
273}
274
275impl<'a> Compiler<'a> {
276    pub(crate) fn add_variable(&mut self, name: &str, expr: CompiledExpr) {
277        self.variables.insert(name.to_owned(), expr.clone());
278    }
279
280    pub(crate) fn register_function(&mut self, f: impl Function) {
281        let name = f.name();
282        self.functions.insert(name, DebugFunc(Arc::new(f)));
283    }
284
285    pub(crate) fn resolve(
286        &self,
287        expr: &cel_parser::Expression,
288    ) -> Result<CompiledExpr, CompileError> {
289        resolve::resolve(self, expr)
290    }
291
292    pub(crate) fn get_variable(&self, name: &str) -> Option<&CompiledExpr> {
293        match self.variables.get(name) {
294            Some(expr) => Some(expr),
295            None => match self.parent {
296                Some(parent) => parent.get_variable(name),
297                None => None,
298            },
299        }
300    }
301
302    pub(crate) fn get_function(
303        &self,
304        name: &str,
305    ) -> Option<&Arc<dyn Function + Send + Sync + 'static>> {
306        match self.functions.get(name) {
307            Some(func) => Some(&func.0),
308            None => match self.parent {
309                Some(parent) => parent.get_function(name),
310                None => None,
311            },
312        }
313    }
314
315    pub(crate) fn registry(&self) -> &'a ProtoTypeRegistry {
316        self.registry
317    }
318}
319
320#[derive(Debug, Clone, PartialEq, thiserror::Error)]
321pub(crate) enum CompileError {
322    #[error("not implemented")]
323    NotImplemented,
324    #[error("invalid syntax: {message} - {syntax}")]
325    InvalidSyntax {
326        message: String,
327        syntax: &'static str,
328    },
329    #[error("type conversion error on type {ty:?}: {message}")]
330    TypeConversion { ty: Box<CelType>, message: String },
331    #[error("member access error on type {ty:?}: {message}")]
332    MemberAccess { ty: Box<CelType>, message: String },
333    #[error("variable not found: {0}")]
334    VariableNotFound(String),
335    #[error("function not found: {0}")]
336    FunctionNotFound(String),
337    #[error("unsupported function call identifier type: {0:?}")]
338    UnsupportedFunctionCallIdentifierType(cel_parser::Expression),
339    #[error("missing message: {0}")]
340    MissingMessage(ProtoPath),
341}
342
343impl CompileError {
344    pub(crate) fn syntax(message: impl std::fmt::Display, func: &impl Function) -> CompileError {
345        CompileError::InvalidSyntax {
346            message: message.to_string(),
347            syntax: func.syntax(),
348        }
349    }
350}
351
352impl From<CelError<'_>> for CompileError {
353    fn from(value: CelError<'_>) -> Self {
354        Self::TypeConversion {
355            ty: Box::new(CelType::CelValue),
356            message: value.to_string(),
357        }
358    }
359}