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
//! Function registry for managing registered functions.
//!
//! This module provides the [`FunctionRegistry`] type which serves as the
//! central repository for all functions available in a CEL environment.
//! It handles function registration, lookup, and overload management.
//!
//! # Features
//!
//! - **Function registration**: Add new function implementations
//! - **Declaration support**: Register type signatures without implementations
//! - **Overload management**: Handle multiple signatures for the same function name
//! - **Efficient lookup**: Fast function resolution during expression evaluation
//!
//! # Thread Safety
//!
//! The registry is designed to be thread-safe and can be shared across
//! multiple evaluation contexts.

use super::*;
use std::collections::HashMap;

/// Compile-time function registry.
///
/// `FunctionRegistry` manages function declarations and implementations during the CEL environment
/// compilation phase. It maintains a mapping from function names to function overloads, where each
/// overload set can contain multiple function implementations with different signatures.
///
/// The registry supports two types of functions:
///
/// - **Function declarations**: Type signatures only for compile-time checking
/// - **Function implementations**: Callable code for runtime execution
///
/// # Function Types
///
/// Functions can be registered as either:
///
/// - **Global functions**: Callable from any context
/// - **Member functions**: Called as methods on values (e.g., `value.method()`)
///
/// # Lifetime Parameters
///
/// - `'f`: Lifetime of function implementations, allowing closures valid within specific scopes
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::{FunctionRegistry, Error};
///
/// let mut registry = FunctionRegistry::new();
///
/// // Register function implementations
/// fn add(a: i64, b: i64) -> Result<i64, Error> {
///     Ok(a + b)
/// }
/// registry.register_global("add", add)?;
///
/// // Register member functions
/// fn string_length(s: String) -> Result<i64, Error> {
///     Ok(s.len() as i64)
/// }
/// registry.register_member("length", string_length)?;
///
/// // Register function declarations (type signatures only)
/// registry.declare_global::<fn(String) -> Result<bool, Error>>("is_valid")?;
///
/// assert_eq!(registry.len(), 3);
/// # Ok::<(), cel_cxx::Error>(())
/// ```
#[derive(Debug, Default)]
pub struct FunctionRegistry<'f> {
    entries: HashMap<String, FunctionOverloads<FunctionDeclOrImpl<'f>>>,
}

impl<'f> FunctionRegistry<'f> {
    /// Creates a new empty function registry.
    pub fn new() -> Self {
        Self {
            entries: HashMap::new(),
        }
    }
}

impl<'f> FunctionRegistry<'f> {
    /// Registers a function implementation with zero-annotation type inference.
    ///
    /// Registers a callable function that can be invoked during CEL expression evaluation.
    /// The function signature is automatically inferred from the Rust function type, eliminating
    /// the need for manual type annotations.
    ///
    /// # Zero-Annotation Features
    ///
    /// - **Automatic type inference**: Function signature extracted from Rust function type
    /// - **Lifetime handling**: Safe conversion of borrowed arguments like `&str`
    /// - **Error conversion**: Automatic conversion of `Result<T, E>` return types
    /// - **Async support**: Seamless handling of both sync and async functions
    ///
    /// # Type Parameters
    ///
    /// - `F`: Function type, must implement [`IntoFunction`]
    /// - `Fm`: Function marker (sync or async), automatically inferred
    /// - `Args`: Argument tuple type, automatically inferred from function signature
    ///
    /// # Parameters
    ///
    /// - `name`: Function name
    /// - `member`: Whether this is a member function (true) or global function (false)
    /// - `f`: Function implementation
    ///
    /// # Returns
    ///
    /// Returns `&mut Self` to support method chaining
    ///
    /// # Examples
    ///
    /// ## Basic functions with automatic type inference
    ///
    /// ```rust,no_run
    /// use cel_cxx::FunctionRegistry;
    ///
    /// let mut registry = FunctionRegistry::new();
    ///
    /// // Zero-annotation function registration
    /// registry.register("add", false, |a: i64, b: i64| a + b)?;
    /// registry.register("greet", false, |name: &str| format!("Hello, {}!", name))?;
    /// registry.register("is_empty", true, |s: String| s.is_empty())?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    ///
    /// ## Error handling with automatic conversion
    ///
    /// ```rust,no_run
    /// use cel_cxx::{FunctionRegistry, Error};
    ///
    /// let mut registry = FunctionRegistry::new();
    ///
    /// // Functions returning Result are automatically handled
    /// registry.register("divide", false, |a: i64, b: i64| -> Result<i64, Error> {
    ///     if b == 0 {
    ///         Err(Error::invalid_argument("Division by zero"))
    ///     } else {
    ///         Ok(a / b)
    ///     }
    /// })?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn register<F, Fm, Args>(
        &mut self,
        name: impl Into<String>,
        member: bool,
        f: F,
    ) -> Result<&mut Self, Error>
    where
        F: IntoFunction<'f, Fm, Args>,
        Fm: FnMarker,
        Args: Arguments,
    {
        let name = name.into();
        let entry = self
            .entries
            .entry(name)
            .or_insert_with(FunctionOverloads::new);
        entry.add_impl(member, f.into_function())?;
        Ok(self)
    }

    /// Registers a member function implementation.
    ///
    /// Convenience method for registering member functions that can be called as methods
    /// on values (e.g., `"hello".length()`).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::{FunctionRegistry, Error};
    ///
    /// let mut registry = FunctionRegistry::new();
    ///
    /// fn to_upper(s: String) -> Result<String, Error> {
    ///     Ok(s.to_uppercase())
    /// }
    ///
    /// registry.register_member("upper", to_upper)?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn register_member<F, Fm, Args>(
        &mut self,
        name: impl Into<String>,
        f: F,
    ) -> Result<&mut Self, Error>
    where
        F: IntoFunction<'f, Fm, Args>,
        Fm: FnMarker,
        Args: Arguments + NonEmptyArguments,
    {
        self.register(name, true, f)
    }

    /// Registers a global function implementation.
    ///
    /// Convenience method for registering global functions that can be called from any context.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::{FunctionRegistry, Error};
    ///
    /// let mut registry = FunctionRegistry::new();
    ///
    /// fn max(a: i64, b: i64) -> Result<i64, Error> {
    ///     Ok(a.max(b))
    /// }
    ///
    /// registry.register_global("max", max)?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn register_global<F, Fm, Args>(
        &mut self,
        name: impl Into<String>,
        f: F,
    ) -> Result<&mut Self, Error>
    where
        F: IntoFunction<'f, Fm, Args>,
        Fm: FnMarker,
        Args: Arguments,
    {
        self.register(name, false, f)
    }

    /// Declares a function signature.
    ///
    /// Declares a function type signature for compile-time type checking without providing
    /// an implementation. The function signature is determined by the generic parameter `D`
    /// which must implement [`FunctionDecl`].
    ///
    /// # Type Parameters
    ///
    /// - `D`: Function declaration type, must implement [`FunctionDecl`]
    ///
    /// # Parameters
    ///
    /// - `name`: Function name
    /// - `member`: Whether this is a member function (true) or global function (false)
    ///
    /// # Returns
    ///
    /// Returns `&mut Self` to support method chaining
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::{FunctionRegistry, Error};
    ///
    /// let mut registry = FunctionRegistry::new();
    ///
    /// // Declare global function signature
    /// registry.declare::<fn(String) -> Result<bool, Error>>("validate", false)?;
    ///
    /// // Declare member function signature  
    /// registry.declare::<fn(String) -> Result<i64, Error>>("size", true)?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn declare<D>(&mut self, name: impl Into<String>, member: bool) -> Result<&mut Self, Error>
    where
        D: FunctionDecl,
    {
        let name = name.into();
        if member && D::ARGUMENTS_LEN == 0 {
            return Err(Error::invalid_argument("Member functions cannot have zero arguments"));
        }
        let entry = self
            .entries
            .entry(name)
            .or_insert_with(FunctionOverloads::new);
        entry.add_decl(member, D::function_type())?;
        Ok(self)
    }

    /// Declares a member function signature.
    ///
    /// Convenience method for declaring member function signatures for compile-time
    /// type checking without providing implementations.
    ///
    /// # Type Parameters
    ///
    /// - `D`: Function declaration type, must implement [`FunctionDecl`] and [`FunctionDeclWithNonEmptyArguments`]
    ///
    /// # Parameters
    ///
    /// - `name`: Function name
    ///
    /// # Returns
    ///
    /// Returns `&mut Self` to support method chaining
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::{FunctionRegistry, Error};
    ///
    /// let mut registry = FunctionRegistry::new();
    ///
    /// // Declare member function signature
    /// registry.declare_member::<fn(String) -> i64>("hash")?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn declare_member<D>(&mut self, name: impl Into<String>) -> Result<&mut Self, Error>
    where
        D: FunctionDecl + FunctionDeclWithNonEmptyArguments,
    {
        self.declare::<D>(name, true)
    }

    /// Declares a global function signature.
    ///
    /// Convenience method for declaring global function signatures for compile-time
    /// type checking without providing implementations.
    ///
    /// # Type Parameters
    ///
    /// - `D`: Function declaration type, must implement [`FunctionDecl`]
    ///
    /// # Parameters
    ///
    /// - `name`: Function name
    ///
    /// # Returns
    ///
    /// Returns `&mut Self` to support method chaining
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::{FunctionRegistry, Error};
    ///
    /// let mut registry = FunctionRegistry::new();
    ///
    /// // Declare global function signature
    /// registry.declare_global::<fn(String, String) -> Result<String, Error>>("concat")?;
    /// # Ok::<(), cel_cxx::Error>(())
    /// ```
    pub fn declare_global<D>(&mut self, name: impl Into<String>) -> Result<&mut Self, Error>
    where
        D: FunctionDecl,
    {
        self.declare::<D>(name, false)
    }

    /// Finds function overloads by name.
    ///
    /// # Parameters
    ///
    /// - `name`: Function name to search for
    ///
    /// # Returns
    ///
    /// `Some(&FunctionOverloads)` if found, `None` if not found
    pub fn find(&self, name: &str) -> Option<&FunctionOverloads<FunctionDeclOrImpl<'f>>> {
        self.entries.get(name)
    }

    /// Finds function overloads by name (mutable).
    ///
    /// # Parameters
    ///
    /// - `name`: Function name to search for
    ///
    /// # Returns
    ///
    /// `Some(&mut FunctionOverloads)` if found, `None` if not found
    pub fn find_mut(
        &mut self,
        name: &str,
    ) -> Option<&mut FunctionOverloads<FunctionDeclOrImpl<'f>>> {
        self.entries.get_mut(name)
    }

    /// Returns an iterator over all function entries.
    ///
    /// # Returns
    ///
    /// Iterator yielding `(&str, &FunctionOverloads)` pairs
    pub fn entries(
        &self,
    ) -> impl Iterator<Item = (&str, &FunctionOverloads<FunctionDeclOrImpl<'f>>)> {
        self.entries.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Returns a mutable iterator over all function entries.
    ///
    /// # Returns
    ///
    /// Iterator yielding `(&str, &mut FunctionOverloads)` pairs
    pub fn entries_mut(
        &mut self,
    ) -> impl Iterator<Item = (&str, &mut FunctionOverloads<FunctionDeclOrImpl<'f>>)> {
        self.entries.iter_mut().map(|(k, v)| (k.as_str(), v))
    }

    /// Removes all overloads for a function name.
    ///
    /// # Parameters
    ///
    /// - `name`: Function name to remove
    ///
    /// # Returns
    ///
    /// `Ok(())` if removal was successful, `Err(Error)` if function not found
    pub fn remove(&mut self, name: &str) -> Result<(), Error> {
        self.entries
            .remove(name)
            .ok_or_else(|| Error::not_found(format!("Function '{name}' not found")))?;
        Ok(())
    }

    /// Clears all registered functions.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Returns the number of registered function names.
    ///
    /// Note: This counts function names, not individual overloads.
    ///
    /// # Returns
    ///
    /// Number of registered function names
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns whether the registry is empty.
    ///
    /// # Returns
    ///
    /// `true` if no functions are registered, `false` otherwise
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

#[allow(dead_code)]
#[allow(unused_variables)]
#[allow(unused_imports)]
#[cfg(test)]
mod test {
    use crate::{
        types::{OpaqueType, ValueType},
        values::OpaqueValue,
        values::Optional,
        values::{TypedOpaque, Value},
        Error, Opaque,
    };
    use std::{
        collections::{BTreeMap, HashMap},
        sync::Arc,
    };

    use super::*;

    fn f1(v: i64) -> Result<i64, Error> {
        Ok(5)
    }
    fn f11(a1: i64, a2: i64) -> Result<i64, Error> {
        Ok(5)
    }

    fn f2(a1: HashMap<i64, i64>) -> Result<i64, Error> {
        Ok(5)
    }
    fn f3(a1: String) -> Result<i64, Error> {
        Ok(5)
    }
    fn f4(a1: String, a2: String) -> Result<i64, Error> {
        Ok(5)
    }
    fn f5(a1: String, a2: String, a3: HashMap<u64, Vec<Vec<i64>>>) -> Result<i64, Error> {
        Ok(5)
    }

    #[cfg(feature = "derive")]
    #[derive(Opaque, Debug, Clone, PartialEq)]
    #[cel_cxx(type = "MyOpaque", crate = crate)]
    #[cel_cxx(display)]
    struct MyOpaque(pub i64);

    #[cfg(feature = "derive")]
    fn f6(a1: String, a2: MyOpaque, a3: HashMap<u64, Vec<Vec<i64>>>) -> Result<i64, Error> {
        Ok(5)
    }

    fn f7(a1: &str) -> Result<(), Error> {
        Ok(())
    }

    #[cfg(feature = "derive")]
    fn f8(a1: &MyOpaque) -> &MyOpaque {
        a1
    }

    #[cfg(feature = "derive")]
    fn f9(a1: Optional<&MyOpaque>) -> Result<Option<&MyOpaque>, Error> {
        Ok(a1.into_option())
    }

    async fn async_f1(a1: String, a2: i64, a3: Option<String>) -> Result<i64, Error> {
        Ok(5)
    }

    fn f_map1(a1: HashMap<String, Vec<u8>>) -> Result<(), Error> {
        Ok(())
    }
    fn f_map2(a1: HashMap<&str, &[u8]>) -> Result<(), Error> {
        Ok(())
    }
    fn f_map3<'a>(a1: HashMap<&'a str, &'a str>) -> Result<BTreeMap<&'a str, &'a str>, Error> {
        Ok(BTreeMap::from_iter(a1))
    }

    #[test]
    fn test_register() -> Result<(), Error> {
        let n = 100;
        let lifetime_closure = |a: i64, b: i64| Ok::<_, Error>(a + b + n);
        let mut registry = FunctionRegistry::new();
        registry
            .register_member("f1", f1)?
            .register_member("f11", f11)?
            .register_member("f2", f2)?
            .register_member("f3", f3)?
            .register_member("f4", f4)?
            .register_member("f5", f5)?
            .register_global("lifetime_closure", lifetime_closure)?
            .register_global("f7", f7)?
            .register_global("f_map1", f_map1)?
            .register_global("f_map2", f_map2)?
            .register_global("f_map3", f_map3)?;

        #[cfg(feature = "derive")]
        registry
            .register_global("f6", f6)?
            .register_global("f8", f8)?
            .register_global("f9", f9)?;

        #[cfg(feature = "async")]
        #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
        let registry = registry.register_global("async_f1", async_f1)?;

        //let variable = VariableDecl::builder()
        //    .add::<i64, _>("v1")
        //    .build(None);
        //let env = Env::new(function, variable);

        #[cfg(feature = "derive")]
        {
            let x = MyOpaque(1);
            let y: Box<dyn Opaque> = Box::new(x);

            let value: OpaqueValue = Box::new(MyOpaque(1));
            assert!(value.is::<MyOpaque>());
            assert!(value.downcast_ref::<MyOpaque>().is_some());
            let value2 = value.clone().downcast::<MyOpaque>();
            assert!(value2.is_ok());

            let value3 = value.clone();
            assert!(value3.is::<MyOpaque>());

            let value4: OpaqueValue = Box::new(MyOpaque(1));
            assert!(value4.is::<MyOpaque>());
            assert!(value4.clone().downcast::<MyOpaque>().is_ok());
            let value5 = value4.downcast::<MyOpaque>();
            assert!(value5.is_ok());
        }

        Ok(())
    }
}