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
//! CEL macro system for extending the expression language.
//!
//! This module provides functionality for defining and registering custom macros
//! that can expand CEL expressions at compile time. Macros enable syntactic sugar
//! and domain-specific language extensions without modifying the core parser.
//!
//! # Overview
//!
//! CEL macros transform parsed expressions into new expression trees before type
//! checking and evaluation. This allows you to:
//!
//! - Add new syntactic constructs (e.g., `has(foo.bar)` for presence testing)
//! - Implement domain-specific operators (e.g., `all(list, predicate)`)
//! - Optimize common patterns by rewriting expressions
//! - Extend CEL with custom comprehension forms
//!
//! # Macro Types
//!
//! There are two types of macros:
//!
//! - **Global macros**: Called as functions, e.g., `all([1, 2, 3], x, x > 0)`
//! - **Receiver macros**: Called as methods, e.g., `list.filter(x, x > 0)`
//!
//! Both types can accept fixed or variable numbers of arguments.
//!
//! # Examples
//!
//! ## Defining a global macro
//!
//! ```rust,no_run
//! use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
//! use cel_cxx::Constant;
//!
//! // Macro that creates a constant expression with doubled value
//! let double_macro = Macro::new_global("double", 1, |factory, args| {
//!     if let Some(expr) = args.first() {
//!         if let Some(val) = expr.kind().and_then(|k| k.as_constant()) {
//!             if let Constant::Int(int_val) = val {
//!                 return Some(factory.new_const(*int_val * 2));
//!             }
//!         }
//!     }
//!     None
//! });
//! ```
//!
//! ## Defining a receiver macro
//!
//! ```rust,no_run
//! # use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
//! // Macro for optional element access: list.maybe_get(index)
//! let maybe_get_macro = Macro::new_receiver("maybe_get", 1, |factory, target, args| {
//!     // Implementation would handle optional list indexing
//!     let arg_copy = factory.copy_expr(&args[0]);
//!     Some(factory.new_call("_?.[]", &[target, arg_copy]))
//! });
//! ```

use crate::Error;
use crate::ffi::{
    Macro as FfiMacro,
    Expr as FfiExpr,
    GlobalMacroExpander as FfiGlobalMacroExpander,
    ReceiverMacroExpander as FfiReceiverMacroExpander,
};

mod expr;
mod factory;
mod expander;

pub use expr::*;
pub use factory::*;
pub use expander::*;

/// A CEL macro that expands expressions at compile time.
///
/// A `Macro` represents a compile-time transformation rule that can be registered
/// with a CEL environment. When the parser encounters a matching function or method
/// call, the macro's expander is invoked to transform the expression tree.
///
/// # Macro Expansion
///
/// During compilation, macros are expanded before type checking:
/// 1. Parser identifies function/method calls matching registered macros
/// 2. Macro expander receives the call expression and its arguments
/// 3. Expander returns a new expression tree or `None` to keep original
/// 4. Type checker validates the expanded expression
///
/// # Thread Safety
///
/// The expander functions captured in macros must be `Send + Sync + 'static`,
/// ensuring thread-safe usage across the CEL environment.
///
/// # Error Handling
///
/// Macro creation methods return `Result<Self, Error>` and can fail if:
/// - The macro name is invalid
/// - Internal FFI allocation fails
/// - The expander closure cannot be registered
///
/// # Examples
///
/// ## Fixed argument count
///
/// ```rust,no_run
/// # use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // A macro that requires exactly 1 argument
/// let add_one_macro = Macro::new_global("add_one", 1, |factory, mut args| {
///     let arg = args.pop()?;
///     Some(factory.new_call("_+_", &[arg, factory.new_const(1)]))
/// })?;
/// # Ok(())
/// # }
/// ```
///
/// ## Variable argument count
///
/// ```rust,no_run
/// # use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // A macro that accepts any number of arguments
/// let debug_macro = Macro::new_global_var_arg("debug", |factory, args| {
///     // Wrap all arguments in a list for debugging
///     let elements: Vec<_> = args.iter()
///         .map(|arg| factory.new_list_element(arg, false))
///         .collect();
///     Some(factory.new_list(&elements))
/// })?;
/// # Ok(())
/// # }
/// ```
pub struct Macro(pub(crate) cxx::UniquePtr<FfiMacro>);

impl Macro {
    /// Creates a new global macro with a fixed number of arguments.
    ///
    /// Global macros are invoked like regular functions, e.g., `macro_name(arg1, arg2)`.
    /// The macro will only be expanded when called with exactly `argument_count` arguments.
    ///
    /// # Parameters
    ///
    /// - `name`: The function name that triggers this macro (as a string reference)
    /// - `argument_count`: The exact number of arguments required
    /// - `expander`: The expansion function that transforms the expression
    ///
    /// # Returns
    ///
    /// - `Ok(Macro)`: Successfully created macro
    /// - `Err(Error)`: Failed to create macro (e.g., invalid name or FFI error)
    ///
    /// # Expander Function
    ///
    /// The expander receives:
    /// - `factory`: A mutable reference to [`MacroExprFactory`] for creating new expressions
    /// - `args`: A vector of argument expressions
    ///
    /// The expander should return:
    /// - `Some(Expr)`: The expanded expression to replace the original call
    /// - `None`: Keep the original expression unchanged
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Macro: not_zero(x) expands to x != 0
    /// let macro_def = Macro::new_global("not_zero", 1, |factory, mut args| {
    ///     let arg = args.pop()?;
    ///     Some(factory.new_call("_!=_", &[arg, factory.new_const(0)]))
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_global(
        name: impl AsRef<str>,
        argument_count: usize,
        expander: impl GlobalMacroExpander + 'static,
    ) -> Result<Self, Error> {
        let ffi_expander: cxx::UniquePtr<FfiGlobalMacroExpander> = FfiGlobalMacroExpander::new(
            move |ffi_factory, ffi_expr| -> cxx::UniquePtr<FfiExpr> {
                let factory = MacroExprFactory::new(ffi_factory);
                let expr = ffi_expr.into_iter()
                    .map(|ffi_expr| Expr::from(&**ffi_expr))
                    .collect::<Vec<_>>();
                if let Some(result) = expander(&factory, expr) {
                    result.into()
                } else {
                    cxx::UniquePtr::null()
                }
            }
        );
        let ffi_macro = FfiMacro::new_global(name.as_ref().into(), argument_count, ffi_expander)?;
        Ok(Macro(ffi_macro))
    }

    /// Creates a new global macro that accepts a variable number of arguments.
    ///
    /// Variable-argument macros can handle any number of arguments, from zero to many.
    /// The expander function receives all arguments and decides how to handle them.
    ///
    /// # Parameters
    ///
    /// - `name`: The function name that triggers this macro (as a string reference)
    /// - `expander`: The expansion function that transforms the expression
    ///
    /// # Returns
    ///
    /// - `Ok(Macro)`: Successfully created macro
    /// - `Err(Error)`: Failed to create macro (e.g., invalid name or FFI error)
    ///
    /// # Expander Function
    ///
    /// The expander receives:
    /// - `factory`: A mutable reference to [`MacroExprFactory`] for creating new expressions
    /// - `args`: A vector of argument expressions (can be empty)
    ///
    /// The expander should return:
    /// - `Some(Expr)`: The expanded expression to replace the original call
    /// - `None`: Keep the original expression unchanged
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Macro: max(args...) finds maximum of all arguments
    /// let max_macro = Macro::new_global_var_arg("max", |factory, args| {
    ///     if args.is_empty() {
    ///         return None;
    ///     }
    ///     // Implementation would build comparison chain
    ///     Some(args.into_iter().reduce(|acc, arg| {
    ///         let arg_copy = factory.copy_expr(&arg);
    ///         let acc_copy = factory.copy_expr(&acc);
    ///         factory.new_call("_>_?_:_", &[acc, arg_copy, acc_copy, arg])
    ///     })?)
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_global_var_arg(
        name: impl AsRef<str>,
        expander: impl GlobalMacroExpander + 'static,
    ) -> Result<Self, Error> {
        let ffi_expander: cxx::UniquePtr<FfiGlobalMacroExpander> = FfiGlobalMacroExpander::new(
            move |ffi_factory, ffi_expr| -> cxx::UniquePtr<FfiExpr> {
                let factory = MacroExprFactory::new(ffi_factory);
                let expr = ffi_expr.into_iter()
                    .map(|ffi_expr| Expr::from(&**ffi_expr))
                    .collect::<Vec<_>>();
                if let Some(result) = expander(&factory, expr) {
                    result.into()
                } else {
                    cxx::UniquePtr::null()
                }
            }
        );
        let ffi_macro = FfiMacro::new_global_var_arg(name.as_ref().into(), ffi_expander)?;
        Ok(Macro(ffi_macro))
    }

    /// Creates a new receiver macro with a fixed number of arguments.
    ///
    /// Receiver macros are invoked as method calls on a target expression,
    /// e.g., `target.macro_name(arg1, arg2)`. The macro will only be expanded
    /// when called with exactly `argument_count` arguments.
    ///
    /// # Parameters
    ///
    /// - `name`: The method name that triggers this macro (as a string reference)
    /// - `argument_count`: The exact number of arguments required (not including receiver)
    /// - `expander`: The expansion function that receives the target and arguments
    ///
    /// # Returns
    ///
    /// - `Ok(Macro)`: Successfully created macro
    /// - `Err(Error)`: Failed to create macro (e.g., invalid name or FFI error)
    ///
    /// # Expander Function
    ///
    /// The expander receives:
    /// - `factory`: A mutable reference to [`MacroExprFactory`] for creating new expressions
    /// - `target`: The receiver expression (the object before the dot)
    /// - `args`: A vector of argument expressions
    ///
    /// The expander should return:
    /// - `Some(Expr)`: The expanded expression to replace the original call
    /// - `None`: Keep the original expression unchanged
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Macro: list.is_empty() expands to size(list) == 0
    /// let is_empty_macro = Macro::new_receiver("is_empty", 0, |factory, target, _args| {
    ///     let size_call = factory.new_call("size", &[target]);
    ///     Some(factory.new_call("_==_", &[size_call, factory.new_const(0)]))
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_receiver(
        name: impl AsRef<str>,
        argument_count: usize,
        expander: impl ReceiverMacroExpander + 'static,
    ) -> Result<Self, Error> {
        let ffi_expander: cxx::UniquePtr<FfiReceiverMacroExpander> = FfiReceiverMacroExpander::new(
            move |ffi_factory, ffi_target, ffi_expr| -> cxx::UniquePtr<FfiExpr> {
                let factory = MacroExprFactory::new(ffi_factory);
                let target = Expr::from(&*ffi_target);
                let expr = ffi_expr.into_iter()
                    .map(|ffi_expr| Expr::from(&**ffi_expr))
                    .collect::<Vec<_>>();
                if let Some(result) = expander(&factory, target, expr) {
                    result.into()
                } else {
                    cxx::UniquePtr::null()
                }
            }
        );
        let ffi_macro = FfiMacro::new_receiver(name.as_ref().into(), argument_count, ffi_expander)?;
        Ok(Macro(ffi_macro))
    }

    /// Creates a new receiver macro that accepts a variable number of arguments.
    ///
    /// Variable-argument receiver macros can handle any number of arguments beyond
    /// the target expression. The expander receives the target and all arguments.
    ///
    /// # Parameters
    ///
    /// - `name`: The method name that triggers this macro (as a string reference)
    /// - `expander`: The expansion function that receives the target and arguments
    ///
    /// # Returns
    ///
    /// - `Ok(Macro)`: Successfully created macro
    /// - `Err(Error)`: Failed to create macro (e.g., invalid name or FFI error)
    ///
    /// # Expander Function
    ///
    /// The expander receives:
    /// - `factory`: A mutable reference to [`MacroExprFactory`] for creating new expressions
    /// - `target`: The receiver expression (the object before the dot)
    /// - `args`: A vector of argument expressions (can be empty)
    ///
    /// The expander should return:
    /// - `Some(Expr)`: The expanded expression to replace the original call
    /// - `None`: Keep the original expression unchanged
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use cel_cxx::macros::{Macro, MacroExprFactory, Expr};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Macro: str.concat(parts...) concatenates multiple strings
    /// let concat_macro = Macro::new_receiver_var_arg("concat", |factory, target, args| {
    ///     let mut result = target;
    ///     for arg in args {
    ///         result = factory.new_call("_+_", &[result, arg]);
    ///     }
    ///     Some(result)
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_receiver_var_arg(
        name: impl AsRef<str>,
        expander: impl ReceiverMacroExpander + 'static,
    ) -> Result<Self, Error> {
        let ffi_expander: cxx::UniquePtr<FfiReceiverMacroExpander> = FfiReceiverMacroExpander::new(
            move |ffi_factory, ffi_target, ffi_expr| -> cxx::UniquePtr<FfiExpr> {
                let factory = MacroExprFactory::new(ffi_factory);
                let target = Expr::from(&*ffi_target);
                let expr = ffi_expr.into_iter()
                    .map(|ffi_expr| Expr::from(&**ffi_expr))
                    .collect::<Vec<_>>();
                if let Some(result) = expander(&factory, target, expr) {
                    result.into()
                } else {
                    cxx::UniquePtr::null()
                }
            }
        );
        let ffi_macro = FfiMacro::new_receiver_var_arg(name.as_ref().into(), ffi_expander)?;
        Ok(Macro(ffi_macro))
    }

    /// Returns the name of this macro as a byte slice.
    ///
    /// This is the function or method name that triggers macro expansion.
    /// The returned byte slice is UTF-8 encoded.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use cel_cxx::macros::Macro;
    /// # fn example(macro_def: &Macro) {
    /// let name = macro_def.name();
    /// let name_str = std::str::from_utf8(name).unwrap();
    /// println!("Macro name: {}", name_str);
    /// # }
    /// ```
    pub fn name(&self) -> &[u8] {
        self.0.function().as_bytes()
    }

    /// Returns the expected number of arguments for this macro.
    ///
    /// Returns `Some(n)` for fixed-argument macros requiring exactly `n` arguments,
    /// or `None` for variable-argument macros that accept any number of arguments.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use cel_cxx::macros::Macro;
    /// # fn example(macro_def: &Macro) {
    /// match macro_def.argument_count() {
    ///     Some(n) => println!("Fixed macro with {} arguments", n),
    ///     None => println!("Variable-argument macro"),
    /// }
    /// # }
    /// ```
    pub fn argument_count(&self) -> Option<usize> {
        if self.0.is_variadic() {
            None
        } else {
            Some(self.0.argument_count())
        }
    }

    /// Returns whether this is a receiver-style macro.
    ///
    /// Receiver-style macros are invoked as method calls (e.g., `target.method(args)`),
    /// while non-receiver macros are invoked as function calls (e.g., `function(args)`).
    ///
    /// # Returns
    ///
    /// - `true`: This is a receiver macro (created with [`new_receiver`] or [`new_receiver_var_arg`])
    /// - `false`: This is a global macro (created with [`new_global`] or [`new_global_var_arg`])
    ///
    /// [`new_receiver`]: Self::new_receiver
    /// [`new_receiver_var_arg`]: Self::new_receiver_var_arg
    /// [`new_global`]: Self::new_global
    /// [`new_global_var_arg`]: Self::new_global_var_arg
    pub fn is_receiver_style(&self) -> bool {
        self.0.is_receiver_style()
    }

    /// Returns the unique key identifying this macro.
    ///
    /// The key is an internal identifier used by the CEL parser to match macro
    /// invocations. It encodes the macro name, receiver style, and argument count.
    ///
    /// # Returns
    ///
    /// A byte slice representing the macro's unique key (UTF-8 encoded).
    ///
    /// # Note
    ///
    /// This method is primarily for internal use and debugging. Most users should
    /// use [`name()`], [`is_receiver_style()`], and [`argument_count()`] instead.
    ///
    /// [`name()`]: Self::name
    /// [`is_receiver_style()`]: Self::is_receiver_style
    /// [`argument_count()`]: Self::argument_count
    pub fn key(&self) -> &[u8] {
        self.0.key().as_bytes()
    }
}

impl From<Macro> for cxx::UniquePtr<crate::ffi::Macro> {
    fn from(value: Macro) -> Self {
        value.0
    }
}

impl From<cxx::UniquePtr<crate::ffi::Macro>> for Macro {
    fn from(value: cxx::UniquePtr<crate::ffi::Macro>) -> Self {
        Macro(value)
    }
}

impl std::fmt::Debug for Macro {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Macro({})", String::from_utf8_lossy(self.key()))
    }
}

impl std::hash::Hash for Macro {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.key().hash(state);
    }
}

impl std::cmp::PartialEq for Macro {
    fn eq(&self, other: &Self) -> bool {
        self.key() == other.key()
    }
}

impl std::cmp::Eq for Macro {}