/src/cel-rust/cel/src/env.rs
Line | Count | Source |
1 | | use crate::common::{ |
2 | | decls::{FunctionDecl, Signature}, |
3 | | functions::{Function, Op}, |
4 | | types::{self, Type}, |
5 | | value::CowVal, |
6 | | }; |
7 | | use crate::container::Container; |
8 | | use crate::parser::{Macro, Macros, Parser}; |
9 | | use crate::registry::{TypeDecl, TypeRegistry}; |
10 | | use crate::runtime::RuntimeOptions; |
11 | | use crate::{common::types::CelStruct, common::value::Val, ExecutionError, StructType}; |
12 | | use crate::{DeclarationError, Library, ParseErrors, Program}; |
13 | | use std::collections::{ |
14 | | btree_map::Entry::{Occupied, Vacant}, |
15 | | BTreeMap, BTreeSet, |
16 | | }; |
17 | | use std::sync::Arc; |
18 | | |
19 | | /// An environment for the CEL execution. |
20 | | /// |
21 | | /// This is where functions, overloads, and custom structs are defined. |
22 | | /// |
23 | | /// # Example |
24 | | /// |
25 | | /// ## Custom Structs |
26 | | /// |
27 | | /// You can define custom struct types that can be instantiated from CEL expressions. |
28 | | /// |
29 | | /// ``` |
30 | | /// use cel::{Env, StructDef, common::types, common::types::CelString}; |
31 | | /// |
32 | | /// let mut env = Env::stdlib(); |
33 | | /// env.add_type( |
34 | | /// StructDef::new("cel.MyStruct".to_owned()) |
35 | | /// .add_field("some_field".to_owned(), types::STRING_TYPE) |
36 | | /// .add_field_with_default("with_default".to_owned(), Box::new(CelString::from("default_value"))) |
37 | | /// ).unwrap(); |
38 | | /// ``` |
39 | | /// |
40 | | /// ## Function Overloads |
41 | | /// |
42 | | /// You can add custom function overloads to the environment. |
43 | | /// |
44 | | /// ``` |
45 | | /// use cel::{Env, common::types, common::value::CowVal}; |
46 | | /// |
47 | | /// let mut env = Env::stdlib(); |
48 | | /// |
49 | | /// // Define a function that takes an integer and returns its square. |
50 | | /// env.add_overload("square", "int_square", vec![types::INT_TYPE], |args| { |
51 | | /// let val = args[0].downcast_ref::<types::CelInt>().unwrap(); |
52 | | /// Ok(CowVal::owned(types::CelInt::from(val.inner() * val.inner()))) |
53 | | /// }).unwrap(); |
54 | | /// ``` |
55 | | pub struct Env { |
56 | | functions: BTreeMap<String, FunctionDecl>, |
57 | | namespaces: BTreeSet<String>, |
58 | | types: TypeRegistry, |
59 | | macros: Arc<Macros>, |
60 | | options: RuntimeOptions, |
61 | | error_on_duplicate_map_keys: bool, |
62 | | optional: bool, |
63 | | container: Container, |
64 | | libraries: BTreeSet<String>, |
65 | | } |
66 | | |
67 | | /// The name the standard library is added under, as in cel-go. |
68 | | const STANDARD_LIBRARY: &str = "cel.lib.std"; |
69 | | |
70 | | /// The name the `optional` library is added under, as in cel-go. |
71 | | const OPTIONAL_LIBRARY: &str = "cel.lib.optional"; |
72 | | |
73 | | impl Default for Env { |
74 | 0 | fn default() -> Self { |
75 | 0 | Env { |
76 | 0 | functions: BTreeMap::new(), |
77 | 0 | namespaces: BTreeSet::new(), |
78 | 0 | types: TypeRegistry::default(), |
79 | 0 | macros: Arc::default(), |
80 | 0 | options: RuntimeOptions::default(), |
81 | 0 | error_on_duplicate_map_keys: true, |
82 | 0 | optional: true, |
83 | 0 | container: Container::default(), |
84 | 0 | libraries: BTreeSet::new(), |
85 | 0 | } |
86 | 0 | } |
87 | | } |
88 | | |
89 | | impl Env { |
90 | | /// Returns the standard library environment. |
91 | | /// |
92 | | /// This environment contains all the standard functions and types as defined by the |
93 | | /// CEL specification. |
94 | 0 | pub fn stdlib() -> Env { |
95 | 0 | Env { |
96 | 0 | macros: Macros::standard(), |
97 | 0 | ..Default::default() |
98 | 0 | } |
99 | 0 | .with_stdlib() |
100 | 0 | } |
101 | | |
102 | | /// Registers the standard types and functions, as defined by the CEL |
103 | | /// specification, on this environment and returns it. |
104 | | /// |
105 | | /// Unlike [`Env::stdlib`], it adds no macros: on an [`Env::default`], |
106 | | /// `has`, `all`, `exists`, `exists_one`, `map` and `filter` are left as |
107 | | /// the calls they are written as. |
108 | | /// |
109 | | /// The `duration` and `timestamp` types and functions need the `chrono` |
110 | | /// feature; the `optional` ones are only registered while this |
111 | | /// environment supports optional values, as it does by default: see |
112 | | /// [`Env::with_optional_support`]. |
113 | | /// |
114 | | /// They are added as the libraries `cel.lib.std` and `cel.lib.optional`, |
115 | | /// see [`Env::has_library`], once each: calling this on an |
116 | | /// [`Env::stdlib`], or twice, registers nothing again. |
117 | | /// |
118 | | /// # Panics |
119 | | /// |
120 | | /// Panics if one of the standard overloads was declared some other way, |
121 | | /// as with [`Env::add_overload`], or if another type is already |
122 | | /// registered under one of the standard types' names. |
123 | | /// |
124 | | /// # Example |
125 | | /// |
126 | | /// ``` |
127 | | /// use cel::{Context, Env, Value}; |
128 | | /// use std::sync::Arc; |
129 | | /// |
130 | | /// let env = Env::default().with_stdlib(); |
131 | | /// let program = env.compile("size('abc') == 3").unwrap(); |
132 | | /// let context = Context::with_env(Arc::new(env)); |
133 | | /// assert_eq!(program.execute(&context), Ok(Value::Bool(true))); |
134 | | /// ``` |
135 | 0 | pub fn with_stdlib(mut self) -> Self { |
136 | 0 | if self.libraries.insert(STANDARD_LIBRARY.to_owned()) { |
137 | 0 | types::bool::stdlib(&mut self); |
138 | 0 | types::bytes::stdlib(&mut self); |
139 | 0 | types::double::stdlib(&mut self); |
140 | 0 | types::r#dyn::stdlib(&mut self); |
141 | 0 | types::int::stdlib(&mut self); |
142 | 0 | types::list::stdlib(&mut self); |
143 | 0 | types::map::stdlib(&mut self); |
144 | 0 | types::null::stdlib(&mut self); |
145 | 0 | types::string::stdlib(&mut self); |
146 | 0 | types::type_val::stdlib(&mut self); |
147 | 0 | types::uint::stdlib(&mut self); |
148 | | |
149 | | #[cfg(feature = "chrono")] |
150 | 0 | { |
151 | 0 | types::duration::stdlib(&mut self); |
152 | 0 | types::timestamp::stdlib(&mut self); |
153 | 0 | } |
154 | 0 | } |
155 | 0 | if self.optional && self.libraries.insert(OPTIONAL_LIBRARY.to_owned()) { |
156 | 0 | types::optional::stdlib(&mut self); |
157 | 0 | } |
158 | 0 | self |
159 | 0 | } |
160 | | |
161 | | /// Sets whether this environment supports optional values, as it does by |
162 | | /// default, and returns it. |
163 | | /// |
164 | | /// Without, the parsers it builds with [`Env::parser`], and so |
165 | | /// [`Env::compile`], reject the optional syntax (`a.?b`, `a[?b]`, `[?a]` |
166 | | /// and `{?k: v}`) as unsupported, and [`Env::with_stdlib`] leaves out the |
167 | | /// `optional` library (`optional.of`, `optional.none`, `hasValue`, ...). |
168 | | /// |
169 | | /// That library is registered when [`Env::with_stdlib`] runs: disable |
170 | | /// support before calling it. On an [`Env::stdlib`], or after |
171 | | /// [`Env::with_stdlib`], this only disables the syntax. |
172 | | /// |
173 | | /// # Example |
174 | | /// |
175 | | /// ``` |
176 | | /// use cel::{Context, Env}; |
177 | | /// use std::sync::Arc; |
178 | | /// |
179 | | /// let env = Env::default().with_optional_support(false).with_stdlib(); |
180 | | /// assert!(env.compile("{'a': 1}.?a").is_err()); |
181 | | /// |
182 | | /// let program = env.compile("optional.of(1).hasValue()").unwrap(); |
183 | | /// let context = Context::with_env(Arc::new(env)); |
184 | | /// assert!(program.execute(&context).is_err()); |
185 | | /// ``` |
186 | 0 | pub fn with_optional_support(mut self, optional: bool) -> Self { |
187 | 0 | self.optional = optional; |
188 | 0 | self |
189 | 0 | } |
190 | | |
191 | | /// Returns a parser that expands the macros of this environment. |
192 | | /// |
193 | | /// [`Env::stdlib`] has the standard macros (`has`, `all`, `exists`, |
194 | | /// `exists_one`, `map` and `filter`); an [`Env::default`] has none, so its |
195 | | /// parser leaves such calls as they are written. |
196 | | /// |
197 | | /// # Example |
198 | | /// |
199 | | /// ``` |
200 | | /// use cel::{Context, Env, Value}; |
201 | | /// |
202 | | /// let env = Env::stdlib(); |
203 | | /// let expr = env.parser().parse("[1, 2, 3].exists(x, x > 2)").unwrap(); |
204 | | /// assert_eq!(Value::resolve(&expr, &Context::default()), Ok(Value::Bool(true))); |
205 | | /// ``` |
206 | 0 | pub fn parser(&self) -> Parser { |
207 | 0 | Parser::new() |
208 | 0 | .enable_optional_syntax(self.optional) |
209 | 0 | .with_macros(Arc::clone(&self.macros)) |
210 | 0 | } |
211 | | |
212 | | /// Compiles `source` into a [`Program`], expanding the macros of this |
213 | | /// environment: the standard ones of [`Env::stdlib`], and those added with |
214 | | /// [`Env::add_macro`], by extensions included. |
215 | | /// |
216 | | /// Macros are expanded while compiling: the program doesn't depend on the |
217 | | /// environment afterwards. |
218 | | /// |
219 | | /// # Errors |
220 | | /// |
221 | | /// Fails with the [`ParseErrors`] of `source`, a macro's included. |
222 | | /// |
223 | | /// # Example |
224 | | /// |
225 | | /// ``` |
226 | | /// use cel::{Context, Env, Value}; |
227 | | /// use std::sync::Arc; |
228 | | /// |
229 | | /// let env = Env::stdlib(); |
230 | | /// let program = env.compile("[1, 2, 3].exists(x, x > 2)").unwrap(); |
231 | | /// let context = Context::with_env(Arc::new(env)); |
232 | | /// assert_eq!(program.execute(&context), Ok(Value::Bool(true))); |
233 | | /// ``` |
234 | 0 | pub fn compile(&self, source: &str) -> Result<Program, ParseErrors> { |
235 | 0 | Program::parse_with(self.parser(), source) |
236 | 0 | } |
237 | | |
238 | | /// Adds a macro, expanded by the programs this environment compiles with |
239 | | /// [`Env::compile`], and by the parsers it builds with [`Env::parser`]; |
240 | | /// [`Program::compile`] only expands the standard ones. |
241 | | /// |
242 | | /// # Errors |
243 | | /// |
244 | | /// Fails with [`DeclarationError::DuplicateMacro`] if a macro for the same |
245 | | /// function, called the same way (globally or on a target) with as many |
246 | | /// arguments, or with any number of them, is already added: the standard |
247 | | /// ones of [`Env::stdlib`] included. A macro for any number of arguments |
248 | | /// and one for an exact number coexist: the latter wins for its calls. |
249 | | /// |
250 | | /// # Example |
251 | | /// |
252 | | /// ``` |
253 | | /// use cel::common::ast::{operators, CallExpr, Expr}; |
254 | | /// use cel::parser::Macro; |
255 | | /// use cel::{Context, Env, Value}; |
256 | | /// use std::sync::Arc; |
257 | | /// |
258 | | /// // `implies(a, b)` is parsed as `!a || b`: true whenever `a` is false, |
259 | | /// // whatever `b` evaluates to. |
260 | | /// let implies = Macro::global("implies", 2, |helper, _target, args| { |
261 | | /// let b = args.pop().unwrap(); |
262 | | /// let a = args.pop().unwrap(); |
263 | | /// let not_a = helper.next_expr(Expr::Call(CallExpr { |
264 | | /// func_name: operators::LOGICAL_NOT.to_string(), |
265 | | /// target: None, |
266 | | /// args: vec![a], |
267 | | /// })); |
268 | | /// Ok(Some(helper.next_expr(Expr::Call(CallExpr { |
269 | | /// func_name: operators::LOGICAL_OR.to_string(), |
270 | | /// target: None, |
271 | | /// args: vec![not_a, b], |
272 | | /// })))) |
273 | | /// }); |
274 | | /// |
275 | | /// let mut env = Env::stdlib(); |
276 | | /// env.add_macro(implies).unwrap(); |
277 | | /// let program = env.compile("implies(false, 1 / 0 == 1)").unwrap(); |
278 | | /// let context = Context::with_env(Arc::new(env)); |
279 | | /// assert_eq!(program.execute(&context), Ok(Value::Bool(true))); |
280 | | /// ``` |
281 | 0 | pub fn add_macro(&mut self, m: Macro) -> Result<(), DeclarationError> { |
282 | | // The standard macros are shared by every `Env::stdlib()` and default |
283 | | // parser: the first macro added copies them for this environment. |
284 | 0 | Arc::make_mut(&mut self.macros).add(m) |
285 | 0 | } |
286 | | |
287 | | /// Adds a global function overload to the environment. |
288 | | /// |
289 | | /// The name is the function name (e.g., `_==_`, `size`). |
290 | | /// The id is the unique identifier for this overload (e.g., `equals_int64`). |
291 | | /// The args are the expected argument types, or a [`Signature`] to also |
292 | | /// declare the result type, which is otherwise `dyn`. |
293 | | /// The op is the function implementation. |
294 | | /// |
295 | | /// # Errors |
296 | | /// |
297 | | /// Fails with [`DeclarationError::DuplicateOverload`] if an overload of that |
298 | | /// name is already declared with the same id, or with the same signature, and |
299 | | /// with [`DeclarationError::OverlappingOverload`] if a call could also resolve |
300 | | /// to one already declared. |
301 | 0 | pub fn add_overload( |
302 | 0 | &mut self, |
303 | 0 | name: &str, |
304 | 0 | id: &str, |
305 | 0 | args: impl Into<Signature>, |
306 | 0 | op: Function, |
307 | 0 | ) -> Result<(), DeclarationError> { |
308 | 0 | self.declare_overload(name, id, args.into(), Op::Function(op)) |
309 | 0 | } Unexecuted instantiation: <cel::env::Env>::add_overload::<alloc::vec::Vec<cel::common::types::Type>> Unexecuted instantiation: <cel::env::Env>::add_overload::<cel::common::decls::Signature> |
310 | | |
311 | | /// Adds a global function overload, as [`Env::add_overload`] does, that a |
312 | | /// closure implements: one that can capture, say the settings of the |
313 | | /// [`Library`] declaring it. |
314 | | /// |
315 | | /// Write the closure in the call, as below, or return it from a function |
316 | | /// declared to return `impl for<'b, 'v> Fn(..) -> ..`: one bound to a |
317 | | /// variable first isn't inferred to take arguments of any lifetimes. |
318 | | /// |
319 | | /// ``` |
320 | | /// use cel::{Context, Env, Value, common::types, common::value::CowVal}; |
321 | | /// use std::sync::Arc; |
322 | | /// |
323 | | /// let mut env = Env::stdlib(); |
324 | | /// let factor = 3; |
325 | | /// env.add_overload_with("scale", "scale_int", vec![types::INT_TYPE], move |args| { |
326 | | /// let val = args[0].downcast_ref::<types::CelInt>().unwrap(); |
327 | | /// Ok(CowVal::owned(types::CelInt::from(val.inner() * factor))) |
328 | | /// }).unwrap(); |
329 | | /// |
330 | | /// let program = env.compile("scale(2)").unwrap(); |
331 | | /// let context = Context::with_env(Arc::new(env)); |
332 | | /// assert_eq!(program.execute(&context), Ok(Value::Int(6))); |
333 | | /// ``` |
334 | | /// |
335 | | /// # Errors |
336 | | /// |
337 | | /// Fails as [`Env::add_overload`] does. |
338 | 0 | pub fn add_overload_with<F>( |
339 | 0 | &mut self, |
340 | 0 | name: &str, |
341 | 0 | id: &str, |
342 | 0 | args: impl Into<Signature>, |
343 | 0 | op: F, |
344 | 0 | ) -> Result<(), DeclarationError> |
345 | 0 | where |
346 | 0 | F: for<'b, 'v> Fn(Vec<CowVal<'b, 'v>>) -> Result<CowVal<'b, 'v>, ExecutionError> |
347 | 0 | + Send |
348 | 0 | + Sync |
349 | 0 | + std::panic::UnwindSafe |
350 | 0 | + std::panic::RefUnwindSafe |
351 | 0 | + 'static, |
352 | | { |
353 | 0 | self.declare_overload(name, id, args.into(), Op::Closure(Box::new(op))) |
354 | 0 | } |
355 | | |
356 | 0 | fn declare_overload( |
357 | 0 | &mut self, |
358 | 0 | name: &str, |
359 | 0 | id: &str, |
360 | 0 | signature: Signature, |
361 | 0 | op: Op, |
362 | 0 | ) -> Result<(), DeclarationError> { |
363 | 0 | match self.functions.entry(name.to_owned()) { |
364 | 0 | Vacant(vacant_entry) => { |
365 | 0 | let mut value = FunctionDecl::new(name); |
366 | 0 | value.add_overload(id.to_string(), false, signature, op)?; |
367 | 0 | vacant_entry.insert(value); |
368 | 0 | if let Some((namespace, _)) = name.split_once('.') { |
369 | 0 | self.namespaces.insert(namespace.to_owned()); |
370 | 0 | } |
371 | 0 | Ok(()) |
372 | | } |
373 | 0 | Occupied(occupied_entry) => { |
374 | 0 | occupied_entry |
375 | 0 | .into_mut() |
376 | 0 | .add_overload(id.to_string(), false, signature, op) |
377 | | } |
378 | | } |
379 | 0 | } |
380 | | |
381 | 0 | pub(crate) fn has_namespace(&self, namespace: &str) -> bool { |
382 | 0 | self.namespaces.contains(namespace) |
383 | 0 | } |
384 | | |
385 | | /// Finds a global function overload that matches the given name and arguments. |
386 | | /// |
387 | | /// `None` as well when that overload is implemented by a closure, added |
388 | | /// with [`Env::add_overload_with`]: it has no [`Function`] to return. |
389 | 0 | pub fn find_overload(&self, name: &str, args: &[CowVal<'_, '_>]) -> Option<Function> { |
390 | 0 | match self.functions.get(name) { |
391 | 0 | None => None, |
392 | 0 | Some(fn_decl) => fn_decl.find_overload(false, args), |
393 | | } |
394 | 0 | } |
395 | | |
396 | | /// The function of that name, as declared by its overloads, if it has any. |
397 | 0 | pub fn function(&self, name: &str) -> Option<&FunctionDecl> { |
398 | 0 | self.functions.get(name) |
399 | 0 | } |
400 | | |
401 | | /// The implementation of the overload a call of `name` with `args` |
402 | | /// resolves to: a member overload's if `member_function`, with the target |
403 | | /// as the first of `args`. |
404 | 0 | pub(crate) fn find_op( |
405 | 0 | &self, |
406 | 0 | name: &str, |
407 | 0 | member_function: bool, |
408 | 0 | args: &[CowVal<'_, '_>], |
409 | 0 | ) -> Option<&Op> { |
410 | 0 | self.functions.get(name)?.find_op(member_function, args) |
411 | 0 | } |
412 | | |
413 | 0 | pub(crate) fn has_overload(&self, name: &str) -> bool { |
414 | 0 | self.functions |
415 | 0 | .get(name) |
416 | 0 | .is_some_and(|function| function.has_overload(false)) |
417 | 0 | } |
418 | | |
419 | | /// Adds a member function overload to the environment. |
420 | | /// |
421 | | /// A member function is one that is called using the receiver syntax (e.g., `x.matches(y)`). |
422 | | /// The name is the function name. |
423 | | /// The id is the unique identifier for this overload. |
424 | | /// The target is the type of the receiver. |
425 | | /// The args are the expected argument types (excluding the receiver), or a |
426 | | /// [`Signature`] to also declare the result type, which is otherwise `dyn`. |
427 | | /// The op is the function implementation. |
428 | | /// |
429 | | /// # Errors |
430 | | /// |
431 | | /// Fails with [`DeclarationError::DuplicateOverload`] if an overload of that |
432 | | /// name is already declared with the same id, or with the same signature, and |
433 | | /// with [`DeclarationError::OverlappingOverload`] if a call could also resolve |
434 | | /// to one already declared. |
435 | 0 | pub fn add_member_overload( |
436 | 0 | &mut self, |
437 | 0 | name: &str, |
438 | 0 | id: &str, |
439 | 0 | target: Type, |
440 | 0 | args: impl Into<Signature>, |
441 | 0 | op: Function, |
442 | 0 | ) -> Result<(), DeclarationError> { |
443 | 0 | let signature = args.into().with_receiver(target); |
444 | 0 | let op = Op::Function(op); |
445 | 0 | match self.functions.entry(name.to_owned()) { |
446 | 0 | Vacant(vacant_entry) => { |
447 | 0 | let mut value = FunctionDecl::new(name); |
448 | 0 | value.add_overload(id.to_string(), true, signature, op)?; |
449 | 0 | vacant_entry.insert(value); |
450 | 0 | Ok(()) |
451 | | } |
452 | 0 | Occupied(occupied_entry) => { |
453 | 0 | occupied_entry |
454 | 0 | .into_mut() |
455 | 0 | .add_overload(id.to_string(), true, signature, op) |
456 | | } |
457 | | } |
458 | 0 | } Unexecuted instantiation: <cel::env::Env>::add_member_overload::<alloc::vec::Vec<cel::common::types::Type>> Unexecuted instantiation: <cel::env::Env>::add_member_overload::<cel::common::decls::Signature> |
459 | | |
460 | 0 | pub(crate) fn has_member_overload(&self, name: &str) -> bool { |
461 | 0 | self.functions |
462 | 0 | .get(name) |
463 | 0 | .is_some_and(|function| function.has_overload(true)) |
464 | 0 | } |
465 | | |
466 | | /// Registers a type with the environment, so that expressions can refer |
467 | | /// to it by name, and, for a struct type, construct it. |
468 | | /// |
469 | | /// The name resolves to the type value, unless a variable of the same name |
470 | | /// shadows it. Values need not be registered to be evaluated: registering |
471 | | /// their type is what lets an expression name it. |
472 | | /// |
473 | | /// ``` |
474 | | /// use cel::{Context, Env, Value}; |
475 | | /// use cel::common::types::Type; |
476 | | /// use std::sync::Arc; |
477 | | /// |
478 | | /// let mut env = Env::stdlib(); |
479 | | /// env.add_type(Type::new_opaque_type("Ip")).unwrap(); |
480 | | /// let program = env.compile("type(Ip) == type").unwrap(); |
481 | | /// let context = Context::with_env(Arc::new(env)); |
482 | | /// |
483 | | /// assert_eq!(program.execute(&context), Ok(Value::Bool(true))); |
484 | | /// ``` |
485 | | /// |
486 | | /// Registering a `StructType`, e.g. a `StructDef`, also lets struct |
487 | | /// literals construct it: |
488 | | /// `cel.MyStruct{some_field: 'value'}`. |
489 | | /// |
490 | | /// # Errors |
491 | | /// |
492 | | /// Fails with [`DeclarationError::TypeConflict`] if another type, or |
493 | | /// another struct type, is already registered under that name, and with |
494 | | /// [`DeclarationError::InvalidTypeName`] if the name is not an identifier, |
495 | | /// or several separated by dots. Registering an equal type again is fine, |
496 | | /// and so is registering a struct type whose type was registered alone. |
497 | 0 | pub fn add_type(&mut self, t: impl Into<TypeDecl>) -> Result<(), DeclarationError> { |
498 | 0 | self.types.register(t) |
499 | 0 | } |
500 | | |
501 | | /// The runtime policy applied to every evaluation under this environment. |
502 | 0 | pub fn options(&self) -> &RuntimeOptions { |
503 | 0 | &self.options |
504 | 0 | } |
505 | | |
506 | | /// Replaces the runtime policy applied to every evaluation under this environment. |
507 | | /// |
508 | | /// # Example |
509 | | /// ``` |
510 | | /// use cel::{Env, RuntimeOptions}; |
511 | | /// |
512 | | /// let mut env = Env::stdlib(); |
513 | | /// env.set_options(RuntimeOptions::default().with_max_iterations(10_000)); |
514 | | /// assert_eq!(env.options().max_iterations(), 10_000); |
515 | | /// ``` |
516 | 0 | pub fn set_options(&mut self, options: RuntimeOptions) { |
517 | 0 | self.options = options; |
518 | 0 | } |
519 | | |
520 | | /// Sets the container names are resolved against: with container `x`, an |
521 | | /// identifier, qualified identifier, struct type name or function name |
522 | | /// `y` also resolves to `x.y`, ahead of the plain `y`. In container `a.b`, |
523 | | /// `y` is tried as `a.b.y`, `a.y`, then `y`; a leading dot, as in `.y`, |
524 | | /// makes the name absolute, so only `y` is tried. |
525 | | /// |
526 | | /// Each call replaces the container; an empty name clears it. |
527 | | /// |
528 | | /// ``` |
529 | | /// use cel::{Context, Env, Value}; |
530 | | /// use std::sync::Arc; |
531 | | /// |
532 | | /// let mut env = Env::stdlib(); |
533 | | /// env.set_container("x").unwrap(); |
534 | | /// let program = env.compile("y").unwrap(); |
535 | | /// let mut context = Context::with_env(Arc::new(env)); |
536 | | /// context.add_variable_from_value("x.y", true); |
537 | | /// |
538 | | /// assert_eq!(program.execute(&context), Ok(Value::Bool(true))); |
539 | | /// ``` |
540 | | /// |
541 | | /// # Errors |
542 | | /// |
543 | | /// Fails with [`DeclarationError::InvalidContainerName`] if `name` is |
544 | | /// neither empty nor an identifier, or several separated by dots; a |
545 | | /// leading dot is rejected. |
546 | 0 | pub fn set_container(&mut self, name: &str) -> Result<(), DeclarationError> { |
547 | 0 | self.container = Container::new(name)?; |
548 | 0 | Ok(()) |
549 | 0 | } |
550 | | |
551 | | /// The name of the container, empty if none is set. |
552 | 0 | pub fn container_name(&self) -> &str { |
553 | 0 | self.container.name() |
554 | 0 | } |
555 | | |
556 | 0 | pub(crate) fn container(&self) -> &Container { |
557 | 0 | &self.container |
558 | 0 | } |
559 | | |
560 | | /// The types registered with the environment. |
561 | 0 | pub fn types(&self) -> &TypeRegistry { |
562 | 0 | &self.types |
563 | 0 | } |
564 | | |
565 | | /// Adds an extension library, such as [`extensions::strings`], by |
566 | | /// handing it this environment to register its types, overloads and |
567 | | /// macros on. Compile with [`Env::compile`] for the macros to be expanded. |
568 | | /// |
569 | | /// The extensions of this crate add a [`Library`], with its default |
570 | | /// settings: adding one again changes nothing. To add one with settings |
571 | | /// of its own, see [`Env::add_library`]. |
572 | | /// |
573 | | /// ``` |
574 | | /// use cel::{extensions, Context, Env, Value}; |
575 | | /// use std::sync::Arc; |
576 | | /// |
577 | | /// let mut env = Env::stdlib(); |
578 | | /// env.add_extension(extensions::strings); |
579 | | /// let program = env.compile("'TacoCat'.lowerAscii()").unwrap(); |
580 | | /// let context = Context::with_env(Arc::new(env)); |
581 | | /// |
582 | | /// assert_eq!(program.execute(&context), Ok(Value::from("tacocat"))); |
583 | | /// ``` |
584 | | /// |
585 | | /// [`extensions::strings`]: crate::extensions::strings |
586 | | pub fn add_extension( |
587 | | &mut self, |
588 | | extension: impl FnOnce(&mut Env) -> Result<(), DeclarationError>, |
589 | | ) -> Result<(), DeclarationError> { |
590 | | extension(self) |
591 | | } |
592 | | |
593 | | /// Adds a [`Library`], by handing it this environment to register its |
594 | | /// types, overloads and macros on: this is how to add an extension with |
595 | | /// settings of its own, when [`Env::add_extension`] adds it with its |
596 | | /// default ones. |
597 | | /// |
598 | | /// A library with a [name](Library::name) is added once: adding one of a |
599 | | /// name that [is there already](Env::has_library) changes nothing, |
600 | | /// whatever its settings. |
601 | | /// |
602 | | /// ``` |
603 | | /// use cel::{extensions, Env}; |
604 | | /// |
605 | | /// let mut env = Env::stdlib(); |
606 | | /// env.add_library(extensions::Strings::default()).unwrap(); |
607 | | /// assert!(env.has_library("cel.lib.ext.strings")); |
608 | | /// // The strings library is there already: nothing is registered again. |
609 | | /// env.add_extension(extensions::strings).unwrap(); |
610 | | /// ``` |
611 | | /// |
612 | | /// # Errors |
613 | | /// |
614 | | /// Fails with the [`DeclarationError`] the library failed to register |
615 | | /// with, as when this environment already declares one of its overloads. |
616 | | /// What the library registered until then stays, but the library isn't |
617 | | /// added: this environment doesn't [have](Env::has_library) its name. |
618 | 0 | pub fn add_library(&mut self, library: impl Library) -> Result<(), DeclarationError> { |
619 | 0 | let Some(name) = library.name() else { |
620 | 0 | return library.register(self); |
621 | | }; |
622 | | // Added before it registers, as in cel-go: a library that is added |
623 | | // again while it registers, by one it adds, is there already. |
624 | 0 | if !self.libraries.insert(name.to_owned()) { |
625 | 0 | return Ok(()); |
626 | 0 | } |
627 | 0 | library.register(self).inspect_err(|_| { |
628 | 0 | self.libraries.remove(name); |
629 | 0 | }) Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::comprehensions::TwoVarComprehensions>::{closure#0}Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::math::Math>::{closure#0}Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::sets::Sets>::{closure#0}Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::lists::Lists>::{closure#0}Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::network::Network>::{closure#0}Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::strings::Strings>::{closure#0}Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::bindings::Bindings>::{closure#0}Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::encoders::Encoders>::{closure#0} |
630 | 0 | } Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::comprehensions::TwoVarComprehensions> Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::math::Math> Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::sets::Sets> Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::lists::Lists> Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::network::Network> Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::strings::Strings> Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::bindings::Bindings> Unexecuted instantiation: <cel::env::Env>::add_library::<cel::extensions::encoders::Encoders> |
631 | | |
632 | | /// Whether a library of that [name](Library::name) was added to this |
633 | | /// environment. [`Env::with_stdlib`] adds the standard library as |
634 | | /// `cel.lib.std`, and the `optional` one as `cel.lib.optional`. |
635 | | /// |
636 | | /// ``` |
637 | | /// use cel::{extensions, Env}; |
638 | | /// |
639 | | /// let mut env = Env::stdlib(); |
640 | | /// assert!(env.has_library("cel.lib.std")); |
641 | | /// assert!(!env.has_library("cel.lib.ext.strings")); |
642 | | /// env.add_extension(extensions::strings).unwrap(); |
643 | | /// assert!(env.has_library("cel.lib.ext.strings")); |
644 | | /// ``` |
645 | 0 | pub fn has_library(&self, name: &str) -> bool { |
646 | 0 | self.libraries.contains(name) |
647 | 0 | } |
648 | | |
649 | | /// The names of the libraries added to this environment, sorted. |
650 | 0 | pub fn libraries(&self) -> impl Iterator<Item = &str> { |
651 | 0 | self.libraries.iter().map(String::as_str) |
652 | 0 | } |
653 | | |
654 | | /// Sets whether a map literal that repeats a key is an error. |
655 | | /// |
656 | | /// On by default, as the spec requires. Turning it off keeps the last entry |
657 | | /// instead, so `{'a': 1, 'a': 2}` evaluates to `{'a': 2}`, which is what |
658 | | /// cel-go does. Mirrors cel-java's `CelOptions.errorOnDuplicateMapKeys`, |
659 | | /// where the shipped default (`CelOptions.DEFAULT`) also errors. |
660 | | /// |
661 | | /// Numeric keys compare by value, as the spec requires, so `{0: 1, 0u: 2}` |
662 | | /// repeats a key too, which cel-java doesn't catch. With the check off, both |
663 | | /// entries are kept, as in cel-go. |
664 | | /// |
665 | | /// ``` |
666 | | /// use cel::{Context, Env, Value}; |
667 | | /// use std::sync::Arc; |
668 | | /// |
669 | | /// let mut env = Env::stdlib(); |
670 | | /// env.set_error_on_duplicate_map_keys(false); |
671 | | /// let program = env.compile("{'a': 1, 'a': 2}['a']").unwrap(); |
672 | | /// let context = Context::with_env(Arc::new(env)); |
673 | | /// |
674 | | /// let value: Value = program.execute(&context).unwrap(); |
675 | | /// assert_eq!(value, 2.into()); |
676 | | /// ``` |
677 | 0 | pub fn set_error_on_duplicate_map_keys(&mut self, value: bool) { |
678 | 0 | self.error_on_duplicate_map_keys = value; |
679 | 0 | } |
680 | | |
681 | 0 | pub(crate) fn error_on_duplicate_map_keys(&self) -> bool { |
682 | 0 | self.error_on_duplicate_map_keys |
683 | 0 | } |
684 | | } |
685 | | |
686 | | /// A definition for a custom struct type. |
687 | | /// |
688 | | /// A struct definition defines the name of the struct, its fields, and any default values |
689 | | /// for those fields. Struct definitions are added to an [`Env`] to allow them to be |
690 | | /// instantiated from CEL expressions. |
691 | | /// |
692 | | /// # Example |
693 | | /// |
694 | | /// ``` |
695 | | /// use cel::{Env, StructDef, common::types, common::types::CelString}; |
696 | | /// |
697 | | /// let mut env = Env::stdlib(); |
698 | | /// env.add_type( |
699 | | /// StructDef::new("MyStruct".to_owned()) |
700 | | /// .add_field("some_field".to_owned(), types::STRING_TYPE) |
701 | | /// .add_field_with_default("with_default".to_owned(), Box::new(CelString::from("default_value"))) |
702 | | /// ).unwrap(); |
703 | | /// ``` |
704 | | pub struct StructDef { |
705 | | r#type: Type, |
706 | | fields: BTreeMap<String, Type>, |
707 | | defaults: BTreeMap<String, Box<dyn Val>>, |
708 | | } |
709 | | |
710 | | impl StructDef { |
711 | | /// Creates a new struct definition with the given name. |
712 | | /// |
713 | | /// The name should be the fully qualified name of the struct as it will be |
714 | | /// referenced in CEL expressions (e.g., `cel.MyStruct`). |
715 | 0 | pub fn new(name: String) -> Self { |
716 | 0 | Self { |
717 | 0 | r#type: Type::new_struct(name), |
718 | 0 | fields: Default::default(), |
719 | 0 | defaults: Default::default(), |
720 | 0 | } |
721 | 0 | } |
722 | | |
723 | | /// Adds a field to the struct definition. |
724 | | /// |
725 | | /// This method adds a field with the given name and type. When the struct is |
726 | | /// instantiated in a CEL expression, this field must be provided unless it |
727 | | /// has a default value (see [`add_field_with_default`](Self::add_field_with_default)). |
728 | 0 | pub fn add_field(self, field: String, t: Type) -> Self { |
729 | 0 | self.insert_field(field, t, None) |
730 | 0 | } |
731 | | |
732 | | /// Adds a field to the struct definition with a default value. |
733 | | /// |
734 | | /// This method adds a field with the given name and a default value. The type |
735 | | /// of the field is automatically inferred from the default value. When the |
736 | | /// struct is instantiated in a CEL expression, this field may be omitted, in |
737 | | /// which case the default value will be used. |
738 | 0 | pub fn add_field_with_default(self, field: String, default: Box<dyn Val>) -> Self { |
739 | 0 | self.insert_field(field, default.get_type().to_owned(), Some(default)) |
740 | 0 | } |
741 | | |
742 | | /// Internal method to insert a field into the struct definition. |
743 | 0 | fn insert_field(self, field: String, t: Type, default: Option<Box<dyn Val>>) -> Self { |
744 | 0 | let mut def = self; |
745 | 0 | def.fields.insert(field.clone(), t); |
746 | 0 | if let Some(default) = default { |
747 | 0 | def.defaults.insert(field, default); |
748 | 0 | } |
749 | 0 | def |
750 | 0 | } |
751 | | |
752 | | /// Creates a new instance of the struct with the given field values. |
753 | | /// |
754 | | /// This method is used internally by the CEL execution engine to instantiate |
755 | | /// a struct from a CEL expression. |
756 | | /// |
757 | | /// # Errors |
758 | | /// |
759 | | /// Missing fields will be populated with their default values if defined. |
760 | | /// Returns an error if: |
761 | | /// - A field is missing and has no default value. |
762 | | /// - A field's type does not match the type in the definition. |
763 | | /// - An unknown field name is provided. |
764 | 0 | fn new_struct<'b, 'v>( |
765 | 0 | &self, |
766 | 0 | fields: BTreeMap<String, CowVal<'b, 'v>>, |
767 | 0 | ) -> Result<CelStruct<'v>, ExecutionError> { |
768 | 0 | let name = self.r#type.name(); |
769 | 0 | let mut s = CelStruct::new(name.to_owned()); |
770 | 0 | let mut fields = fields; |
771 | 0 | for (field, default) in &self.defaults { |
772 | 0 | if let Some(value) = fields.remove(field) { |
773 | 0 | s.add_field_value(field.clone(), value); |
774 | 0 | } else { |
775 | 0 | s.add_field_value(field.clone(), CowVal::Owned(default.clone_as_boxed())); |
776 | 0 | } |
777 | | } |
778 | 0 | for (field, value) in fields { |
779 | 0 | match self.fields.get(&field) { |
780 | 0 | Some(t) => { |
781 | 0 | if t != value.get_type() { |
782 | 0 | return Err(ExecutionError::UnexpectedType { |
783 | 0 | got: value.get_type().name().to_owned(), |
784 | 0 | want: format!("{} for field {field} in {name}", t.name()), |
785 | 0 | }); |
786 | 0 | } |
787 | 0 | s.add_field_value(field, value); |
788 | | } |
789 | | None => { |
790 | 0 | return Err(ExecutionError::NoSuchKey(std::sync::Arc::new(format!( |
791 | 0 | "field `{field}` on struct `{name}`" |
792 | 0 | )))) |
793 | | } |
794 | | } |
795 | | } |
796 | 0 | Ok(s) |
797 | 0 | } |
798 | | } |
799 | | |
800 | | impl StructType for StructDef { |
801 | 0 | fn get_type(&self) -> &Type { |
802 | 0 | &self.r#type |
803 | 0 | } |
804 | | |
805 | 0 | fn new_value<'b, 'v>( |
806 | 0 | &self, |
807 | 0 | fields: BTreeMap<String, CowVal<'b, 'v>>, |
808 | 0 | ) -> Result<Box<dyn Val + 'v>, ExecutionError> { |
809 | 0 | Ok(Box::new(self.new_struct(fields)?)) |
810 | 0 | } |
811 | | } |
812 | | |
813 | | #[cfg(test)] |
814 | | mod tests { |
815 | | use super::*; |
816 | | use crate::common::types::Type; |
817 | | use crate::common::value::Val; |
818 | | use crate::Context; |
819 | | use std::borrow::Cow; |
820 | | use std::cell::Cell; |
821 | | use std::sync::Arc; |
822 | | |
823 | | #[test] |
824 | | fn test_env_default() { |
825 | | let _: Arc<dyn Send + Sync> = Arc::new(Env::default()); |
826 | | } |
827 | | |
828 | | #[test] |
829 | | fn an_empty_container_name_clears_the_container() { |
830 | | use crate::{Context, Program, Value}; |
831 | | |
832 | | let program = Program::compile("y").unwrap(); |
833 | | let run = |env: &Arc<Env>| { |
834 | | let mut context = Context::with_env(env.clone()); |
835 | | context.add_variable_from_value("x.y", true); |
836 | | program.execute(&context) |
837 | | }; |
838 | | |
839 | | let mut env = Arc::new(Env::stdlib()); |
840 | | assert_eq!(env.container_name(), ""); |
841 | | let env_mut = Arc::get_mut(&mut env).unwrap(); |
842 | | env_mut.set_container("x").unwrap(); |
843 | | assert!(env_mut.set_container(".x").is_err()); |
844 | | assert_eq!(env.container_name(), "x", "a failed call changes nothing"); |
845 | | assert_eq!(run(&env), Ok(Value::Bool(true))); |
846 | | |
847 | | Arc::get_mut(&mut env).unwrap().set_container("").unwrap(); |
848 | | assert_eq!(env.container_name(), ""); |
849 | | assert!(run(&env).is_err(), "`y` no longer means `x.y`"); |
850 | | } |
851 | | |
852 | | #[test] |
853 | | fn its_parser_expands_the_macros_of_the_env_only() { |
854 | | use crate::common::ast::Expr; |
855 | | |
856 | | let source = "[1].exists(x, x > 0)"; |
857 | | let expanded = Env::stdlib().parser().parse(source).unwrap(); |
858 | | assert!( |
859 | | matches!(expanded.expr, Expr::Comprehension(_)), |
860 | | "{expanded:?}" |
861 | | ); |
862 | | let as_written = Env::default().parser().parse(source).unwrap(); |
863 | | assert!(matches!(as_written.expr, Expr::Call(_)), "{as_written:?}"); |
864 | | } |
865 | | |
866 | | fn first_arg( |
867 | | _: &mut crate::parser::MacroExprHelper<'_>, |
868 | | _: &mut Option<crate::IdedExpr>, |
869 | | args: &mut Vec<crate::IdedExpr>, |
870 | | ) -> Result<Option<crate::IdedExpr>, crate::ParseError> { |
871 | | Ok(Some(args.remove(0))) |
872 | | } |
873 | | |
874 | | #[test] |
875 | | fn a_macro_expands_only_the_calls_of_its_style_and_argument_count() { |
876 | | use crate::common::ast::Expr; |
877 | | |
878 | | let mut env = Env::default(); |
879 | | env.add_macro(Macro::receiver("f", 1, first_arg)).unwrap(); |
880 | | let expanded = env.parser().parse("m.f(1)").unwrap(); |
881 | | assert!(matches!(expanded.expr, Expr::Literal(_)), "{expanded:?}"); |
882 | | for source in ["m.f()", "m.f(1, 2)", "f(1)"] { |
883 | | let as_written = env.parser().parse(source).unwrap(); |
884 | | assert!( |
885 | | matches!(as_written.expr, Expr::Call(_)), |
886 | | "{source}: {as_written:?}" |
887 | | ); |
888 | | } |
889 | | } |
890 | | |
891 | | #[test] |
892 | | fn a_macro_for_the_calls_of_another_is_a_duplicate() { |
893 | | let mut env = Env::stdlib(); |
894 | | assert_eq!( |
895 | | env.add_macro(Macro::receiver("exists", 2, first_arg)), |
896 | | Err(DeclarationError::duplicate_macro("exists")), |
897 | | "the standard `exists` expands those" |
898 | | ); |
899 | | // Called globally, or with another argument count, it's another call. |
900 | | assert_eq!(env.add_macro(Macro::global("exists", 2, first_arg)), Ok(())); |
901 | | assert_eq!( |
902 | | env.add_macro(Macro::receiver("exists", 3, first_arg)), |
903 | | Ok(()) |
904 | | ); |
905 | | assert_eq!( |
906 | | env.add_macro(Macro::receiver("exists", 3, first_arg)), |
907 | | Err(DeclarationError::duplicate_macro("exists")) |
908 | | ); |
909 | | // For any number of arguments, it's yet other calls, once. |
910 | | assert_eq!( |
911 | | env.add_macro(Macro::receiver_var_arg("exists", first_arg)), |
912 | | Ok(()) |
913 | | ); |
914 | | assert_eq!( |
915 | | env.add_macro(Macro::receiver_var_arg("exists", first_arg)), |
916 | | Err(DeclarationError::duplicate_macro("exists")) |
917 | | ); |
918 | | assert_eq!( |
919 | | env.add_macro(Macro::global_var_arg("exists", first_arg)), |
920 | | Ok(()) |
921 | | ); |
922 | | } |
923 | | |
924 | | /// Declines `f(x)` after popping `x`, or `mem::take`-ing it. |
925 | | fn takes_then_declines( |
926 | | _: &mut crate::parser::MacroExprHelper<'_>, |
927 | | _: &mut Option<crate::IdedExpr>, |
928 | | args: &mut Vec<crate::IdedExpr>, |
929 | | ) -> Result<Option<crate::IdedExpr>, crate::ParseError> { |
930 | | match args[0].expr { |
931 | | crate::common::ast::Expr::Literal(_) => drop(args.pop()), |
932 | | _ => drop(std::mem::take(&mut args[0])), |
933 | | } |
934 | | Ok(None) |
935 | | } |
936 | | |
937 | | #[test] |
938 | | fn declining_a_call_after_taking_from_it_is_an_error() { |
939 | | let mut env = Env::stdlib(); |
940 | | env.add_macro(Macro::global("f", 1, takes_then_declines)) |
941 | | .unwrap(); |
942 | | for source in ["f(1)", "f(a)"] { |
943 | | let errors = env.parser().parse(source).unwrap_err().errors; |
944 | | let messages: Vec<_> = errors.iter().map(|e| e.msg.as_str()).collect(); |
945 | | assert_eq!( |
946 | | messages, |
947 | | ["macro 'f' declined the call after taking from it"], |
948 | | "{source}" |
949 | | ); |
950 | | } |
951 | | } |
952 | | |
953 | | fn declines( |
954 | | _: &mut crate::parser::MacroExprHelper<'_>, |
955 | | _: &mut Option<crate::IdedExpr>, |
956 | | _: &mut Vec<crate::IdedExpr>, |
957 | | ) -> Result<Option<crate::IdedExpr>, crate::ParseError> { |
958 | | Ok(None) |
959 | | } |
960 | | |
961 | | /// The parser leaves a default node for an argument it failed to expand: |
962 | | /// that isn't something a declining macro took. |
963 | | #[test] |
964 | | fn declining_a_call_with_a_broken_argument_reports_only_that_argument() { |
965 | | let mut env = Env::stdlib(); |
966 | | env.add_macro(Macro::global("f", 1, declines)).unwrap(); |
967 | | let errors = env.parser().parse("f(has(1))").unwrap_err().errors; |
968 | | let messages: Vec<_> = errors.iter().map(|e| e.msg.as_str()).collect(); |
969 | | assert_eq!(messages, ["invalid argument to has() macro"]); |
970 | | } |
971 | | |
972 | | #[test] |
973 | | fn a_qualified_overload_declares_its_namespace() { |
974 | | let mut env = Env::default(); |
975 | | env.add_overload("a.b.f", "a_b_f", vec![], noop).unwrap(); |
976 | | env.add_overload("g", "g", vec![], noop).unwrap(); |
977 | | env.add_member_overload("c.m", "c_m", types::INT_TYPE, vec![], noop) |
978 | | .unwrap(); |
979 | | assert!(env.has_namespace("a")); |
980 | | assert!(!env.has_namespace("a.b")); |
981 | | assert!(!env.has_namespace("g")); |
982 | | assert!(!env.has_namespace("c"), "member overloads aren't qualified"); |
983 | | } |
984 | | |
985 | | #[test] |
986 | | fn the_standard_library_registers_its_types() { |
987 | | let names = [ |
988 | | "bool", |
989 | | "bytes", |
990 | | "double", |
991 | | "int", |
992 | | "list", |
993 | | "map", |
994 | | "null_type", |
995 | | "optional_type", |
996 | | "string", |
997 | | "type", |
998 | | "uint", |
999 | | #[cfg(feature = "chrono")] |
1000 | | "google.protobuf.Duration", |
1001 | | #[cfg(feature = "chrono")] |
1002 | | "google.protobuf.Timestamp", |
1003 | | ]; |
1004 | | let stdlib = Env::stdlib(); |
1005 | | let default = Env::default(); |
1006 | | for name in names { |
1007 | | assert_eq!(stdlib.types().find_type(name).map(Type::name), Some(name)); |
1008 | | assert!(default.types().find_type(name).is_none(), "{name}"); |
1009 | | } |
1010 | | } |
1011 | | |
1012 | | #[test] |
1013 | | fn add_type_rejects_another_type_of_a_registered_name() { |
1014 | | let mut env = Env::stdlib(); |
1015 | | assert_eq!( |
1016 | | env.add_type(Type::new_opaque_type("optional_type")), |
1017 | | Err(DeclarationError::type_conflict("optional_type")) |
1018 | | ); |
1019 | | assert_eq!(env.add_type(types::OPTIONAL_TYPE), Ok(())); |
1020 | | } |
1021 | | |
1022 | | fn noop<'b, 'v>(args: Vec<CowVal<'b, 'v>>) -> Result<CowVal<'b, 'v>, crate::ExecutionError> { |
1023 | | Ok(args.into_iter().next().unwrap()) |
1024 | | } |
1025 | | |
1026 | | fn duplicate(function: &str, id: &str) -> DeclarationError { |
1027 | | DeclarationError::duplicate_overload(function, id) |
1028 | | } |
1029 | | |
1030 | | /// A library, `acme.lib.counted`, that counts the times it registers. |
1031 | | struct Counted<'a>(&'a Cell<u32>); |
1032 | | |
1033 | | impl Library for Counted<'_> { |
1034 | | fn name(&self) -> Option<&str> { |
1035 | | Some("acme.lib.counted") |
1036 | | } |
1037 | | |
1038 | | fn register(&self, _: &mut Env) -> Result<(), DeclarationError> { |
1039 | | self.0.set(self.0.get() + 1); |
1040 | | Ok(()) |
1041 | | } |
1042 | | } |
1043 | | |
1044 | | #[test] |
1045 | | fn a_named_library_is_registered_once() { |
1046 | | let registered = Cell::new(0); |
1047 | | let mut env = Env::default(); |
1048 | | assert!(!env.has_library("acme.lib.counted")); |
1049 | | assert_eq!(env.add_library(Counted(®istered)), Ok(())); |
1050 | | assert_eq!(env.add_library(Counted(®istered)), Ok(())); |
1051 | | assert_eq!(registered.get(), 1); |
1052 | | assert!(env.has_library("acme.lib.counted")); |
1053 | | assert!(!env.has_library("acme.lib")); |
1054 | | } |
1055 | | |
1056 | | /// A library is its name: another one of an added name isn't registered. |
1057 | | #[test] |
1058 | | fn a_library_of_an_added_name_is_not_registered() { |
1059 | | struct DeclaresF; |
1060 | | |
1061 | | impl Library for DeclaresF { |
1062 | | fn name(&self) -> Option<&str> { |
1063 | | Some("acme.lib.counted") |
1064 | | } |
1065 | | |
1066 | | fn register(&self, env: &mut Env) -> Result<(), DeclarationError> { |
1067 | | env.add_overload("f", "f", vec![], noop) |
1068 | | } |
1069 | | } |
1070 | | |
1071 | | let registered = Cell::new(0); |
1072 | | let mut env = Env::default(); |
1073 | | assert_eq!(env.add_library(Counted(®istered)), Ok(())); |
1074 | | assert_eq!(env.add_library(DeclaresF), Ok(())); |
1075 | | assert!(!env.has_overload("f")); |
1076 | | assert_eq!(env.libraries().collect::<Vec<_>>(), ["acme.lib.counted"]); |
1077 | | } |
1078 | | |
1079 | | #[test] |
1080 | | fn a_library_without_a_name_is_registered_every_time() { |
1081 | | struct Unnamed<'a>(&'a Cell<u32>); |
1082 | | |
1083 | | impl Library for Unnamed<'_> { |
1084 | | fn register(&self, _: &mut Env) -> Result<(), DeclarationError> { |
1085 | | self.0.set(self.0.get() + 1); |
1086 | | Ok(()) |
1087 | | } |
1088 | | } |
1089 | | |
1090 | | let registered = Cell::new(0); |
1091 | | assert_eq!(Unnamed(®istered).name(), None); |
1092 | | let mut env = Env::default(); |
1093 | | for _ in 0..2 { |
1094 | | assert_eq!(env.add_library(Unnamed(®istered)), Ok(())); |
1095 | | } |
1096 | | assert_eq!(registered.get(), 2); |
1097 | | assert_eq!(env.libraries().count(), 0); |
1098 | | } |
1099 | | |
1100 | | /// An extension is a function, called every time it is added: it is only |
1101 | | /// added once when it adds a library. |
1102 | | #[test] |
1103 | | fn an_extension_is_called_every_time_it_is_added() { |
1104 | | fn declares_f(env: &mut Env) -> Result<(), DeclarationError> { |
1105 | | env.add_overload("f", "f", vec![], noop) |
1106 | | } |
1107 | | |
1108 | | fn adds_a_library(env: &mut Env) -> Result<(), DeclarationError> { |
1109 | | struct DeclaresG; |
1110 | | |
1111 | | impl Library for DeclaresG { |
1112 | | fn name(&self) -> Option<&str> { |
1113 | | Some("acme.lib.g") |
1114 | | } |
1115 | | |
1116 | | fn register(&self, env: &mut Env) -> Result<(), DeclarationError> { |
1117 | | env.add_overload("g", "g", vec![], noop) |
1118 | | } |
1119 | | } |
1120 | | |
1121 | | env.add_library(DeclaresG) |
1122 | | } |
1123 | | |
1124 | | let mut env = Env::default(); |
1125 | | assert_eq!(env.add_extension(declares_f), Ok(())); |
1126 | | assert_eq!(env.add_extension(declares_f), Err(duplicate("f", "f"))); |
1127 | | assert_eq!(env.add_extension(adds_a_library), Ok(())); |
1128 | | assert_eq!(env.add_extension(adds_a_library), Ok(())); |
1129 | | assert!(env.has_overload("g")); |
1130 | | assert_eq!(env.libraries().collect::<Vec<_>>(), ["acme.lib.g"]); |
1131 | | } |
1132 | | |
1133 | | #[test] |
1134 | | fn a_library_that_fails_to_register_is_not_added() { |
1135 | | struct Failing<'a>(&'a Cell<u32>); |
1136 | | |
1137 | | impl Library for Failing<'_> { |
1138 | | fn name(&self) -> Option<&str> { |
1139 | | Some("acme.lib.failing") |
1140 | | } |
1141 | | |
1142 | | fn register(&self, env: &mut Env) -> Result<(), DeclarationError> { |
1143 | | self.0.set(self.0.get() + 1); |
1144 | | env.set_container("not a container") |
1145 | | } |
1146 | | } |
1147 | | |
1148 | | let registered = Cell::new(0); |
1149 | | let mut env = Env::default(); |
1150 | | for attempts in 1..=2 { |
1151 | | assert_eq!( |
1152 | | env.add_library(Failing(®istered)), |
1153 | | Err(DeclarationError::invalid_container_name("not a container")) |
1154 | | ); |
1155 | | assert_eq!(registered.get(), attempts); |
1156 | | assert!(!env.has_library("acme.lib.failing")); |
1157 | | } |
1158 | | } |
1159 | | |
1160 | | /// As in cel-go, a library is added before it registers: when a library |
1161 | | /// it adds, or itself, adds it again, it is there already. |
1162 | | #[test] |
1163 | | fn a_library_is_added_by_the_time_it_registers() { |
1164 | | struct AddsItself<'a>(&'a Cell<u32>); |
1165 | | |
1166 | | impl Library for AddsItself<'_> { |
1167 | | fn name(&self) -> Option<&str> { |
1168 | | Some("acme.lib.recursive") |
1169 | | } |
1170 | | |
1171 | | fn register(&self, env: &mut Env) -> Result<(), DeclarationError> { |
1172 | | self.0.set(self.0.get() + 1); |
1173 | | assert!(env.has_library("acme.lib.recursive")); |
1174 | | env.add_library(AddsItself(self.0)) |
1175 | | } |
1176 | | } |
1177 | | |
1178 | | let registered = Cell::new(0); |
1179 | | let mut env = Env::default(); |
1180 | | assert_eq!(env.add_library(AddsItself(®istered)), Ok(())); |
1181 | | assert_eq!(registered.get(), 1); |
1182 | | assert!(env.has_library("acme.lib.recursive")); |
1183 | | } |
1184 | | |
1185 | | #[test] |
1186 | | fn the_standard_library_is_added_once() { |
1187 | | use crate::{Context, Value}; |
1188 | | |
1189 | | assert_eq!(Env::default().libraries().count(), 0); |
1190 | | // Registered again, its overloads would be duplicates. |
1191 | | for env in [ |
1192 | | Env::stdlib(), |
1193 | | Env::stdlib().with_stdlib(), |
1194 | | Env::default().with_stdlib().with_stdlib(), |
1195 | | ] { |
1196 | | assert_eq!( |
1197 | | env.libraries().collect::<Vec<_>>(), |
1198 | | ["cel.lib.optional", "cel.lib.std"] |
1199 | | ); |
1200 | | let program = env.compile("optional.of(size('abc')).value()").unwrap(); |
1201 | | let context = Context::with_env(Arc::new(env)); |
1202 | | assert_eq!(program.execute(&context), Ok(Value::Int(3))); |
1203 | | } |
1204 | | } |
1205 | | |
1206 | | /// The `optional` library is one of its own: the standard library adds |
1207 | | /// it when optional values are supported, even if only later. |
1208 | | #[test] |
1209 | | fn the_optional_library_is_added_once_optional_values_are_supported() { |
1210 | | let env = Env::default().with_optional_support(false).with_stdlib(); |
1211 | | assert_eq!(env.libraries().collect::<Vec<_>>(), ["cel.lib.std"]); |
1212 | | assert!(!env.has_overload("optional.of")); |
1213 | | |
1214 | | let env = env.with_optional_support(true).with_stdlib().with_stdlib(); |
1215 | | assert!(env.has_library("cel.lib.optional")); |
1216 | | assert!(env.has_overload("optional.of")); |
1217 | | } |
1218 | | |
1219 | | /// An extension adds its library, with its default settings. |
1220 | | #[test] |
1221 | | fn the_extensions_are_added_once_under_the_names_of_cel_go() { |
1222 | | use crate::extensions; |
1223 | | |
1224 | | type Extension = fn(&mut Env) -> Result<(), DeclarationError>; |
1225 | | let named: &[(&str, Extension)] = &[ |
1226 | | ("cel.lib.ext.cel.bindings", extensions::bindings), |
1227 | | ("cel.lib.ext.comprev2", extensions::two_var_comprehensions), |
1228 | | #[cfg(feature = "ext_encoders")] |
1229 | | ("cel.lib.ext.encoders", extensions::encoders), |
1230 | | ("cel.lib.ext.lists", extensions::lists), |
1231 | | ("cel.lib.ext.math", extensions::math), |
1232 | | ("cel.lib.ext.network", extensions::network), |
1233 | | ("cel.lib.ext.sets", extensions::sets), |
1234 | | ("cel.lib.ext.strings", extensions::strings), |
1235 | | ]; |
1236 | | let mut env = Env::stdlib(); |
1237 | | for (name, extension) in named { |
1238 | | assert!(!env.has_library(name), "{name}"); |
1239 | | for _ in 0..2 { |
1240 | | assert_eq!(env.add_extension(extension), Ok(()), "{name}"); |
1241 | | } |
1242 | | assert!(env.has_library(name), "{name}"); |
1243 | | } |
1244 | | let names = named.iter().map(|(name, _)| *name); |
1245 | | assert_eq!( |
1246 | | env.libraries().collect::<Vec<_>>(), |
1247 | | names |
1248 | | .chain(["cel.lib.optional", "cel.lib.std"]) |
1249 | | .collect::<Vec<_>>() |
1250 | | ); |
1251 | | |
1252 | | assert_eq!(env.add_library(extensions::Strings::default()), Ok(())); |
1253 | | let mut env = Env::stdlib(); |
1254 | | assert_eq!(env.add_library(extensions::Strings::default()), Ok(())); |
1255 | | assert_eq!(env.add_extension(extensions::strings), Ok(())); |
1256 | | assert!(env.has_member_overload("lowerAscii")); |
1257 | | } |
1258 | | |
1259 | | /// A closure holds what it captured, and is called as a function is. |
1260 | | #[test] |
1261 | | fn an_overload_can_be_a_closure() { |
1262 | | use crate::common::types::CelInt; |
1263 | | use crate::{Context, Value}; |
1264 | | |
1265 | | fn scale( |
1266 | | factor: i64, |
1267 | | ) -> impl for<'b, 'v> Fn(Vec<CowVal<'b, 'v>>) -> Result<CowVal<'b, 'v>, ExecutionError> |
1268 | | { |
1269 | | move |args| { |
1270 | | let n = args[0].downcast_ref::<CelInt>().unwrap().inner(); |
1271 | | Ok(CowVal::owned(CelInt::from(n * factor))) |
1272 | | } |
1273 | | } |
1274 | | |
1275 | | let mut env = Env::stdlib(); |
1276 | | for (name, factor) in [("twice", 2), ("a.thrice", 3)] { |
1277 | | assert_eq!( |
1278 | | env.add_overload_with(name, name, vec![types::INT_TYPE], scale(factor)), |
1279 | | Ok(()) |
1280 | | ); |
1281 | | } |
1282 | | assert!(env.has_namespace("a")); |
1283 | | |
1284 | | let env = Arc::new(env); |
1285 | | for (expr, expected) in [("twice(4)", 8), ("a.thrice(4)", 12)] { |
1286 | | let program = env.compile(expr).unwrap(); |
1287 | | let context = Context::with_env(env.clone()); |
1288 | | assert_eq!(program.execute(&context), Ok(Value::Int(expected))); |
1289 | | } |
1290 | | } |
1291 | | |
1292 | | /// An overload is picked by the coarse types of its arguments: that of a |
1293 | | /// `list(int)` is called with any list, one of a type parameter with |
1294 | | /// anything. |
1295 | | #[test] |
1296 | | fn a_call_resolves_to_generic_and_parameterized_overloads() { |
1297 | | static LIST_OF_INT: [Cow<'static, Type>; 1] = [Cow::Borrowed(&types::INT_TYPE)]; |
1298 | | static MAP_OF_STRING_INT: [Cow<'static, Type>; 2] = [ |
1299 | | Cow::Borrowed(&types::STRING_TYPE), |
1300 | | Cow::Borrowed(&types::INT_TYPE), |
1301 | | ]; |
1302 | | let mut env = Env::stdlib(); |
1303 | | for (name, arg) in [ |
1304 | | ("ints", Type::new_list_type(&LIST_OF_INT)), |
1305 | | ("entries", Type::new_map_type(&MAP_OF_STRING_INT)), |
1306 | | ("any", Type::new_type_param("A")), |
1307 | | ] { |
1308 | | env.add_overload(name, name, vec![arg], noop).unwrap(); |
1309 | | } |
1310 | | let env = Arc::new(env); |
1311 | | let eval = |source: &str| { |
1312 | | let program = env.compile(source).unwrap(); |
1313 | | program.execute(&Context::with_env(Arc::clone(&env))) |
1314 | | }; |
1315 | | |
1316 | | for source in ["ints([])", "ints([1])", "ints(['a'])", "ints(['a', 1])"] { |
1317 | | assert!(eval(source).is_ok(), "{source}"); |
1318 | | } |
1319 | | for source in ["entries({})", "entries({'a': 1})", "entries({1: 'a'})"] { |
1320 | | assert!(eval(source).is_ok(), "{source}"); |
1321 | | } |
1322 | | for source in ["any(1)", "any('a')", "any([1])", "any(null)"] { |
1323 | | assert!(eval(source).is_ok(), "{source}"); |
1324 | | } |
1325 | | for source in ["ints(1)", "ints({})", "entries([])", "entries(1)"] { |
1326 | | assert!( |
1327 | | matches!(eval(source), Err(crate::ExecutionError::NoSuchOverload(_))), |
1328 | | "{source}", |
1329 | | ); |
1330 | | } |
1331 | | } |
1332 | | |
1333 | | /// Only optionals reach the overloads of `optional_type`, and whatever |
1334 | | /// else they are called on doesn't have them. |
1335 | | #[test] |
1336 | | fn optional_overloads_reject_other_values() { |
1337 | | let env = Arc::new(Env::stdlib()); |
1338 | | for source in [ |
1339 | | "1.hasValue()", |
1340 | | "'a'.orValue(1)", |
1341 | | "1.value()", |
1342 | | "1.or(optional.none())", |
1343 | | ] { |
1344 | | let result = env |
1345 | | .compile(source) |
1346 | | .unwrap() |
1347 | | .execute(&Context::with_env(Arc::clone(&env))); |
1348 | | assert!( |
1349 | | matches!(result, Err(crate::ExecutionError::NoSuchOverload(_))), |
1350 | | "{source}: {result:?}", |
1351 | | ); |
1352 | | } |
1353 | | } |
1354 | | |
1355 | | /// The name of a type parameter only means something within its overload, |
1356 | | /// so it doesn't make for another signature. |
1357 | | #[test] |
1358 | | fn a_signature_is_the_same_whatever_its_type_params_are_named() { |
1359 | | const A: Type = Type::new_type_param("A"); |
1360 | | const B: Type = Type::new_type_param("B"); |
1361 | | static PARAM_A: Type = A; |
1362 | | static PARAM_B: Type = B; |
1363 | | static LIST_OF_A: [Cow<'static, Type>; 1] = [Cow::Borrowed(&PARAM_A)]; |
1364 | | static LIST_OF_B: [Cow<'static, Type>; 1] = [Cow::Borrowed(&PARAM_B)]; |
1365 | | let mut env = Env::default(); |
1366 | | |
1367 | | assert_eq!(env.add_overload("f", "f_a", vec![A], noop), Ok(())); |
1368 | | assert_eq!( |
1369 | | env.add_overload("f", "f_b", vec![B], noop), |
1370 | | Err(duplicate("f", "f_b")) |
1371 | | ); |
1372 | | assert_eq!( |
1373 | | env.add_overload("g", "g_a", vec![Type::new_list_type(&LIST_OF_A)], noop), |
1374 | | Ok(()) |
1375 | | ); |
1376 | | assert_eq!( |
1377 | | env.add_overload("g", "g_b", vec![Type::new_list_type(&LIST_OF_B)], noop), |
1378 | | Err(duplicate("g", "g_b")) |
1379 | | ); |
1380 | | // a member overload's signature is another one |
1381 | | assert_eq!(env.add_member_overload("f", "a_f", A, vec![], noop), Ok(())); |
1382 | | assert_eq!( |
1383 | | env.add_member_overload("f", "b_f", B, vec![], noop), |
1384 | | Err(duplicate("f", "b_f")) |
1385 | | ); |
1386 | | } |
1387 | | |
1388 | | fn only_overload<'a>(env: &'a Env, name: &str) -> &'a crate::common::decls::OverloadDecl { |
1389 | | let mut overloads = env.function(name).unwrap().overloads(); |
1390 | | assert_eq!(overloads.len(), 1); |
1391 | | overloads.next().unwrap() |
1392 | | } |
1393 | | |
1394 | | #[test] |
1395 | | fn a_signature_declares_the_argument_and_result_types() { |
1396 | | let mut env = Env::default(); |
1397 | | let signature = Signature::new(vec![types::INT_TYPE, types::UINT_TYPE]); |
1398 | | env.add_overload("f", "f_id", signature.returns(types::STRING_TYPE), noop) |
1399 | | .unwrap(); |
1400 | | |
1401 | | let overload = only_overload(&env, "f"); |
1402 | | assert_eq!(overload.id, "f_id"); |
1403 | | assert!(!overload.is_member_function()); |
1404 | | assert_eq!( |
1405 | | overload.arg_types().collect::<Vec<_>>(), |
1406 | | [&types::INT_TYPE, &types::UINT_TYPE] |
1407 | | ); |
1408 | | assert_eq!(overload.result_type(), &types::STRING_TYPE); |
1409 | | } |
1410 | | |
1411 | | #[test] |
1412 | | fn a_member_overload_takes_its_receiver_first() { |
1413 | | let mut env = Env::default(); |
1414 | | let signature = Signature::new(vec![types::UINT_TYPE]).returns(types::STRING_TYPE); |
1415 | | env.add_member_overload("f", "int_f", types::INT_TYPE, signature, noop) |
1416 | | .unwrap(); |
1417 | | |
1418 | | let overload = only_overload(&env, "f"); |
1419 | | assert!(overload.is_member_function()); |
1420 | | assert_eq!( |
1421 | | overload.arg_types().collect::<Vec<_>>(), |
1422 | | [&types::INT_TYPE, &types::UINT_TYPE] |
1423 | | ); |
1424 | | assert_eq!(overload.result_type(), &types::STRING_TYPE); |
1425 | | } |
1426 | | |
1427 | | #[test] |
1428 | | fn a_closure_declares_a_signature_too() { |
1429 | | let mut env = Env::default(); |
1430 | | let signature = Signature::new(vec![types::INT_TYPE]).returns(types::STRING_TYPE); |
1431 | | env.add_overload_with("f", "f_id", signature, noop).unwrap(); |
1432 | | env.add_overload_with("g", "g_id", vec![types::INT_TYPE], noop) |
1433 | | .unwrap(); |
1434 | | |
1435 | | assert_eq!(only_overload(&env, "f").result_type(), &types::STRING_TYPE); |
1436 | | assert_eq!(only_overload(&env, "g").result_type(), &types::DYN_TYPE); |
1437 | | } |
1438 | | |
1439 | | /// Argument types alone leave the result undeclared, whichever way the |
1440 | | /// overload is added. |
1441 | | #[test] |
1442 | | fn an_undeclared_result_is_dyn() { |
1443 | | let mut env = Env::default(); |
1444 | | env.add_overload("f", "f_id", vec![], noop).unwrap(); |
1445 | | env.add_member_overload("g", "g_id", types::INT_TYPE, vec![], noop) |
1446 | | .unwrap(); |
1447 | | assert_eq!(only_overload(&env, "f").result_type(), &types::DYN_TYPE); |
1448 | | assert_eq!(only_overload(&env, "g").result_type(), &types::DYN_TYPE); |
1449 | | } |
1450 | | |
1451 | | #[test] |
1452 | | fn overloads_are_listed_in_the_order_they_were_declared() { |
1453 | | let mut env = Env::default(); |
1454 | | for (id, arg) in [ |
1455 | | ("f_string", types::STRING_TYPE), |
1456 | | ("f_int", types::INT_TYPE), |
1457 | | ("f_bool", types::BOOL_TYPE), |
1458 | | ] { |
1459 | | env.add_overload("f", id, vec![arg], noop).unwrap(); |
1460 | | } |
1461 | | let ids: Vec<_> = env |
1462 | | .function("f") |
1463 | | .unwrap() |
1464 | | .overloads() |
1465 | | .map(|overload| overload.id.as_str()) |
1466 | | .collect(); |
1467 | | assert_eq!(ids, ["f_string", "f_int", "f_bool"]); |
1468 | | } |
1469 | | |
1470 | | #[test] |
1471 | | fn an_undeclared_function_is_absent() { |
1472 | | assert!(Env::default().function("f").is_none()); |
1473 | | assert!(Env::stdlib().function("f").is_none()); |
1474 | | assert!(Env::stdlib().function("size").is_some()); |
1475 | | } |
1476 | | |
1477 | | /// Overloads are picked by their arguments, so that's all that tells them |
1478 | | /// apart. |
1479 | | #[test] |
1480 | | fn overloads_can_t_differ_by_their_result_type_alone() { |
1481 | | let mut env = Env::default(); |
1482 | | let returning = |result| Signature::new(vec![types::INT_TYPE]).returns(result); |
1483 | | assert_eq!( |
1484 | | env.add_overload("f", "f_int", returning(types::INT_TYPE), noop), |
1485 | | Ok(()) |
1486 | | ); |
1487 | | assert_eq!( |
1488 | | env.add_overload("f", "f_string", returning(types::STRING_TYPE), noop), |
1489 | | Err(duplicate("f", "f_string")) |
1490 | | ); |
1491 | | } |
1492 | | |
1493 | | /// The result type is a declaration: evaluation doesn't look at it. |
1494 | | #[test] |
1495 | | fn evaluation_ignores_the_declared_result_type() { |
1496 | | let mut env = Env::stdlib(); |
1497 | | let signature = Signature::new(vec![types::INT_TYPE]).returns(types::STRING_TYPE); |
1498 | | env.add_overload("f", "f_int", signature, noop).unwrap(); |
1499 | | let env = Arc::new(env); |
1500 | | let result = env |
1501 | | .compile("f(1)") |
1502 | | .unwrap() |
1503 | | .execute(&Context::with_env(Arc::clone(&env))); |
1504 | | assert_eq!(result, Ok(crate::Value::Int(1))); |
1505 | | } |
1506 | | |
1507 | | /// Spec, Functions: "Overloads must have non-overlapping argument types, |
1508 | | /// after erasure of all type variables". |
1509 | | #[test] |
1510 | | fn overloads_whose_argument_types_overlap_are_rejected() { |
1511 | | static LIST_OF_INT: [Cow<'static, Type>; 1] = [Cow::Borrowed(&types::INT_TYPE)]; |
1512 | | static LIST_OF_STRING: [Cow<'static, Type>; 1] = [Cow::Borrowed(&types::STRING_TYPE)]; |
1513 | | static PARAM_A: Type = A; |
1514 | | static LIST_OF_A: [Cow<'static, Type>; 1] = [Cow::Borrowed(&PARAM_A)]; |
1515 | | static MAP_OF_INT_INT: [Cow<'static, Type>; 2] = [ |
1516 | | Cow::Borrowed(&types::INT_TYPE), |
1517 | | Cow::Borrowed(&types::INT_TYPE), |
1518 | | ]; |
1519 | | const A: Type = Type::new_type_param("A"); |
1520 | | let list_of_int = || Type::new_list_type(&LIST_OF_INT); |
1521 | | let list_of_string = || Type::new_list_type(&LIST_OF_STRING); |
1522 | | let list_of_a = || Type::new_list_type(&LIST_OF_A); |
1523 | | let map_of_int_int = || Type::new_map_type(&MAP_OF_INT_INT); |
1524 | | |
1525 | | let overlapping: Vec<(Vec<Type>, Vec<Type>)> = vec![ |
1526 | | (vec![types::DYN_TYPE], vec![types::INT_TYPE]), |
1527 | | (vec![A], vec![types::INT_TYPE]), |
1528 | | (vec![A], vec![types::DYN_TYPE]), |
1529 | | (vec![A], vec![list_of_int()]), |
1530 | | (vec![list_of_a()], vec![list_of_int()]), |
1531 | | (vec![list_of_int()], vec![list_of_string()]), |
1532 | | (vec![types::LIST_TYPE], vec![list_of_a()]), |
1533 | | (vec![types::MAP_TYPE], vec![map_of_int_int()]), |
1534 | | (vec![types::OPTIONAL_TYPE], vec![A]), |
1535 | | ( |
1536 | | vec![types::INT_TYPE, types::DYN_TYPE], |
1537 | | vec![types::DYN_TYPE, types::STRING_TYPE], |
1538 | | ), |
1539 | | ]; |
1540 | | for (first, second) in overlapping { |
1541 | | let shown = format!("{first:?} / {second:?}"); |
1542 | | // whichever is declared first |
1543 | | for (first, second) in [ |
1544 | | ( |
1545 | | first.iter().map(Type::to_owned).collect::<Vec<_>>(), |
1546 | | second.iter().map(Type::to_owned).collect::<Vec<_>>(), |
1547 | | ), |
1548 | | (second, first), |
1549 | | ] { |
1550 | | let mut env = Env::default(); |
1551 | | assert_eq!( |
1552 | | env.add_overload("f", "first", first, noop), |
1553 | | Ok(()), |
1554 | | "{shown}" |
1555 | | ); |
1556 | | assert_eq!( |
1557 | | env.add_overload("f", "second", second, noop), |
1558 | | Err(DeclarationError::overlapping_overload( |
1559 | | "f", "second", "first" |
1560 | | )), |
1561 | | "{shown}", |
1562 | | ); |
1563 | | } |
1564 | | } |
1565 | | |
1566 | | let distinct: Vec<(Vec<Type>, Vec<Type>)> = vec![ |
1567 | | (vec![types::INT_TYPE], vec![types::STRING_TYPE]), |
1568 | | (vec![list_of_a()], vec![types::INT_TYPE]), |
1569 | | (vec![list_of_int()], vec![map_of_int_int()]), |
1570 | | (vec![types::OPTIONAL_TYPE], vec![types::LIST_TYPE]), |
1571 | | ( |
1572 | | vec![types::DYN_TYPE], |
1573 | | vec![types::DYN_TYPE, types::DYN_TYPE], |
1574 | | ), |
1575 | | (vec![], vec![A]), |
1576 | | ( |
1577 | | vec![types::INT_TYPE, types::DYN_TYPE], |
1578 | | vec![types::STRING_TYPE, types::DYN_TYPE], |
1579 | | ), |
1580 | | ( |
1581 | | vec![Type::new_opaque_type("a")], |
1582 | | vec![Type::new_opaque_type("b")], |
1583 | | ), |
1584 | | ]; |
1585 | | for (first, second) in distinct { |
1586 | | let shown = format!("{first:?} / {second:?}"); |
1587 | | let mut env = Env::default(); |
1588 | | assert_eq!( |
1589 | | env.add_overload("f", "first", first, noop), |
1590 | | Ok(()), |
1591 | | "{shown}" |
1592 | | ); |
1593 | | assert_eq!( |
1594 | | env.add_overload("f", "second", second, noop), |
1595 | | Ok(()), |
1596 | | "{shown}" |
1597 | | ); |
1598 | | } |
1599 | | } |
1600 | | |
1601 | | #[test] |
1602 | | fn only_overloads_of_the_same_call_style_overlap() { |
1603 | | let mut env = Env::default(); |
1604 | | assert_eq!( |
1605 | | env.add_overload("f", "f_dyn", vec![types::DYN_TYPE], noop), |
1606 | | Ok(()) |
1607 | | ); |
1608 | | assert_eq!( |
1609 | | env.add_member_overload("f", "int_f", types::INT_TYPE, vec![], noop), |
1610 | | Ok(()) |
1611 | | ); |
1612 | | assert_eq!( |
1613 | | env.add_member_overload("f", "dyn_f", types::DYN_TYPE, vec![], noop), |
1614 | | Err(DeclarationError::overlapping_overload( |
1615 | | "f", "dyn_f", "int_f" |
1616 | | )) |
1617 | | ); |
1618 | | assert_eq!( |
1619 | | env.add_overload("g", "g_int", vec![types::INT_TYPE], noop), |
1620 | | Ok(()) |
1621 | | ); |
1622 | | assert_eq!( |
1623 | | env.add_overload_with("g", "g_dyn", vec![types::DYN_TYPE], noop), |
1624 | | Err(DeclarationError::overlapping_overload( |
1625 | | "g", "g_dyn", "g_int" |
1626 | | )) |
1627 | | ); |
1628 | | } |
1629 | | |
1630 | | /// A duplicate is reported as such, even when another overload overlaps |
1631 | | /// first: only the id, or the signature, needs changing. |
1632 | | #[test] |
1633 | | fn a_duplicate_is_not_reported_as_an_overlap() { |
1634 | | let mut env = Env::default(); |
1635 | | assert_eq!( |
1636 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop), |
1637 | | Ok(()) |
1638 | | ); |
1639 | | assert_eq!( |
1640 | | env.add_overload("f", "f_string", vec![types::STRING_TYPE], noop), |
1641 | | Ok(()) |
1642 | | ); |
1643 | | assert_eq!( |
1644 | | env.add_overload("f", "f_string", vec![types::DYN_TYPE], noop), |
1645 | | Err(duplicate("f", "f_string")) |
1646 | | ); |
1647 | | assert_eq!( |
1648 | | env.add_overload("f", "f_other", vec![types::STRING_TYPE], noop), |
1649 | | Err(duplicate("f", "f_other")) |
1650 | | ); |
1651 | | } |
1652 | | |
1653 | | /// A rejected overload leaves the function as it was. |
1654 | | #[test] |
1655 | | fn a_rejected_overlap_declares_nothing() { |
1656 | | let mut env = Env::stdlib(); |
1657 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop) |
1658 | | .unwrap(); |
1659 | | assert!(env |
1660 | | .add_overload("f", "f_dyn", vec![types::DYN_TYPE], noop) |
1661 | | .is_err()); |
1662 | | let env = Arc::new(env); |
1663 | | let eval = |source: &str| { |
1664 | | let program = env.compile(source).unwrap(); |
1665 | | program.execute(&Context::with_env(Arc::clone(&env))) |
1666 | | }; |
1667 | | assert_eq!(eval("f(1)"), Ok(crate::Value::Int(1))); |
1668 | | assert!(matches!( |
1669 | | eval("f('a')"), |
1670 | | Err(crate::ExecutionError::NoSuchOverload(_)) |
1671 | | )); |
1672 | | } |
1673 | | |
1674 | | /// What the standard library and the extensions declare doesn't overlap. |
1675 | | #[test] |
1676 | | fn nothing_declared_by_this_crate_overlaps() { |
1677 | | let mut env = Env::stdlib().with_optional_support(true); |
1678 | | env.add_extension(crate::extensions::bindings).unwrap(); |
1679 | | env.add_extension(crate::extensions::encoders).unwrap(); |
1680 | | env.add_extension(crate::extensions::lists).unwrap(); |
1681 | | env.add_extension(crate::extensions::math).unwrap(); |
1682 | | env.add_extension(crate::extensions::network).unwrap(); |
1683 | | env.add_extension(crate::extensions::strings).unwrap(); |
1684 | | } |
1685 | | |
1686 | | /// A closure and a function are overloads alike: neither's id, nor |
1687 | | /// signature, can be another's. |
1688 | | #[test] |
1689 | | fn add_overload_with_rejects_a_duplicate_id_or_signature() { |
1690 | | let mut env = Env::default(); |
1691 | | assert_eq!( |
1692 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop), |
1693 | | Ok(()) |
1694 | | ); |
1695 | | assert_eq!( |
1696 | | env.add_overload_with("f", "f_int", vec![types::STRING_TYPE], noop), |
1697 | | Err(duplicate("f", "f_int")) |
1698 | | ); |
1699 | | assert_eq!( |
1700 | | env.add_overload_with("f", "other_id", vec![types::INT_TYPE], noop), |
1701 | | Err(duplicate("f", "other_id")) |
1702 | | ); |
1703 | | assert_eq!( |
1704 | | env.add_overload_with("f", "f_string", vec![types::STRING_TYPE], noop), |
1705 | | Ok(()) |
1706 | | ); |
1707 | | assert_eq!( |
1708 | | env.add_overload("f", "f_string", vec![types::BOOL_TYPE], noop), |
1709 | | Err(duplicate("f", "f_string")) |
1710 | | ); |
1711 | | } |
1712 | | |
1713 | | /// A closure isn't a [`Function`]: `find_overload` has none to hand out |
1714 | | /// for the overload, which a call still resolves to. |
1715 | | #[test] |
1716 | | fn find_overload_only_finds_the_functions() { |
1717 | | use crate::common::types::{CelInt, CelString}; |
1718 | | |
1719 | | let mut env = Env::default(); |
1720 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop) |
1721 | | .unwrap(); |
1722 | | env.add_overload_with("f", "f_string", vec![types::STRING_TYPE], noop) |
1723 | | .unwrap(); |
1724 | | |
1725 | | let int = || vec![CowVal::owned(CelInt::from(1))]; |
1726 | | let string = || vec![CowVal::owned(CelString::from("a"))]; |
1727 | | assert!(env.find_overload("f", &int()).is_some()); |
1728 | | assert!(env.find_overload("f", &string()).is_none()); |
1729 | | for args in [int, string] { |
1730 | | let op = env.find_op("f", false, &args()).unwrap(); |
1731 | | assert!(op.call(args()).is_ok()); |
1732 | | assert!(env.find_op("f", true, &args()).is_none()); |
1733 | | } |
1734 | | assert!(env.find_op("g", false, &int()).is_none()); |
1735 | | } |
1736 | | |
1737 | | #[test] |
1738 | | fn add_overload_rejects_a_duplicate_id() { |
1739 | | let mut env = Env::default(); |
1740 | | assert_eq!( |
1741 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop), |
1742 | | Ok(()) |
1743 | | ); |
1744 | | // another signature, but the id is taken |
1745 | | assert_eq!( |
1746 | | env.add_overload("f", "f_int", vec![types::STRING_TYPE], noop), |
1747 | | Err(duplicate("f", "f_int")) |
1748 | | ); |
1749 | | } |
1750 | | |
1751 | | #[test] |
1752 | | fn add_overload_rejects_a_duplicate_signature() { |
1753 | | let mut env = Env::default(); |
1754 | | assert_eq!( |
1755 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop), |
1756 | | Ok(()) |
1757 | | ); |
1758 | | // another id, but the signature is taken |
1759 | | assert_eq!( |
1760 | | env.add_overload("f", "other_id", vec![types::INT_TYPE], noop), |
1761 | | Err(duplicate("f", "other_id")) |
1762 | | ); |
1763 | | } |
1764 | | |
1765 | | #[test] |
1766 | | fn add_member_overload_rejects_a_duplicate_id_or_signature() { |
1767 | | let mut env = Env::default(); |
1768 | | assert_eq!( |
1769 | | env.add_member_overload("f", "int_f", types::INT_TYPE, vec![], noop), |
1770 | | Ok(()) |
1771 | | ); |
1772 | | assert_eq!( |
1773 | | env.add_member_overload("f", "int_f", types::STRING_TYPE, vec![], noop), |
1774 | | Err(duplicate("f", "int_f")) |
1775 | | ); |
1776 | | assert_eq!( |
1777 | | env.add_member_overload("f", "other_id", types::INT_TYPE, vec![], noop), |
1778 | | Err(duplicate("f", "other_id")) |
1779 | | ); |
1780 | | } |
1781 | | |
1782 | | /// An id is unique across the global and member overloads of a function, |
1783 | | /// while a signature also includes whether the overload is a member: `f(int)` |
1784 | | /// and `int.f()` are different overloads, but may not share an id. |
1785 | | #[test] |
1786 | | fn a_global_and_a_member_overload_may_share_a_shape_but_not_an_id() { |
1787 | | let mut env = Env::default(); |
1788 | | assert_eq!( |
1789 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop), |
1790 | | Ok(()) |
1791 | | ); |
1792 | | assert_eq!( |
1793 | | env.add_member_overload("f", "int_f", types::INT_TYPE, vec![], noop), |
1794 | | Ok(()) |
1795 | | ); |
1796 | | assert_eq!( |
1797 | | env.add_member_overload("f", "f_int", types::STRING_TYPE, vec![], noop), |
1798 | | Err(duplicate("f", "f_int")) |
1799 | | ); |
1800 | | } |
1801 | | |
1802 | | /// The same id is fine on another function, and a rejected overload leaves the |
1803 | | /// environment as it was. |
1804 | | #[test] |
1805 | | fn a_rejected_overload_is_not_declared() { |
1806 | | let mut env = Env::default(); |
1807 | | env.add_overload("f", "f_int", vec![types::INT_TYPE], noop) |
1808 | | .unwrap(); |
1809 | | assert!(env |
1810 | | .add_overload("f", "f_dup", vec![types::INT_TYPE], noop) |
1811 | | .is_err()); |
1812 | | assert!(env |
1813 | | .add_overload("g", "f_int", vec![types::INT_TYPE], noop) |
1814 | | .is_ok()); |
1815 | | |
1816 | | let int: Box<dyn Val> = Box::new(crate::common::types::CelInt::from(1)); |
1817 | | assert!(env.find_overload("f", &[CowVal::Owned(int)]).is_some()); |
1818 | | assert!(env.has_overload("f") && env.has_overload("g")); |
1819 | | assert!(!env.has_member_overload("f")); |
1820 | | } |
1821 | | } |