Skip to main content

tonneau_build/codegen/cel/functions/
enum_.rs

1use syn::parse_quote;
2use tonneau_cel::CelValue;
3
4use super::Function;
5use crate::codegen::cel::compiler::{
6    CompileError, CompiledExpr, CompilerCtx, ConstantCompiledExpr, RuntimeCompiledExpr,
7};
8use crate::codegen::cel::types::CelType;
9use crate::types::{ProtoModifiedValueType, ProtoPath, ProtoType, ProtoValueType};
10
11#[derive(Debug, Clone, Default)]
12pub(crate) struct Enum(pub Option<ProtoPath>);
13
14impl Function for Enum {
15    fn name(&self) -> &'static str {
16        "enum"
17    }
18
19    fn syntax(&self) -> &'static str {
20        "<this>.enum() | <this>.enum(<path>)"
21    }
22
23    fn compile(&self, ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
24        let Some(this) = ctx.this.as_ref() else {
25            return Err(CompileError::syntax("missing this", self));
26        };
27
28        if ctx.args.len() > 1 {
29            return Err(CompileError::syntax("invalid number of arguments", self));
30        }
31
32        let enum_path = if let Some(arg) = ctx.args.first() {
33            ctx.resolve(arg)?
34        } else {
35            match (&this, &self.0) {
36                (
37                    CompiledExpr::Runtime(RuntimeCompiledExpr {
38                        ty:
39                            CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Optional(
40                                ProtoValueType::Enum(path),
41                            )))
42                            | CelType::Proto(ProtoType::Value(ProtoValueType::Enum(path))),
43                        ..
44                    }),
45                    _,
46                )
47                | (_, Some(path)) => CompiledExpr::Constant(ConstantCompiledExpr {
48                    value: CelValue::String(path.0.clone().into()),
49                }),
50                _ => {
51                    return Err(CompileError::syntax(
52                        "unable to determine enum type, try providing an explicit path",
53                        self,
54                    ));
55                }
56            }
57        };
58
59        let this = this.clone().into_cel()?;
60        let enum_path = enum_path.into_cel()?;
61
62        match (this, enum_path) {
63            (
64                CompiledExpr::Constant(ConstantCompiledExpr { value: this }),
65                CompiledExpr::Constant(ConstantCompiledExpr { value: enum_path }),
66            ) => Ok(CompiledExpr::constant(CelValue::cel_to_enum(
67                this, enum_path,
68            )?)),
69            (this, enum_path) => Ok(CompiledExpr::runtime(
70                CelType::CelValue,
71                parse_quote! {
72                    ::tonneau::__private::cel::CelValue::cel_to_enum(
73                        #this,
74                        #enum_path,
75                    )?
76                },
77            )),
78        }
79    }
80}
81
82#[cfg(test)]
83#[cfg(feature = "prost")]
84#[cfg_attr(coverage_nightly, coverage(off))]
85mod tests {
86    use syn::parse_quote;
87
88    use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
89    use crate::codegen::cel::functions::{Enum, Function};
90    use crate::codegen::cel::types::CelType;
91    use crate::extern_paths::ExternPaths;
92    use crate::path_set::PathSet;
93    use crate::types::{ProtoType, ProtoTypeRegistry, ProtoValueType};
94
95    #[test]
96    fn test_enum_syntax() {
97        let registry = ProtoTypeRegistry::new(
98            crate::Mode::Prost,
99            ExternPaths::new(crate::Mode::Prost),
100            PathSet::default(),
101        );
102        let compiler = Compiler::new(&registry);
103        let enum_ = Enum(None);
104        insta::assert_debug_snapshot!(enum_.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
105        Err(
106            InvalidSyntax {
107                message: "missing this",
108                syntax: "<this>.enum() | <this>.enum(<path>)",
109            },
110        )
111        "#);
112
113        insta::assert_debug_snapshot!(enum_.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(5)), &[])), @r#"
114        Err(
115            InvalidSyntax {
116                message: "unable to determine enum type, try providing an explicit path",
117                syntax: "<this>.enum() | <this>.enum(<path>)",
118            },
119        )
120        "#);
121
122        insta::assert_debug_snapshot!(enum_.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(5)), &[
123            cel_parser::parse("'some.Enum'").unwrap(),
124        ])), @r#"
125        Ok(
126            Constant(
127                ConstantCompiledExpr {
128                    value: Enum(
129                        CelEnum {
130                            tag: Owned(
131                                "some.Enum",
132                            ),
133                            value: 5,
134                        },
135                    ),
136                },
137            ),
138        )
139        "#);
140    }
141
142    #[test]
143    #[cfg(not(valgrind))]
144    fn test_enum_runtime() {
145        let registry = ProtoTypeRegistry::new(
146            crate::Mode::Prost,
147            ExternPaths::new(crate::Mode::Prost),
148            PathSet::default(),
149        );
150        let compiler = Compiler::new(&registry);
151
152        let string_value = CompiledExpr::runtime(
153            CelType::Proto(ProtoType::Value(ProtoValueType::Int32)),
154            parse_quote!(input),
155        );
156
157        let output = Enum(None)
158            .compile(CompilerCtx::new(
159                compiler.child(),
160                Some(string_value),
161                &[cel_parser::parse("'some.Enum'").unwrap()],
162            ))
163            .unwrap();
164
165        insta::assert_snapshot!(postcompile::compile_str!(
166            postcompile::config! {
167                test: true,
168                dependencies: vec![
169                    postcompile::Dependency::path("tonneau", "../tonneau"),
170                ],
171            },
172            quote::quote! {
173                fn to_enum(input: i32) -> Result<::tonneau::__private::cel::CelValue<'static>, ::tonneau::__private::cel::CelError<'static>> {
174                    Ok(#output)
175                }
176
177                #[test]
178                fn test_to_enum() {
179                    #[::tonneau::reexports::linkme::distributed_slice(::tonneau::__private::cel::TONNEAU_CEL_ENUM_VTABLE)]
180                    #[linkme(crate = ::tonneau::reexports::linkme)]
181                    static ENUM_VTABLE: ::tonneau::__private::cel::EnumVtable = ::tonneau::__private::cel::EnumVtable {
182                        proto_path: "some.Enum",
183                        is_valid: |_| {
184                            true
185                        },
186                        to_serde: |_| {
187                            ::tonneau::__private::cel::CelValue::String(::tonneau::__private::cel::CelString::Borrowed("SERDE"))
188                        },
189                        to_proto: |_| {
190                            ::tonneau::__private::cel::CelValue::String(::tonneau::__private::cel::CelString::Borrowed("PROTO"))
191                        }
192                    };
193
194                    ::tonneau::__private::cel::CelMode::Serde.set();
195                    assert_eq!(to_enum(1).unwrap().to_string(), "SERDE");
196                    ::tonneau::__private::cel::CelMode::Proto.set();
197                    assert_eq!(to_enum(1).unwrap().to_string(), "PROTO");
198                }
199            },
200        ));
201    }
202}