Skip to main content

maps/
maps.rs

1//! Map operations in CEL.
2//!
3//! Run with: cargo run -p cel-core --example maps
4
5use cel_core::{CelType, Env, MapActivation, Value};
6
7fn main() {
8    let env = Env::with_standard_library()
9        .with_variable("user", CelType::map(CelType::String, CelType::Dyn));
10
11    // Mixed value types require explicit Value::from()
12    let user = Value::map([
13        ("name", Value::from("Alice")),
14        ("age", Value::from(30)), // i32 automatically widens to i64
15        ("active", Value::from(true)),
16    ]);
17
18    let mut activation = MapActivation::new();
19    activation.insert("user", user);
20
21    // Field access
22    let ast = env.compile("user.name").unwrap();
23    let program = env.program(&ast).unwrap();
24    let result = program.eval(&activation);
25    println!("user.name:     {}", result);
26
27    // Index access
28    let ast = env.compile(r#"user["age"]"#).unwrap();
29    let program = env.program(&ast).unwrap();
30    let result = program.eval(&activation);
31    println!(r#"user["age"]:   {}"#, result);
32
33    // Check field existence with 'in'
34    let ast = env.compile(r#""name" in user"#).unwrap();
35    let program = env.program(&ast).unwrap();
36    let result = program.eval(&activation);
37    println!(r#""name" in user: {}"#, result);
38
39    // Check field existence with has()
40    let ast = env.compile("has(user.email)").unwrap();
41    let program = env.program(&ast).unwrap();
42    let result = program.eval(&activation);
43    println!("has(user.email): {}", result);
44
45    // Combine conditions
46    let ast = env.compile(r#"user.active && user.age >= 21"#).unwrap();
47    let program = env.program(&ast).unwrap();
48    let result = program.eval(&activation);
49    println!("active && age >= 21: {}", result);
50}