forked from cel-rust/cel-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.rs
More file actions
306 lines (283 loc) · 10.4 KB
/
context.rs
File metadata and controls
306 lines (283 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
use crate::extensions::ExtensionRegistry;
use crate::magic::{Function, FunctionRegistry, IntoFunction};
use crate::objects::{TryIntoValue, Value};
use crate::parser::Expression;
use crate::{functions, ExecutionError};
use std::collections::BTreeMap;
use std::sync::Arc;
/// Context is a collection of variables and functions that can be used
/// by the interpreter to resolve expressions.
///
/// The context can be either a parent context, or a child context. A
/// parent context is created by default and contains all of the built-in
/// functions. A child context can be created by calling `.new_inner_scope()`. The
/// child context has it's own variables (which can be added to), but it
/// will also reference the parent context. This allows for variables to
/// be overridden within the child context while still being able to
/// resolve variables in the child's parents. You can have theoretically
/// have an infinite number of child contexts that reference each-other.
///
/// So why is this important? Well some CEL-macros such as the `.map` macro
/// declare intermediate user-specified identifiers that should only be
/// available within the macro, and should not override variables in the
/// parent context. The `.map` macro can create a child context from the parent, add the
/// intermediate identifier to the child context, and then evaluate the
/// map expression.
///
/// Intermediate variable stored in child context
/// ↓
/// [1, 2, 3].map(x, x * 2) == [2, 4, 6]
/// ↑
/// Only in scope for the duration of the map expression
///
pub enum Context<'a> {
Root {
functions: FunctionRegistry,
variables: BTreeMap<String, Value>,
resolver: Option<&'a dyn VariableResolver>,
extensions: ExtensionRegistry,
container: Option<String>,
},
Child {
parent: &'a Context<'a>,
variables: BTreeMap<String, Value>,
resolver: Option<&'a dyn VariableResolver>,
container: Option<String>,
},
}
impl<'a> Context<'a> {
pub fn add_variable<S, V>(
&mut self,
name: S,
value: V,
) -> Result<(), <V as TryIntoValue>::Error>
where
S: Into<String>,
V: TryIntoValue,
{
match self {
Context::Root { variables, .. } => {
variables.insert(name.into(), value.try_into_value()?);
}
Context::Child { variables, .. } => {
variables.insert(name.into(), value.try_into_value()?);
}
}
Ok(())
}
pub fn add_variable_from_value<S, V>(&mut self, name: S, value: V)
where
S: Into<String>,
V: Into<Value>,
{
match self {
Context::Root { variables, .. } => {
variables.insert(name.into(), value.into());
}
Context::Child { variables, .. } => {
variables.insert(name.into(), value.into());
}
}
}
pub fn set_variable_resolver(&mut self, r: &'a dyn VariableResolver) {
match self {
Context::Root { resolver, .. } => {
*resolver = Some(r);
}
Context::Child { resolver, .. } => {
*resolver = Some(r);
}
}
}
pub fn get_variable<S>(&self, name: S) -> Result<Value, ExecutionError>
where
S: AsRef<str>,
{
let name = name.as_ref();
match self {
Context::Child {
variables,
parent,
resolver,
..
} => resolver
.and_then(|r| r.resolve(name))
.or_else(|| {
variables
.get(name)
.cloned()
.or_else(|| parent.get_variable(name).ok())
})
.ok_or_else(|| ExecutionError::UndeclaredReference(name.to_string().into())),
Context::Root {
variables,
resolver,
..
} => resolver
.and_then(|r| r.resolve(name))
.or_else(|| variables.get(name).cloned())
.ok_or_else(|| ExecutionError::UndeclaredReference(name.to_string().into())),
}
}
pub fn get_extension_registry(&self) -> Option<&ExtensionRegistry> {
match self {
Context::Root { extensions, .. } => Some(extensions),
Context::Child { parent, .. } => parent.get_extension_registry(),
}
}
pub fn get_extension_registry_mut(&mut self) -> Option<&mut ExtensionRegistry> {
match self {
Context::Root { extensions, .. } => Some(extensions),
Context::Child { .. } => None,
}
}
pub(crate) fn get_function(&self, name: &str) -> Option<&Function> {
match self {
Context::Root { functions, .. } => functions.get(name),
Context::Child { parent, .. } => parent.get_function(name),
}
}
pub fn add_function<T: 'static, F>(&mut self, name: &str, value: F)
where
F: IntoFunction<T> + 'static + Send + Sync,
{
if let Context::Root { functions, .. } = self {
functions.add(name, value);
};
}
pub fn resolve(&self, expr: &Expression) -> Result<Value, ExecutionError> {
Value::resolve(expr, self)
}
pub fn resolve_all(&self, exprs: &[Expression]) -> Result<Value, ExecutionError> {
Value::resolve_all(exprs, self)
}
pub fn new_inner_scope(&self) -> Context<'_> {
Context::Child {
parent: self,
variables: Default::default(),
resolver: None,
container: None,
}
}
pub fn with_container(mut self, container: String) -> Self {
match &mut self {
Context::Root { container: c, .. } => {
*c = Some(container);
}
Context::Child { container: c, .. } => {
*c = Some(container);
}
}
self
}
/// Constructs a new empty context with no variables or functions.
///
/// If you're looking for a context that has all the standard methods, functions
/// and macros already added to the context, use [`Context::default`] instead.
///
/// # Example
/// ```
/// use cel::Context;
/// let mut context = Context::empty();
/// context.add_function("add", |a: i64, b: i64| a + b);
/// ```
pub fn empty() -> Self {
Context::Root {
variables: Default::default(),
functions: Default::default(),
resolver: None,
extensions: ExtensionRegistry::new(),
container: None,
}
}
}
impl Default for Context<'_> {
fn default() -> Self {
let mut ctx = Context::Root {
variables: Default::default(),
functions: Default::default(),
resolver: None,
extensions: ExtensionRegistry::new(),
container: None,
};
ctx.add_function("contains", functions::contains);
ctx.add_function("size", functions::size);
ctx.add_function("max", functions::max);
ctx.add_function("min", functions::min);
ctx.add_function("startsWith", functions::starts_with);
ctx.add_function("endsWith", functions::ends_with);
ctx.add_function("string", functions::string);
ctx.add_function("bytes", functions::bytes);
ctx.add_function("double", functions::double);
ctx.add_function("float", functions::float);
ctx.add_function("int", functions::int);
ctx.add_function("uint", functions::uint);
ctx.add_function("optional.none", functions::optional_none);
ctx.add_function("optional.of", functions::optional_of);
ctx.add_function(
"optional.ofNonZeroValue",
functions::optional_of_non_zero_value,
);
ctx.add_function("value", functions::optional_value);
ctx.add_function("hasValue", functions::optional_has_value);
ctx.add_function("or", functions::optional_or_optional);
ctx.add_function("orValue", functions::optional_or_value);
#[cfg(feature = "regex")]
ctx.add_function("matches", functions::matches);
#[cfg(feature = "chrono")]
{
ctx.add_function("duration", functions::duration);
ctx.add_function("timestamp", functions::timestamp);
ctx.add_function("getFullYear", functions::time::timestamp_year);
ctx.add_function("getMonth", functions::time::timestamp_month);
ctx.add_function("getDayOfYear", functions::time::timestamp_year_day);
ctx.add_function("getDayOfMonth", functions::time::timestamp_month_day);
ctx.add_function("getDate", functions::time::timestamp_date);
ctx.add_function("getDayOfWeek", functions::time::timestamp_weekday);
ctx.add_function("getHours", functions::time::timestamp_hours);
ctx.add_function("getMinutes", functions::time::timestamp_minutes);
ctx.add_function("getSeconds", functions::time::timestamp_seconds);
ctx.add_function("getMilliseconds", functions::time::timestamp_millis);
}
ctx
}
}
/// VariableResolver implements a custom resolver for variables that is consulted before looking at
/// variables added to the context. This allows dynamic variables, or avoiding HashMap lookup/creation.
///
///
/// # Example
/// ```
/// struct ValueContext {
/// request: cel::Value,
/// response: cel::Value,
/// }
///
/// impl cel::context::VariableResolver for ValueContext {
/// fn resolve(&self, variable: &str) -> Option<cel::Value> {
/// match variable {
/// "request" => Some(self.request.clone()),
/// "response" => Some(self.response.clone()),
/// _ => None,
/// }
/// }
/// }
/// ```
pub trait VariableResolver: Send + Sync {
fn resolve(&self, variable: &str) -> Option<Value>;
}
impl<T: VariableResolver> VariableResolver for Box<T> {
fn resolve(&self, variable: &str) -> Option<Value> {
(**self).resolve(variable)
}
}
impl<T: VariableResolver> VariableResolver for Arc<T> {
fn resolve(&self, variable: &str) -> Option<Value> {
(**self).resolve(variable)
}
}
impl<T: VariableResolver> VariableResolver for &T {
fn resolve(&self, variable: &str) -> Option<Value> {
(**self).resolve(variable)
}
}