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
//! Compiled CEL program evaluation.
//!
//! This module provides the [`Program`] type, which represents a compiled CEL expression
//! ready for evaluation. Programs are created by compiling CEL expressions using an
//! [`Env`](crate::Env) and can be evaluated multiple times with different variable
//! bindings (activations).
//!
//! # Key Features
//!
//! - **Compiled expressions**: CEL expressions are parsed and compiled once, then evaluated many times
//! - **Type safety**: Programs know their return type at compile time
//! - **Variable binding**: Support for dynamic variable values through activations
//! - **Async support**: Programs can contain and evaluate async functions
//! - **Runtime selection**: Choose between different async runtimes (Tokio, async-std)
//!
//! # Program Types
//!
//! Programs are parameterized by function and runtime markers:
//!
//! - **`Program<'f>`**: Synchronous program with sync functions only
//! - **`AsyncProgram<'f>`**: Program that can contain async functions
//! - **`Program<'f, Fm, Rm>`**: Full type with function marker `Fm` and runtime marker `Rm`
//!
//! # Evaluation Model
//!
//! Programs use an activation-based evaluation model:
//!
//! 1. **Compilation**: Parse and type-check the CEL expression
//! 2. **Activation**: Bind variables and functions for a specific evaluation
//! 3. **Evaluation**: Execute the compiled expression with the bound values
//!
//! # Examples
//!
//! ## Basic synchronous evaluation
//!
//! ```rust,no_run
//! use cel_cxx::*;
//!
//! // Create environment and compile expression
//! let env = Env::builder()
//!     .declare_variable::<String>("user_name")?
//!     .declare_variable::<i64>("user_age")?
//!     .build()?;
//!
//! let program = env.compile("'Hello ' + user_name + ', you are ' + string(user_age)")?;
//!
//! // Create activation with variable bindings
//! let activation = Activation::new()
//!     .bind_variable("user_name", "Alice".to_string())?
//!     .bind_variable("user_age", 30i64)?;
//!
//! // Evaluate the program
//! let result = program.evaluate(activation)?;
//! println!("{}", result); // "Hello Alice, you are 30"
//! # Ok::<(), cel_cxx::Error>(())
//! ```
//!
//! ## Working with functions
//!
//! ```rust,no_run
//! use cel_cxx::*;
//!
//! // Register custom function
//! let env = Env::builder()
//!     .register_global_function("multiply", |a: i64, b: i64| a * b)?
//!     .declare_variable::<i64>("x")?
//!     .build()?;
//!
//! let program = env.compile("multiply(x, 2) + 1")?;
//!
//! let activation = Activation::new()
//!     .bind_variable("x", 21i64)?;
//!
//! let result = program.evaluate(activation)?;
//! assert_eq!(result, Value::Int(43));
//! # Ok::<(), cel_cxx::Error>(())
//! ```
//!
//! ## Async evaluation
//!
//! ```rust,no_run
//! # #[cfg(feature = "async")]
//! # async fn example() -> Result<(), cel_cxx::Error> {
//! use cel_cxx::*;
//! use cel_cxx::r#async::Tokio;
//!
//! // Register async function
//! let env = Env::builder()
//!     .register_global_function("fetch_data", |url: String| async move {
//!         // Simulate async work
//!         tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
//!         format!("Data from {}", url)
//!     })?
//!     .build()?;
//!
//! let program = env.compile("fetch_data('https://api.example.com')")?
//!     .use_runtime::<Tokio>();
//!
//! let result = program.evaluate(()).await?;
//! println!("{}", result); // "Data from https://api.example.com"
//! # Ok(())
//! # }
//! ```
//!
//! ## Reusing programs
//!
//! ```rust,no_run
//! use cel_cxx::*;
//!
//! let env = Env::builder()
//!     .declare_variable::<i64>("value")?
//!     .build()?;
//!
//! // Compile once
//! let program = env.compile("value * value")?;
//!
//! // Evaluate multiple times with different values
//! for i in 1..=5 {
//!     let activation = Activation::new()
//!         .bind_variable("value", i)?;
//!     
//!     let result = program.evaluate(activation)?;
//!     println!("{} * {} = {}", i, i, result);
//! }
//! # Ok::<(), cel_cxx::Error>(())
//! ```

use std::sync::Arc;
mod eval_dispatch;
mod inner;
use super::{ActivationInterface, Error, Value, ValueType};
use crate::{FnMarker, FnMarkerAggr, FnResult, RuntimeMarker};
use eval_dispatch::{EvalDispatch, EvalDispatcher};

pub(crate) use inner::ProgramInner;

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
use crate::marker::Async;

/// Compiled CEL program ready for evaluation.
///
/// A `Program` represents a compiled CEL expression that can be evaluated
/// multiple times with different variable bindings (activations). Programs
/// are created by compiling CEL expressions using an [`Env`](crate::Env).
///
/// # Type Parameters
///
/// - `'f`: Lifetime of functions registered in the environment
/// - `Fm`: Function marker type indicating sync/async function support
/// - `Rm`: Runtime marker type indicating the async runtime (if any)
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let env = Env::builder()
///     .declare_variable::<String>("name")?
///     .build()?;
///     
/// let program = env.compile("'Hello, ' + name")?;
///
/// let activation = Activation::new()
///     .bind_variable("name", "World")?;
///     
/// let result = program.evaluate(activation)?;
/// # Ok::<(), cel_cxx::Error>(())
/// ```
///
/// ## Type Information
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let env = Env::builder().build()?;
/// let program = env.compile("42")?;
///
/// // Check the return type
/// println!("Return type: {:?}", program.return_type());
/// # Ok::<(), cel_cxx::Error>(())
/// ```
pub struct Program<'f, Fm: FnMarker = (), Rm: RuntimeMarker = ()> {
    pub(crate) inner: Arc<ProgramInner<'f>>,
    pub(crate) _fn_marker: std::marker::PhantomData<Fm>,
    pub(crate) _rt_marker: std::marker::PhantomData<Rm>,
}

/// Type alias for asynchronous CEL programs.
///
/// This is a convenience type alias for programs that support asynchronous
/// evaluation with async functions and/or async runtime.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub type AsyncProgram<'f, Rm = ()> = Program<'f, Async, Rm>;

impl<'f, Fm: FnMarker, Rm: RuntimeMarker> Program<'f, Fm, Rm> {
    /// Returns the return type of this program.
    ///
    /// This method returns the CEL type that this program will produce when
    /// evaluated. The type is determined during compilation based on the
    /// expression and the declared variables and functions.
    ///
    /// # Returns
    ///
    /// A reference to the [`ValueType`] that this program returns.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let env = Env::builder().build()?;
    /// let program = env.compile("42")?;
    ///
    /// println!("Return type: {:?}", program.return_type());
    /// // Output: Return type: Int
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn return_type(&self) -> &ValueType {
        self.inner.return_type()
    }

    /// Evaluates the program with the given activation.
    ///
    /// This method evaluates the compiled CEL expression using the variable
    /// and function bindings provided in the activation. The return type
    /// of this method depends on the program and activation markers:
    ///
    /// - For synchronous programs: Returns `Result<Value, Error>`
    /// - For asynchronous programs: Returns `BoxFuture<Result<Value, Error>>`
    ///
    /// # Arguments
    ///
    /// * `activation` - The activation containing variable and function bindings
    ///
    /// # Type Parameters
    ///
    /// * `A` - The activation type
    /// * `Afm` - The activation's function marker type
    ///
    /// # Examples
    ///
    /// ## Synchronous Evaluation
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let env = Env::builder()
    ///     .declare_variable::<i64>("x")?
    ///     .build()?;
    ///     
    /// let program = env.compile("x * 2")?;
    ///
    /// let activation = Activation::new()
    ///     .bind_variable("x", 21i64)?;
    ///     
    /// let result = program.evaluate(activation)?;
    /// // result == Value::Int(42)
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    ///
    /// ## With Empty Activation
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let env = Env::builder().build()?;
    /// let program = env.compile("1 + 2 * 3")?;
    ///
    /// let result = program.evaluate(())?;
    /// // result == Value::Int(7)
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn evaluate<'a, A, Afm>(
        &self,
        activation: A,
    ) -> <<Afm as FnMarkerAggr<Fm>>::Output as FnResult<'f, Result<Value, Error>>>::Output
    where
        'f: 'a,
        A: ActivationInterface<'f, Afm> + 'a,
        Afm: FnMarkerAggr<Fm>,
        <Afm as FnMarkerAggr<Fm>>::Output: FnResult<'f, Result<Value, Error>>,
        EvalDispatcher<<Afm as FnMarkerAggr<Fm>>::Output, Rm>:
            EvalDispatch<
                'f,
                A,
                Afm,
                Output = <<Afm as FnMarkerAggr<Fm>>::Output as FnResult<
                    'f,
                    Result<Value, Error>,
                >>::Output,
            >,
    {
        EvalDispatcher::<<Afm as FnMarkerAggr<Fm>>::Output, Rm>::new()
            .eval(self.inner.clone(), activation)
    }
}

/// Async-specific methods for programs.
///
/// These methods are only available when the `async` feature is enabled
/// and provide utilities for working with async runtimes.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
const _: () = {
    use crate::r#async::*;

    impl<'f, Rm: RuntimeMarker> Program<'f, (), Rm> {
        /// Forces conversion to an async program.
        ///
        /// This method converts a synchronous program to an asynchronous one,
        /// allowing it to work with async functions and evaluation.
        ///
        /// # Examples
        ///
        /// ```rust,no_run
        /// # #[cfg(feature = "async")]
        /// # {
        /// use cel_cxx::*;
        ///
        /// let sync_program = Env::builder().build()?.compile("42")?;
        /// let async_program = sync_program.force_async();
        /// # }
        /// # Ok::<(), cel_cxx::Error>(())
        /// ```
        pub fn force_async(self) -> Program<'f, Async, Rm> {
            Program {
                inner: self.inner,
                _fn_marker: std::marker::PhantomData,
                _rt_marker: std::marker::PhantomData,
            }
        }
    }

    impl<'f, Fm: FnMarker> Program<'f, Fm, ()> {
        /// Configures this program to use a specific async runtime.
        ///
        /// This method allows you to specify which async runtime should be
        /// used for evaluating this program when it contains async functions.
        ///
        /// # Type Parameters
        ///
        /// * `Rt` - The runtime type to use
        ///
        /// # Examples
        ///
        /// ```rust,no_run
        /// # #[cfg(feature = "tokio")]
        /// # fn example() -> Result<(), cel_cxx::Error> {
        /// use cel_cxx::*;
        /// use cel_cxx::r#async::Tokio;
        ///
        /// let env = Env::builder().build()?;
        /// let program = env.compile("42")?;
        ///
        /// let async_program = program.use_runtime::<Tokio>();
        /// # Ok::<(), cel_cxx::Error>(())
        /// # }
        /// ```
        pub fn use_runtime<Rt: Runtime>(self) -> Program<'f, Fm, Rt> {
            Program {
                inner: self.inner,
                _fn_marker: self._fn_marker,
                _rt_marker: std::marker::PhantomData,
            }
        }

        /// Configures this program to use the Tokio async runtime.
        ///
        /// This is a convenience method equivalent to `use_runtime::<Tokio>()`.
        ///
        /// # Examples
        ///
        /// ```rust,no_run
        /// # #[cfg(feature = "tokio")]
        /// # fn example() -> Result<(), cel_cxx::Error> {
        /// use cel_cxx::*;
        ///
        /// let env = Env::builder().build()?;
        /// let program = env.compile("42")?;
        ///
        /// let tokio_program = program.use_tokio();
        /// # Ok::<(), cel_cxx::Error>(())
        /// # }
        /// ```
        #[cfg(feature = "tokio")]
        #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
        pub fn use_tokio(self) -> Program<'f, Fm, Tokio> {
            self.use_runtime::<Tokio>()
        }

        /// Configures this program to use the async-std runtime.
        ///
        /// This is a convenience method equivalent to `use_runtime::<AsyncStd>()`.
        ///
        /// # Examples
        ///
        /// ```rust,no_run
        /// # #[cfg(feature = "async-std")]
        /// # fn example() -> Result<(), cel_cxx::Error> {
        /// use cel_cxx::*;
        ///
        /// let env = Env::builder().build()?;
        /// let program = env.compile("42")?;
        ///
        /// let async_std_program = program.use_async_std();
        /// # Ok::<(), cel_cxx::Error>(())
        /// # }
        /// ```
        #[cfg(feature = "async-std")]
        #[cfg_attr(docsrs, doc(cfg(feature = "async-std")))]
        pub fn use_async_std(self) -> Program<'f, Fm, AsyncStd> {
            self.use_runtime::<AsyncStd>()
        }

        /// Configures this program to use the smol runtime.
        ///
        /// This is a convenience method equivalent to `use_runtime::<Smol>()`.
        ///
        /// # Examples
        ///
        /// ```rust,no_run
        /// # #[cfg(feature = "smol")]
        /// # fn example() -> Result<(), cel_cxx::Error> {
        /// use cel_cxx::*;
        ///
        /// let env = Env::builder().build()?;
        /// let program = env.compile("42")?;
        ///
        /// let smol_program = program.use_smol();
        /// # Ok::<(), cel_cxx::Error>(())
        /// # }
        /// ```
        #[cfg(feature = "smol")]
        #[cfg_attr(docsrs, doc(cfg(feature = "smol")))]
        pub fn use_smol(self) -> Program<'f, Fm, Smol> {
            self.use_runtime::<Smol>()
        }
    }
};

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

impl<'f, Fm: FnMarker, Rm: RuntimeMarker> Clone for Program<'f, Fm, Rm> {
    fn clone(&self) -> Self {
        Program {
            inner: self.inner.clone(),
            _fn_marker: self._fn_marker,
            _rt_marker: self._rt_marker,
        }
    }
}

#[cfg(test)]
mod test {
    #![allow(unused)]

    use super::*;
    use crate::Activation;

    fn assert_eval_type<'f>(program: Program<'f, (), ()>, activation: Activation<'f, ()>) {
        let _result: Result<Value, Error> = program.evaluate(activation);
    }

    #[cfg(feature = "async")]
    const _: () = {
        use crate::r#async::Tokio;
        use crate::Async;
        use futures::future::BoxFuture;

        #[cfg(feature = "tokio")]
        const _: () = {
            fn assert_eval_type_async1<'f>(
                program: Program<'f, Async, Tokio>,
                activation: Activation<'f, ()>,
            ) {
                let _result: BoxFuture<'f, Result<Value, Error>> = program.evaluate(activation);
            }

            fn assert_eval_type_async2<'f>(
                program: Program<'f, (), Tokio>,
                activation: Activation<'f, Async>,
            ) {
                let _result: BoxFuture<'f, Result<Value, Error>> = program.evaluate(activation);
            }

            fn assert_eval_type_async3<'f>(
                program: Program<'f, Async, Tokio>,
                activation: Activation<'f, Async>,
            ) {
                let _result: BoxFuture<'f, Result<Value, Error>> = program.evaluate(activation);
            }

            fn assert_eval_type_async4<'f>(
                program: Program<'f, Async, ()>,
                activation: Activation<'f, Async>,
            ) {
                let _result: BoxFuture<'f, Result<Value, Error>> =
                    program.use_tokio().evaluate(activation);
            }
        };
    };
}