tonneau_build/codegen/cel/functions/
string.rs1use quote::quote;
2use syn::parse_quote;
3use tonneau_cel::CelValue;
4
5use super::Function;
6use crate::codegen::cel::compiler::{
7 CompileError, CompiledExpr, Compiler, CompilerCtx, CompilerTarget, ConstantCompiledExpr,
8 RuntimeCompiledExpr,
9};
10use crate::codegen::cel::types::CelType;
11
12#[derive(Debug, Clone, Default)]
13pub(crate) struct String;
14
15fn cel_to_string(ctx: &Compiler, value: &CelValue<'static>) -> CompiledExpr {
16 match value {
17 CelValue::List(list) => {
18 let items: Vec<_> = list.iter().map(|item| cel_to_string(ctx, item)).collect();
19 if items
20 .iter()
21 .any(|item| matches!(item, CompiledExpr::Runtime(_)))
22 {
23 CompiledExpr::runtime(
24 CelType::CelValue,
25 parse_quote!({
26 ::tonneau::__private::cel::CelValue::cel_to_string(::tonneau::__private::cel::CelValue::List([
27 #(#items),*
28 ].into_iter().collect()))
29 }),
30 )
31 } else {
32 CompiledExpr::constant(CelValue::cel_to_string(CelValue::List(
33 items
34 .into_iter()
35 .map(|i| match i {
36 CompiledExpr::Constant(ConstantCompiledExpr { value }) => value,
37 _ => unreachable!(),
38 })
39 .collect(),
40 )))
41 }
42 }
43 CelValue::Map(map) => {
44 let items: Vec<_> = map
45 .iter()
46 .map(|(key, value)| (cel_to_string(ctx, key), cel_to_string(ctx, value)))
47 .collect();
48 if items.iter().any(|(key, value)| {
49 matches!(key, CompiledExpr::Runtime(_)) || matches!(value, CompiledExpr::Runtime(_))
50 }) {
51 let items = items.iter().map(|(key, value)| quote!((#key, #value)));
52 CompiledExpr::runtime(
53 CelType::CelValue,
54 parse_quote!({
55 ::tonneau::__private::cel::CelValue::cel_to_string(::tonneau::__private::cel::CelValue::Map([
56 #(#items),*
57 ].into_iter().collect()))
58 }),
59 )
60 } else {
61 CompiledExpr::constant(CelValue::cel_to_string(CelValue::Map(
62 items
63 .into_iter()
64 .map(|i| match i {
65 (
66 CompiledExpr::Constant(ConstantCompiledExpr { value: key }),
67 CompiledExpr::Constant(ConstantCompiledExpr { value }),
68 ) => (key, value),
69 _ => unreachable!(),
70 })
71 .collect(),
72 )))
73 }
74 }
75 CelValue::Enum(cel_enum) => {
76 let Some((proto_name, proto_enum)) = ctx
77 .registry()
78 .get_enum(&cel_enum.tag)
79 .and_then(|e| e.variants.iter().find(|(_, v)| v.value == cel_enum.value))
80 else {
81 return CompiledExpr::constant(CelValue::cel_to_string(cel_enum.value));
82 };
83
84 let serde_name = &proto_enum.options.serde_name;
85
86 match ctx.target() {
87 Some(CompilerTarget::Serde) => {
88 CompiledExpr::constant(CelValue::String(serde_name.clone().into()))
89 }
90 Some(CompilerTarget::Proto) => {
91 CompiledExpr::constant(CelValue::String(proto_name.clone().into()))
92 }
93 None => CompiledExpr::runtime(
94 CelType::CelValue,
95 parse_quote! {
96 match ::tonneau::__private::cel::CelMode::current() {
97 ::tonneau::__private::cel::CelMode::Serde => ::tonneau::__private::cel::CelValueConv::conv(#serde_name),
98 ::tonneau::__private::cel::CelMode::Proto => ::tonneau::__private::cel::CelValueConv::conv(#proto_name),
99 }
100 },
101 ),
102 }
103 }
104 v @ (CelValue::Bool(_)
105 | CelValue::Bytes(_)
106 | CelValue::Duration(_)
107 | CelValue::Null
108 | CelValue::Number(_)
109 | CelValue::String(_)
110 | CelValue::Timestamp(_)) => CompiledExpr::constant(CelValue::cel_to_string(v.clone())),
111 }
112}
113
114impl Function for String {
115 fn name(&self) -> &'static str {
116 "string"
117 }
118
119 fn syntax(&self) -> &'static str {
120 "<this>.string()"
121 }
122
123 fn compile(&self, mut ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
124 let Some(this) = ctx.this.take() else {
125 return Err(CompileError::syntax("missing this", self));
126 };
127
128 if !ctx.args.is_empty() {
129 return Err(CompileError::syntax("takes no arguments", self));
130 }
131
132 match this.into_cel()? {
133 CompiledExpr::Constant(ConstantCompiledExpr { value }) => {
134 Ok(cel_to_string(&ctx, &value))
135 }
136 CompiledExpr::Runtime(RuntimeCompiledExpr { expr, .. }) => Ok(CompiledExpr::runtime(
137 CelType::CelValue,
138 parse_quote!(::tonneau::__private::cel::CelValue::cel_to_string(#expr)),
139 )),
140 }
141 }
142}
143
144#[cfg(test)]
145#[cfg(feature = "prost")]
146#[cfg_attr(coverage_nightly, coverage(off))]
147mod tests {
148 use syn::parse_quote;
149 use tonneau_cel::CelValue;
150
151 use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
152 use crate::codegen::cel::functions::{Function, String};
153 use crate::codegen::cel::types::CelType;
154 use crate::extern_paths::ExternPaths;
155 use crate::path_set::PathSet;
156 use crate::types::{ProtoType, ProtoTypeRegistry, ProtoValueType};
157
158 #[test]
159 fn test_string_syntax() {
160 let registry = ProtoTypeRegistry::new(
161 crate::Mode::Prost,
162 ExternPaths::new(crate::Mode::Prost),
163 PathSet::default(),
164 );
165 let compiler = Compiler::new(®istry);
166 insta::assert_debug_snapshot!(String.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
167 Err(
168 InvalidSyntax {
169 message: "missing this",
170 syntax: "<this>.string()",
171 },
172 )
173 "#);
174
175 insta::assert_debug_snapshot!(String.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("13".into()))), &[])), @r#"
176 Ok(
177 Constant(
178 ConstantCompiledExpr {
179 value: String(
180 Borrowed(
181 "13",
182 ),
183 ),
184 },
185 ),
186 )
187 "#);
188
189 insta::assert_debug_snapshot!(String.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::List(Default::default()))), &[
190 cel_parser::parse("1 + 1").unwrap(), ])), @r#"
192 Err(
193 InvalidSyntax {
194 message: "takes no arguments",
195 syntax: "<this>.string()",
196 },
197 )
198 "#);
199 }
200
201 #[test]
202 #[cfg(not(valgrind))]
203 fn test_string_runtime() {
204 let registry = ProtoTypeRegistry::new(
205 crate::Mode::Prost,
206 ExternPaths::new(crate::Mode::Prost),
207 PathSet::default(),
208 );
209 let compiler = Compiler::new(®istry);
210
211 let string_value = CompiledExpr::runtime(
212 CelType::Proto(ProtoType::Value(ProtoValueType::String)),
213 parse_quote!(input),
214 );
215
216 let output = String
217 .compile(CompilerCtx::new(compiler.child(), Some(string_value), &[]))
218 .unwrap();
219
220 insta::assert_snapshot!(postcompile::compile_str!(
221 postcompile::config! {
222 test: true,
223 dependencies: vec![
224 postcompile::Dependency::path("tonneau", "../tonneau"),
225 ],
226 },
227 quote::quote! {
228 fn to_string(input: &str) -> Result<::tonneau::__private::cel::CelValue<'_>, ::tonneau::__private::cel::CelError<'_>> {
229 Ok(#output)
230 }
231
232 #[test]
233 fn test_to_int() {
234 assert_eq!(to_string("55").unwrap(), ::tonneau::__private::cel::CelValueConv::conv("55"));
235 }
236 },
237 ));
238 }
239}