cel 0.15.0

A parser and interpreter for the Common Expression Language (CEL)
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
use crate::common::types::CelType;
use crate::common::value::{CowVal, Val};
use crate::magic::{Function, FunctionRegistry, IntoFunction};
use crate::objects::{TryIntoValue, Value};
use crate::parser::Expression;
use crate::{DeclarationError, Env, ExecutionError};
use std::borrow::Cow;
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
///
/// # Lifetimes
///
/// `'v` bounds the data the context's values may borrow: the
/// [`VariableResolver`] it references and any [`Val`] bound with
/// [`add_variable_as_val`](Context::add_variable_as_val). Values resolved
/// against the context borrow for at most `'v`. `'p` is the borrow of the
/// parent context for a child scope; a root context does not use it.
pub enum Context<'p, 'v> {
    Root {
        functions: FunctionRegistry,
        variables: BTreeMap<String, Box<dyn Val + 'v>>,
        resolver: Option<&'v dyn VariableResolver>,
        env: Arc<Env>,
    },
    Child {
        parent: &'p Context<'p, 'v>,
        variables: BTreeMap<String, Box<dyn Val + 'v>>,
        resolver: Option<&'v dyn VariableResolver>,
    },
}

impl<'p, 'v> Context<'p, 'v> {
    pub fn add_variable<S, V>(
        &mut self,
        name: S,
        value: V,
    ) -> Result<(), <V as TryIntoValue>::Error>
    where
        S: Into<String>,
        V: TryIntoValue,
    {
        let value = value.try_into_value()?;
        let value: Box<dyn Val> = value.try_into().unwrap();
        self.add_variable_as_val(name, value);
        Ok(())
    }

    pub fn add_variable_from_value<S, V>(&mut self, name: S, value: V)
    where
        S: Into<String>,
        V: Into<Value>,
    {
        let value = value.into();
        let value: Box<dyn Val> = value.try_into().unwrap();
        self.add_variable_as_val(name, value);
    }

    /// Binds a variable to a custom [`Val`] implementation directly, without
    /// going through the [`Value`] enum.
    ///
    /// [`add_variable`](Self::add_variable) and
    /// [`add_variable_from_value`](Self::add_variable_from_value) convert their
    /// input into a [`Value`], whose compound variants ([`Value::Map`],
    /// [`Value::List`], and `Value::Struct`) hold eagerly-materialized contents.
    /// For a value that should resolve its contents *on access* instead — e.g.
    /// a large or recursive backing object (a protobuf message, a database
    /// row) where member access maps to
    /// [`Indexer::get`](crate::common::traits::Indexer::get) and is computed
    /// lazily — implement [`Val`] and the relevant operator traits (such as
    /// [`Indexer`](crate::common::traits::Indexer),
    /// [`Iterable`](crate::common::traits::Iterable),
    /// [`Sizer`](crate::common::traits::Sizer)) for your type and bind it here.
    /// The built-in implementations in
    /// [`common::types`](crate::common::types) (e.g. `DefaultMap`, `Struct`)
    /// are the reference for what to implement.
    ///
    /// The value may borrow data for `'v`, for example a
    /// [`CelString`](crate::common::types::CelString) built from a `&'v str`.
    ///
    /// ```ignore
    /// // `my_value` implements `Val` + `Indexer`, resolving fields on access.
    /// let env = Arc::new(Env::stdlib());
    /// let mut ctx = Context::with_env(Arc::clone(&env));
    /// ctx.add_variable_as_val("input", Box::new(my_value));
    /// let program = env.compile("input.field")?;
    /// // `input.field` calls `Indexer::get` on `my_value` only when evaluated.
    /// let result = program.execute(&ctx)?;
    /// ```
    pub fn add_variable_as_val<S>(&mut self, name: S, value: Box<dyn Val + 'v>)
    where
        S: Into<String>,
    {
        match self {
            Context::Root { variables, .. } => {
                variables.insert(name.into(), value);
            }
            Context::Child { variables, .. } => {
                variables.insert(name.into(), value);
            }
        }
    }

    pub fn set_variable_resolver(&mut self, r: &'v dyn VariableResolver) {
        match self {
            Context::Root { resolver, .. } => {
                *resolver = Some(r);
            }
            Context::Child { resolver, .. } => {
                *resolver = Some(r);
            }
        }
    }

    /// Looks a variable up: the resolver first, then this scope's variables,
    /// then the parent scopes. The result borrows from the context where it
    /// can and is bounded by `'v` where the resolver or a bound value
    /// borrows data.
    pub fn get_variable<'b, S>(&'b self, name: S) -> Option<CowVal<'b, 'v>>
    where
        S: AsRef<str>,
    {
        let name = name.as_ref();
        self.scopes().find_map(|scope| scope.own_variable(name))
    }

    /// This scope, then its parents, innermost first.
    fn scopes<'b>(&'b self) -> impl Iterator<Item = &'b Context<'p, 'v>> {
        std::iter::successors(Some(self), |scope| match scope {
            Context::Child { parent, .. } => Some(*parent),
            Context::Root { .. } => None,
        })
    }

    /// The scopes `name` may be resolved in: an absolute name, one with a
    /// leading dot, skips the inner ones.
    fn scopes_for<'b>(&'b self, name: &str) -> impl Iterator<Item = &'b Context<'p, 'v>> {
        let absolute = name.starts_with('.');
        self.scopes()
            .filter(move |scope| !absolute || matches!(scope, Context::Root { .. }))
    }

    /// A variable of this scope alone.
    fn own_variable<'b>(&'b self, name: &str) -> Option<CowVal<'b, 'v>> {
        let (variables, resolver) = match self {
            Context::Child {
                variables,
                resolver,
                ..
            }
            | Context::Root {
                variables,
                resolver,
                ..
            } => (variables, resolver),
        };
        resolver
            .and_then(|r| r.resolve(name))
            .or_else(|| variables.get(name).map(|v| CowVal::Borrowed(v.as_ref())))
    }

    pub(crate) fn env(&self) -> &Env {
        match self {
            Context::Root { env, .. } => env.as_ref(),
            Context::Child { parent, .. } => parent.env(),
        }
    }

    /// Whether a function named `namespace.…` is declared, in the `Env` or
    /// added to the root context.
    pub(crate) fn has_function_namespace(&self, namespace: &str) -> bool {
        match self {
            Context::Root { functions, env, .. } => {
                env.has_namespace(namespace) || functions.has_namespace(namespace)
            }
            Context::Child { parent, .. } => parent.has_function_namespace(namespace),
        }
    }

    /// Resolves `name` as an identifier: the innermost scope that has it
    /// wins, and within a scope the variable, else the type, of each
    /// container candidate in turn, most specific first. An absolute name
    /// skips the inner scopes.
    pub(crate) fn resolve_ident(&self, name: &str) -> Option<CowVal<'_, 'v>> {
        self.scopes_for(name)
            .find_map(|scope| scope.resolve_own(name, true))
    }

    /// Resolves the qualified name `a.b.c`, given as its segments, to a value
    /// and the fields left to select on it.
    ///
    /// The innermost scope that has any of it wins. Within a scope, as in
    /// cel-go, the most specific name wins: the variable `a.b.c`, else the
    /// type `a.b.c`, else the variable `a.b` with `c` left to select, else the
    /// variable `a` with `b` and `c` left. Only the whole name can be a type,
    /// as types have no fields.
    pub(crate) fn resolve_qualified<'b, 's>(
        &'b self,
        segments: &'s [&'b str],
    ) -> Result<(CowVal<'b, 'v>, &'s [&'b str]), ExecutionError> {
        let name = segments.join(".");
        for scope in self.scopes_for(&name) {
            let mut len = name.len();
            for prefix in (1..=segments.len()).rev() {
                let whole = prefix == segments.len();
                if let Some(value) = scope.resolve_own(&name[..len], whole) {
                    return Ok((value, &segments[prefix..]));
                }
                // drop the last segment and its dot
                len = len.saturating_sub(segments[prefix - 1].len() + 1);
            }
        }
        Err(ExecutionError::UndeclaredReference(Arc::new(
            segments[0].to_owned(),
        )))
    }

    /// The variable of this scope named by a container candidate of `name`,
    /// else, in the root scope, the type, if `may_be_type`.
    fn resolve_own(&self, name: &str, may_be_type: bool) -> Option<CowVal<'_, 'v>> {
        let env = self.env();
        env.container().candidates(name).find_map(|candidate| {
            self.own_variable(&candidate).or_else(|| {
                if !may_be_type || !matches!(self, Context::Root { .. }) {
                    return None;
                }
                let t = env.types().find_type(&candidate)?;
                Some(CowVal::owned(CelType::from(t)))
            })
        })
    }

    /// The struct type `name` names under the container.
    pub(crate) fn find_struct(&self, name: &str) -> Option<&dyn crate::StructType> {
        let types = self.env().types();
        self.env()
            .container()
            .candidates(name)
            .find_map(|candidate| types.find_struct(&candidate))
    }

    fn has_function(&self, name: &str) -> bool {
        self.env().has_overload(name) || self.get_function(name).is_some()
    }

    /// The global function a call to `name` calls under the container: the
    /// first candidate that is declared, else the plain name, which then
    /// reports itself undeclared. The plain name, the only candidate without
    /// a container, is not checked here: the call does that.
    pub(crate) fn resolve_function<'n>(&self, name: &'n str) -> Cow<'n, str> {
        let mut candidates = self.env().container().candidates(name).peekable();
        while let Some(candidate) = candidates.next() {
            if candidates.peek().is_none() || self.has_function(&candidate) {
                return candidate;
            }
        }
        Cow::Borrowed(name)
    }

    /// The name of the function a call on `target` names when `target` spells a
    /// qualified name that, with `func_name`, names a declared function:
    /// `a.b.f()` calls the function `a.b.f`, rather than `f` on `a.b`, under
    /// the container too. Mirrors cel-go's `resolveFunction`, deciding on the
    /// name alone, but on every evaluation: a target whose first segment is no
    /// function's namespace, as most are, is told apart without allocating.
    pub(crate) fn resolve_qualified_function(
        &self,
        target: &Expression,
        func_name: &str,
    ) -> Option<String> {
        let container = self.env().container();
        let root = target.expr.qualified_name_root()?;
        if !container
            .candidates(root)
            .any(|c| self.has_function_namespace(c.split('.').next().unwrap_or_default()))
        {
            return None;
        }
        let segments = target.expr.qualified_name_segments()?;
        let name = format!("{}.{func_name}", segments.join("."));
        let found = container
            .candidates(&name)
            .find(|candidate| self.has_function(candidate))
            .map(Cow::into_owned);
        found
    }

    #[allow(dead_code)]
    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),
        }
    }

    /// Adds a function, callable by `name` both as `name(..)` and as a method.
    ///
    /// # Errors
    ///
    /// Fails with [`DeclarationError::OverloadConflict`] if `name` is already
    /// declared as an overload in this context's [`Env`], whether a function or a
    /// member function. When a call is resolved, overloads take precedence over
    /// the functions added here: the function would be shadowed for every call an
    /// overload accepts, and only be reached for the others, so which of the two
    /// answers would depend on the types of the arguments. The standard library
    /// declares overloads for `size`, `contains`, `startsWith`, `string`,
    /// `int`, ... Choose another name, or declare it as an overload with
    /// [`Env::add_overload`] instead.
    ///
    /// # Example
    /// ```
    /// use cel::{Context, DeclarationError};
    ///
    /// let mut context = Context::default();
    /// context.add_function("add", |a: i64, b: i64| a + b).unwrap();
    ///
    /// // `size` is declared as an overload by the standard library
    /// assert_eq!(
    ///     context.add_function("size", |a: i64| a),
    ///     Err(DeclarationError::overload_conflict("size")),
    /// );
    /// ```
    pub fn add_function<T: 'static, F>(
        &mut self,
        name: &str,
        value: F,
    ) -> Result<(), DeclarationError>
    where
        F: IntoFunction<T> + 'static + Send + Sync,
    {
        if let Context::Root { functions, env, .. } = self {
            if env.has_overload(name) || env.has_member_overload(name) {
                return Err(DeclarationError::overload_conflict(name));
            }
            functions.add(name, value);
        };
        Ok(())
    }

    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)
    }

    /// Creates a child scope that borrows this context as its parent. Values
    /// bound in the child keep the parent's `'v`, so a value resolved in the
    /// child scope can outlive the child.
    pub fn new_inner_scope<'b>(&'b self) -> Context<'b, 'v> {
        Context::Child {
            parent: self,
            variables: Default::default(),
            resolver: None,
        }
    }

    /// 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).unwrap();
    /// ```
    pub fn empty() -> Self {
        Context::Root {
            env: Arc::new(Env::default()),
            variables: Default::default(),
            functions: Default::default(),
            resolver: None,
        }
    }

    pub fn with_env(env: Arc<Env>) -> Self {
        Context::Root {
            env,
            variables: Default::default(),
            functions: Default::default(),
            resolver: None,
        }
    }
}

impl Default for Context<'_, '_> {
    fn default() -> Self {
        Context::Root {
            env: Arc::new(Env::stdlib()),
            variables: Default::default(),
            functions: Default::default(),
            resolver: None,
        }
    }
}

/// 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.
///
/// Unlike [`add_variable`](Context::add_variable) and
/// [`add_variable_from_value`](Context::add_variable_from_value), which convert their input once
/// at bind time, `resolve` runs on *every* lookup of the variable - including every reference to
/// it inside a loop or comprehension. It returns a [`CowVal`] directly (see
/// [`add_variable_as_val`](Context::add_variable_as_val)) rather than a [`Value`], so a resolver
/// backed by something already `Val`-shaped (or by a lazy/recursive object best wrapped directly,
/// per `add_variable_as_val`'s doc) never has to round-trip through `Value` on the hot path - and
/// one that already owns persistent `Val` data (e.g. a table of pre-built values) can hand back a
/// `CowVal::Borrowed` into `self` instead of cloning on every lookup. The value may borrow from
/// the resolver itself, e.g. a [`CelString`](crate::common::types::CelString) built from a `&str`
/// the resolver holds, avoiding a copy.
///
/// # Example
/// ```
/// use cel::common::value::CowVal;
///
/// struct ValueContext {
///     request: cel::Value,
///     response: cel::Value,
/// }
///
/// impl cel::context::VariableResolver for ValueContext {
///     fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
///         let value = match variable {
///             "request" => self.request.clone(),
///             "response" => self.response.clone(),
///             _ => return None,
///         };
///         value.try_into().ok().map(CowVal::Owned)
///     }
/// }
/// ```
///
/// Borrowing instead of copying:
/// ```
/// use cel::common::types::CelString;
/// use cel::common::value::CowVal;
///
/// struct Names<'a> {
///     name: &'a str,
/// }
///
/// impl cel::context::VariableResolver for Names<'_> {
///     fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
///         match variable {
///             // `CelString::from(&str)` borrows: no copy of the bytes
///             "name" => Some(CowVal::owned(CelString::from(self.name))),
///             _ => None,
///         }
///     }
/// }
/// ```
pub trait VariableResolver: Send + Sync {
    fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>>;
}

impl<T: VariableResolver> VariableResolver for Box<T> {
    fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
        (**self).resolve(variable)
    }
}

impl<T: VariableResolver> VariableResolver for Arc<T> {
    fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
        (**self).resolve(variable)
    }
}

impl<T: VariableResolver> VariableResolver for &T {
    fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
        (**self).resolve(variable)
    }
}

#[cfg(test)]
mod test {
    use super::{Context, VariableResolver};
    use crate::common::types::CelString;
    use crate::common::value::CowVal;

    // A helper function that requires T to implement some traits
    fn assert_send<T: Send>() {}

    #[test]
    fn test_context_is_send() {
        // This line will only compile if assertion passes
        assert_send::<super::Context>();
    }

    /// A [`VariableResolver`] can hand back a lazy, `Indexer`-backed [`Val`] directly -
    /// something with no [`Value`] representation at all - rather than being forced to
    /// produce one. Field access on it should still call straight into `Indexer::get`.
    #[test]
    fn test_variable_resolver_returns_val_directly() {
        use crate::common::traits::Indexer;
        use crate::common::types::{CelInt, Type, DYN_TYPE};
        use crate::common::value::{CowVal, Val};
        use crate::{Context, ExecutionError, Program, Value};

        #[derive(Debug)]
        struct Lazy;

        impl Val for Lazy {
            fn get_type(&self) -> &Type {
                &DYN_TYPE
            }

            fn cel_type() -> &'static Type {
                &DYN_TYPE
            }

            fn as_indexer<'b, 'v>(&'b self) -> Option<&'b (dyn Indexer + 'v)>
            where
                Self: 'v,
            {
                Some(self)
            }

            fn clone_as_boxed<'v>(&self) -> Box<dyn Val + 'v> {
                Box::new(Lazy)
            }
        }

        impl Indexer for Lazy {
            fn get<'b, 'v>(&'b self, _idx: &dyn Val) -> Result<CowVal<'b, 'v>, ExecutionError>
            where
                Self: 'v,
            {
                Ok(CowVal::owned(CelInt::from(42)))
            }

            fn steal<'v>(
                self: Box<Self>,
                _idx: &dyn Val,
            ) -> Result<Box<dyn Val + 'v>, ExecutionError>
            where
                Self: 'v,
            {
                Ok(Box::new(CelInt::from(42)))
            }
        }

        struct LazyResolver;

        impl super::VariableResolver for LazyResolver {
            fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
                (variable == "input").then(|| CowVal::owned(Lazy))
            }
        }

        let mut ctx = Context::default();
        ctx.set_variable_resolver(&LazyResolver);
        let program = Program::compile("input.anything").unwrap();
        assert_eq!(program.execute(&ctx), Ok(Value::Int(42)));
    }

    /// A [`VariableResolver`] that already owns persistent `Val` data (e.g. a table of
    /// pre-built values) can hand back a `CowVal::Borrowed` into itself instead of cloning
    /// on every lookup - including every reference to the same variable within one
    /// expression.
    #[test]
    fn test_variable_resolver_can_borrow() {
        use crate::common::types::{Type, DYN_TYPE};
        use crate::common::value::{CowVal, Val};
        use crate::{Context, Program};
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        #[derive(Debug)]
        struct CountedVal(Arc<AtomicUsize>);

        impl Val for CountedVal {
            fn get_type(&self) -> &Type {
                &DYN_TYPE
            }

            fn cel_type() -> &'static Type {
                &DYN_TYPE
            }

            fn clone_as_boxed<'v>(&self) -> Box<dyn Val + 'v> {
                self.0.fetch_add(1, Ordering::SeqCst);
                Box::new(CountedVal(self.0.clone()))
            }
        }

        struct BorrowResolver(Box<dyn Val>);

        impl super::VariableResolver for BorrowResolver {
            fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
                (variable == "counted").then(|| CowVal::Borrowed(self.0.as_ref()))
            }
        }

        let clones = Arc::new(AtomicUsize::new(0));
        let resolver = BorrowResolver(Box::new(CountedVal(clones.clone())));
        let mut ctx = Context::default();
        ctx.set_variable_resolver(&resolver);

        // Referenced twice - a per-lookup clone would show up as 2, not 0.
        let program = Program::compile("counted == counted").unwrap();
        program.execute(&ctx).unwrap();

        assert_eq!(clones.load(Ordering::SeqCst), 0);
    }

    struct Borrowing<'a>(&'a str);

    impl VariableResolver for Borrowing<'_> {
        fn resolve<'b>(&'b self, variable: &str) -> Option<CowVal<'b, 'b>> {
            (variable == "s").then(|| CowVal::owned(CelString::from(self.0)))
        }
    }

    /// A borrowed string survives a whole evaluation without being copied,
    /// through a conditional, a `string()` call, an optional, a list index,
    /// a map field, and a comprehension.
    #[test]
    fn resolver_value_borrows_through_a_full_evaluation() {
        use crate::parser::Parser;
        use crate::Value;

        let owned = String::from("cel-rust");
        let resolver = Borrowing(owned.as_str());
        let mut ctx = Context::default();
        ctx.set_variable_resolver(&resolver);
        for expr in [
            "s",
            "s == 'cel-rust' ? s : 'other'",
            "string(s)",
            "dyn(s)",
            "optional.of(s).value()",
            "optional.of(s).orValue('other')",
            "[s][0]",
            "{'k': s}.k",
            "{'k': s}['k']",
            "[s].map(x, x)[0]",
            "[1].map(x, s)[0]",
        ] {
            let ast = Parser::default()
                .enable_optional_syntax(true)
                .parse(expr)
                .unwrap();
            let v = Value::resolve_val(&ast, &ctx).unwrap();
            let s = v.downcast_ref::<CelString>().unwrap();
            assert!(
                std::ptr::eq(s.inner(), owned.as_str()),
                "`{expr}` copied the string"
            );
        }
    }

    #[test]
    fn resolver_value_borrows_through_the_context_and_a_child_scope() {
        let owned = String::from("cel-rust");
        let resolver = Borrowing(owned.as_str());
        let mut ctx = Context::default();
        ctx.set_variable_resolver(&resolver);
        let inner = ctx.new_inner_scope();
        let v = inner.get_variable("s").unwrap();
        let s = v.downcast_ref::<CelString>().unwrap();
        assert!(std::ptr::eq(s.inner(), owned.as_str()));
        // the value outlives the child scope: it is bounded by `'v`, not by
        // the scope borrow
        let escaped: Box<dyn crate::common::value::Val + '_> = v.into_owned();
        drop(inner);
        let s = escaped.downcast_ref::<CelString>().unwrap();
        assert!(std::ptr::eq(s.inner(), owned.as_str()));
    }

    /// Overloads take precedence over the functions added to a `Context`, so a
    /// function may not reuse the name of one: a global overload, a member
    /// overload, both, or a namespaced one.
    #[test]
    fn add_function_rejects_a_name_declared_as_an_overload() {
        use crate::{Context, DeclarationError};

        let mut context = Context::default();
        for name in ["int", "startsWith", "size", "optional.of"] {
            assert_eq!(
                context.add_function(name, |a: i64| a),
                Err(DeclarationError::overload_conflict(name)),
                "{name}"
            );
        }
    }

    #[test]
    fn add_function_accepts_a_name_no_overload_uses() {
        use crate::{Context, Program};

        let mut context = Context::default();
        assert_eq!(context.add_function("add", |a: i64, b: i64| a + b), Ok(()));
        let program = Program::compile("add(2, 3)").unwrap();
        assert_eq!(program.execute(&context), Ok(5.into()));
    }

    /// A rejected function must not be registered anyway: were it, `size(1)`
    /// (which no `size` overload accepts) would fall through to it.
    #[test]
    fn a_rejected_function_is_not_registered() {
        use crate::{Context, ExecutionError, Program};

        let mut context = Context::default();
        assert!(context.add_function("size", |_: i64| 42_i64).is_err());

        let program = Program::compile("size(1)").unwrap();
        assert!(matches!(
            program.execute(&context),
            Err(ExecutionError::NoSuchOverload(_))
        ));
        let program = Program::compile("size('abc')").unwrap();
        assert_eq!(program.execute(&context), Ok(3.into()));
    }

    /// The conflict is with the overloads of the context's own `Env`: an empty
    /// one declares none, so the standard names are free.
    #[test]
    fn add_function_only_conflicts_with_the_overloads_of_its_env() {
        use crate::common::types::INT_TYPE;
        use crate::common::value::CowVal;
        use crate::{Context, DeclarationError, Env, ExecutionError};
        use std::sync::Arc;

        assert_eq!(Context::empty().add_function("size", |a: i64| a), Ok(()),);

        fn custom<'b, 'v>(args: Vec<CowVal<'b, 'v>>) -> Result<CowVal<'b, 'v>, ExecutionError> {
            Ok(args.into_iter().next().unwrap())
        }
        let mut env = Env::default();
        env.add_overload("custom", "custom_int", vec![INT_TYPE], custom)
            .unwrap();
        let mut context = Context::with_env(Arc::new(env));
        assert_eq!(
            context.add_function("custom", |a: i64| a),
            Err(DeclarationError::overload_conflict("custom")),
        );
        assert_eq!(context.add_function("other", |a: i64| a), Ok(()));
    }

    #[test]
    fn add_function_on_a_child_is_a_silent_noop_ignores_dups() {
        use crate::Context;

        let context = Context::default();
        let mut child = context.new_inner_scope();
        assert_eq!(child.add_function("size", |a: i64| a), Ok(()),);
    }

    #[test]
    fn a_qualified_function_declares_its_namespace() {
        let mut context = Context::default();
        context.add_function("a.b.f", |i: i64| i).unwrap();
        context.add_function("g", |i: i64| i).unwrap();
        assert!(context.has_function_namespace("a"));
        assert!(!context.has_function_namespace("g"));
        assert!(context.has_function_namespace("optional"), "from the Env");
        assert!(context.new_inner_scope().has_function_namespace("a"));
    }

    /// Type names are resolved by the interpreter, not looked up as variables.
    #[test]
    fn a_type_name_is_not_a_variable() {
        let context = Context::default();
        assert!(context.get_variable("int").is_none());
        assert!(context.new_inner_scope().get_variable("int").is_none());
    }
}