cel-cxx 0.2.5

A high-performance, type-safe Rust interface for Common Expression Language (CEL), build on top of cel-cpp with zero-cost FFI bindings via cxx
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
//! Activation context for expression evaluation.
//!
//! This module provides the [`Activation`] type, which serves as the runtime context
//! for CEL expression evaluation. Activations contain variable bindings and function
//! implementations that are used during expression evaluation.
//!
//! # Key Concepts
//!
//! ## Activation Interface
//!
//! The [`ActivationInterface`] trait defines the contract for providing variable
//! and function bindings to the CEL evaluator. It provides access to:
//!
//! - **Variable bindings**: Map variable names to runtime values
//! - **Function bindings**: Provide runtime function implementations
//!
//! ## Activation Types
//!
//! The module provides several activation types:
//!
//! - **`Activation<'f>`**: Standard activation for synchronous evaluation
//! - **`AsyncActivation<'f>`**: Activation with async function support
//! - **`()`**: Empty activation for expressions without variables/functions
//!
//! # Variable Binding
//!
//! Variables can be bound to values that match the types declared in the environment:
//!
//! ```rust,no_run
//! use cel_cxx::*;
//!
//! let activation = Activation::new()
//!     .bind_variable("user_name", "Alice".to_string())?
//!     .bind_variable("user_age", 30i64)?
//!     .bind_variable("is_admin", true)?;
//! # Ok::<(), cel_cxx::Error>(())
//! ```
//!
//! # Function Binding
//!
//! Functions can be bound at runtime to override or supplement environment functions:
//!
//! ```rust,no_run
//! use cel_cxx::*;
//!
//! let activation = Activation::new()
//!     .bind_global_function("custom_add", |a: i64, b: i64| a + b)?
//!     .bind_member_function("to_upper", |s: String| s.to_uppercase())?;
//! # Ok::<(), cel_cxx::Error>(())
//! ```
//!
//! # Variable Providers
//!
//! For dynamic or computed values, you can bind variable providers:
//!
//! ```rust,no_run
//! use cel_cxx::*;
//!
//! let activation = Activation::new()
//!     .bind_variable_provider("current_time", || {
//!         std::time::SystemTime::now()
//!             .duration_since(std::time::UNIX_EPOCH)
//!             .unwrap()
//!             .as_secs() as i64
//!     })?;
//! # Ok::<(), cel_cxx::Error>(())
//! ```
//!
//! # Empty Activations
//!
//! For expressions that don't require any bindings, you can use the unit type:
//!
//! ```rust,no_run
//! use cel_cxx::*;
//!
//! let env = Env::builder().build()?;
//! let program = env.compile("1 + 2 * 3")?;
//! let result = program.evaluate(())?; // No activation needed
//! # Ok::<(), cel_cxx::Error>(())
//! ```
//!
//! # Async Support
//!
//! When the `async` feature is enabled, activations can contain async functions:
//!
//! ```rust,no_run
//! # #[cfg(feature = "async")]
//! # async fn example() -> Result<(), cel_cxx::Error> {
//! use cel_cxx::*;
//!
//! let activation = AsyncActivation::new_async()
//!     .bind_global_function("fetch_data", |url: String| async move {
//!         // Simulate async work
//!         format!("Data from {}", url)
//!     })?;
//! # Ok(())
//! # }
//! ```

use crate::function::FunctionBindings;
use crate::function::{Arguments, NonEmptyArguments, IntoFunction};
use crate::marker::*;
use crate::values::{IntoValue, StructValue, TypedValue};
use crate::variable::VariableBindings;
use crate::Error;
use std::marker::PhantomData;

/// Interface for providing variable and function bindings during evaluation.
///
/// This trait defines the interface that activation types must implement
/// to provide variable and function bindings to the CEL evaluator.
///
/// # Type Parameters
///
/// * `'f` - Lifetime of the functions in the bindings
/// * `Fm` - Function marker type indicating sync/async function support
pub trait ActivationInterface<'f, Fm: FnMarker = ()> {
    /// Returns a reference to the variable bindings.
    ///
    /// Variable bindings map variable names to their values during evaluation.
    fn variables(&self) -> &VariableBindings<'f>;

    /// Returns a reference to the function bindings.
    ///
    /// Function bindings provide runtime function implementations that can
    /// override or supplement the functions registered in the environment.
    fn functions(&self) -> &FunctionBindings<'f>;
}

/// Activation context for CEL expression evaluation.
///
/// An `Activation` provides variable and function bindings that are used
/// during the evaluation of a CEL expression. It allows you to bind runtime
/// values to variables and functions that were declared in the environment.
///
/// # Type Parameters
///
/// * `'f` - Lifetime of the functions in the activation
/// * `Fm` - Function marker type indicating sync/async function support
///
/// # Examples
///
/// ## Basic Variable Binding
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let activation = Activation::new()
///     .bind_variable("name", "Alice")
///     .unwrap()
///     .bind_variable("age", 30i64)
///     .unwrap();
/// ```
///
/// ## Function Binding
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let activation = Activation::new()
///     .bind_global_function("custom_fn", |x: i64| -> i64 { x * 2 })
///     .unwrap();
/// ```
///
/// ## Empty Activation
///
/// For expressions that don't need any bindings, you can use `()`:
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let env = Env::builder().build().unwrap();
/// let program = env.compile("1 + 2").unwrap();
/// let result = program.evaluate(()).unwrap();
/// ```
pub struct Activation<'f, Fm: FnMarker = ()> {
    variables: VariableBindings<'f>,
    functions: FunctionBindings<'f>,
    _fn_marker: PhantomData<Fm>,
}

/// Activation with async support.
///
/// This is a convenience type that can be used to create activations with
/// async support. It is equivalent to `Activation<'f, Async>`.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let activation = AsyncActivation::new_async();
/// ```
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub type AsyncActivation<'f> = Activation<'f, Async>;

impl<'f> Default for Activation<'f, ()> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'f> Activation<'f, ()> {
    /// Creates a new empty activation.
    ///
    /// This creates an activation with no variable or function bindings.
    /// You can then use the builder methods to add bindings.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let activation = Activation::new();
    /// ```
    pub fn new() -> Self {
        Self {
            variables: VariableBindings::new(),
            functions: FunctionBindings::new(),
            _fn_marker: PhantomData,
        }
    }

    /// Force the activation to be async.
    ///
    /// This method is only available when the `async` feature is enabled.
    /// It converts the activation to an `AsyncActivation`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let activation = Activation::new().force_async();
    /// ```
    #[cfg(feature = "async")]
    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
    pub fn force_async(self) -> Activation<'f, Async> {
        Activation {
            variables: self.variables,
            functions: self.functions,
            _fn_marker: PhantomData,
        }
    }
}

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
impl<'f> Activation<'f, Async> {
    /// Creates a new empty activation with async support.
    ///
    /// This creates an activation with no variable or function bindings.
    /// You can then use the builder methods to add bindings.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let activation = Activation::new_async();
    /// ```
    pub fn new_async() -> Self {
        Self {
            variables: VariableBindings::new(),
            functions: FunctionBindings::new(),
            _fn_marker: PhantomData,
        }
    }
}

impl<'f, Fm: FnMarker> Activation<'f, Fm> {
    /// Binds a variable to a value.
    ///
    /// This method adds a variable binding to the activation. The variable
    /// name must match a variable declared in the environment, and the value
    /// must be compatible with the declared type.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the variable to bind
    /// * `value` - The value to bind to the variable
    ///
    /// # Type Parameters
    ///
    /// * `S` - The type of the variable name (must convert to `String`)
    /// * `T` - The type of the value (must implement `IntoValue` and `TypedValue`)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the updated activation or an error if
    /// the binding failed.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let activation = Activation::new()
    ///     .bind_variable("name", "World")
    ///     .unwrap()
    ///     .bind_variable("count", 42i64)
    ///     .unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The variable name is not declared in the environment
    /// - The value type doesn't match the declared variable type
    /// - The value cannot be converted to a CEL value
    pub fn bind_variable<S, T>(mut self, name: S, value: T) -> Result<Self, Error>
    where
        S: Into<String>,
        T: IntoValue + TypedValue,
    {
        self.variables.bind(name, value)?;
        Ok(Activation {
            variables: self.variables,
            functions: self.functions,
            _fn_marker: PhantomData,
        })
    }

    /// Binds a runtime-typed variable from a [`StructValue`].
    ///
    /// Unlike [`bind_variable`](Self::bind_variable), which infers the CEL type
    /// from the Rust type via the `TypedValue` trait, this method accepts a
    /// [`StructValue`] whose type name and serialized bytes are supplied at
    /// runtime. The type name must match a type declared via
    /// [`EnvBuilder::declare_variable_with_type`](crate::EnvBuilder::declare_variable_with_type),
    /// and the environment must include the corresponding `FileDescriptorSet`.
    ///
    /// For lazily-computed values, see
    /// [`bind_variable_provider`](Self::bind_variable_provider) instead.
    ///
    /// # Arguments
    ///
    /// * `name` - The variable name (must match a declared variable)
    /// * `value` - The [`StructValue`] to bind
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// # let serialized_bytes: Vec<u8> = vec![];
    /// let activation = Activation::new()
    ///     .bind_variable_dynamic("msg", StructValue::from_bytes("my.package.MyMessage", serialized_bytes))?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn bind_variable_dynamic<S>(
        mut self,
        name: S,
        value: StructValue,
    ) -> Result<Self, Error>
    where
        S: Into<String>,
    {
        self.variables.bind_with_value(
            name,
            crate::ValueType::Struct(crate::types::StructType::new(value.type_name())),
            value.into_value(),
        )?;
        Ok(Activation {
            variables: self.variables,
            functions: self.functions,
            _fn_marker: PhantomData,
        })
    }

    /// Binds a variable to a value provider.
    ///
    /// This method allows you to bind a variable to a provider function that
    /// will be called to get the value when the variable is accessed during
    /// evaluation. This can be useful for lazy evaluation or for variables
    /// whose values are expensive to compute.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the variable to bind
    /// * `provider` - The provider function that will supply the value
    ///
    /// # Type Parameters
    ///
    /// * `S` - The type of the variable name (must convert to `String`)
    /// * `F` - The provider function type (must implement `IntoFunction`)
    /// * `Ffm` - The function marker type (sync/async)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the updated activation with the appropriate
    /// function marker type, or an error if the binding failed.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let activation = Activation::new()
    ///     .bind_variable_provider("timestamp", || -> i64 {
    ///         std::time::SystemTime::now()
    ///             .duration_since(std::time::UNIX_EPOCH)
    ///             .unwrap()
    ///             .as_secs() as i64
    ///     })
    ///     .unwrap();
    /// ```
    pub fn bind_variable_provider<S, F, Ffm>(
        mut self,
        name: S,
        provider: F,
    ) -> Result<Activation<'f, <Ffm as FnMarkerAggr<Fm>>::Output>, Error>
    where
        S: Into<String>,
        F: IntoFunction<'f, Ffm>,
        Ffm: FnMarkerAggr<Fm>,
    {
        self.variables.bind_provider(name, provider)?;
        Ok(Activation {
            variables: self.variables,
            functions: self.functions,
            _fn_marker: PhantomData,
        })
    }

    /// Binds a function (either global or member).
    ///
    /// This method allows you to bind a function implementation that can be
    /// called during expression evaluation. The function can be either a
    /// global function or a member function.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the function to bind
    /// * `member` - Whether this is a member function (`true`) or global function (`false`)
    /// * `f` - The function implementation
    ///
    /// # Type Parameters
    ///
    /// * `S` - The type of the function name (must convert to `String`)
    /// * `F` - The function implementation type (must implement `IntoFunction`)
    /// * `Ffm` - The function marker type (sync/async)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the updated activation with the appropriate
    /// function marker type, or an error if the binding failed.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// // Bind a global function
    /// let activation = Activation::new()
    ///     .bind_function("double", false, |x: i64| -> i64 { x * 2 })
    ///     .unwrap();
    ///
    /// // Bind a member function
    /// let activation = Activation::new()
    ///     .bind_function("to_upper", true, |s: String| -> String { s.to_uppercase() })
    ///     .unwrap();
    /// ```
    pub fn bind_function<S, F, Ffm, Args>(
        mut self,
        name: S,
        member: bool,
        f: F,
    ) -> Result<Activation<'f, <Ffm as FnMarkerAggr<Fm>>::Output>, Error>
    where
        S: Into<String>,
        F: IntoFunction<'f, Ffm, Args>,
        Ffm: FnMarkerAggr<Fm>,
        Args: Arguments,
    {
        self.functions.bind(name, member, f)?;
        Ok(Activation {
            variables: self.variables,
            functions: self.functions,
            _fn_marker: PhantomData,
        })
    }

    /// Binds a member function.
    ///
    /// This is a convenience method for binding member functions (functions that
    /// are called as methods on values, like `value.method()`).
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the function to bind
    /// * `f` - The function implementation
    ///
    /// # Type Parameters
    ///
    /// * `S` - The type of the function name (must convert to `String`)
    /// * `F` - The function implementation type (must implement `IntoFunction`)
    /// * `Ffm` - The function marker type (sync/async)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the updated activation with the appropriate
    /// function marker type, or an error if the binding failed.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let activation = Activation::new()
    ///     .bind_member_function("to_upper", |s: String| -> String { s.to_uppercase() })
    ///     .unwrap();
    /// ```
    pub fn bind_member_function<S, F, Ffm, Args>(
        self,
        name: S,
        f: F,
    ) -> Result<Activation<'f, <Ffm as FnMarkerAggr<Fm>>::Output>, Error>
    where
        S: Into<String>,
        F: IntoFunction<'f, Ffm, Args>,
        Ffm: FnMarkerAggr<Fm>,
        Args: Arguments + NonEmptyArguments,
    {
        self.bind_function(name, true, f)
    }

    /// Binds a global function.
    ///
    /// This is a convenience method for binding global functions (functions that
    /// can be called from any context).
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the function to bind
    /// * `f` - The function implementation
    ///
    /// # Type Parameters
    ///
    /// * `S` - The type of the function name (must convert to `String`)
    /// * `F` - The function implementation type (must implement `IntoFunction`)
    /// * `Ffm` - The function marker type (sync/async)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the updated activation with the appropriate
    /// function marker type, or an error if the binding failed.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let activation = Activation::new()
    ///     .bind_global_function("double", |x: i64| -> i64 { x * 2 })
    ///     .unwrap();
    /// ```
    pub fn bind_global_function<S, F, Ffm, Args>(
        self,
        name: S,
        f: F,
    ) -> Result<Activation<'f, <Ffm as FnMarkerAggr<Fm>>::Output>, Error>
    where
        S: Into<String>,
        F: IntoFunction<'f, Ffm, Args>,
        Ffm: FnMarkerAggr<Fm>,
        Args: Arguments,
    {
        self.bind_function(name, false, f)
    }
}

impl<'f, Fm: FnMarker> ActivationInterface<'f, Fm> for Activation<'f, Fm> {
    fn variables(&self) -> &VariableBindings<'f> {
        &self.variables
    }

    fn functions(&self) -> &FunctionBindings<'f> {
        &self.functions
    }
}

impl<'f, Fm: FnMarker> ActivationInterface<'f, Fm> for &Activation<'f, Fm> {
    fn variables(&self) -> &VariableBindings<'f> {
        (*self).variables()
    }

    fn functions(&self) -> &FunctionBindings<'f> {
        (*self).functions()
    }
}

impl<'f, Fm: FnMarker> ActivationInterface<'f, Fm> for std::sync::Arc<Activation<'f, Fm>> {
    fn variables(&self) -> &VariableBindings<'f> {
        (**self).variables()
    }

    fn functions(&self) -> &FunctionBindings<'f> {
        (**self).functions()
    }
}

impl<'f, Fm: FnMarker> ActivationInterface<'f, Fm> for Box<Activation<'f, Fm>> {
    fn variables(&self) -> &VariableBindings<'f> {
        (**self).variables()
    }

    fn functions(&self) -> &FunctionBindings<'f> {
        (**self).functions()
    }
}

static EMPTY_VARIABLES: std::sync::LazyLock<VariableBindings<'static>> =
    std::sync::LazyLock::new(VariableBindings::new);
static EMPTY_FUNCTIONS: std::sync::LazyLock<FunctionBindings<'static>> =
    std::sync::LazyLock::new(FunctionBindings::new);

/// Empty activation implementation for the unit type.
///
/// This allows you to use `()` as an activation when no variable or function
/// bindings are needed.
impl ActivationInterface<'static> for () {
    fn variables(&self) -> &VariableBindings<'static> {
        &EMPTY_VARIABLES
    }

    fn functions(&self) -> &FunctionBindings<'static> {
        &EMPTY_FUNCTIONS
    }
}

/// Empty activation implementation for references to the unit type.
impl ActivationInterface<'static> for &() {
    fn variables(&self) -> &VariableBindings<'static> {
        &EMPTY_VARIABLES
    }

    fn functions(&self) -> &FunctionBindings<'static> {
        &EMPTY_FUNCTIONS
    }
}

impl<'f, Fm: FnMarker> std::fmt::Debug for Activation<'f, Fm> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Activation")
            .field("variables", &self.variables)
            .field("functions", &self.functions)
            .finish()
    }
}