superscript 0.2.3

A Common Expression Language (CEL) interpreter for Rust
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
#[cfg(not(target_arch = "wasm32"))]
uniffi::include_scaffolding!("cel");
pub mod ast;
pub mod models;

use crate::ast::{ASTExecutionContext, JSONExpression};
use crate::models::PassableValue::Function;
use crate::models::PassableValue::PMap;
use crate::models::{ExecutionContext, PassableMap, PassableValue};
use crate::ExecutableType::{CompiledProgram, AST};
use async_trait::async_trait;
use cel_interpreter::extractors::This;
use cel_interpreter::objects::{Key, Map, TryIntoValue};
use cel_interpreter::{Context, ExecutionError, Expression, FunctionContext, Program, Value};
use cel_parser::parse;
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fmt::Debug;
use std::ops::Deref;
use std::sync::{mpsc, Arc, Mutex};
use std::thread::spawn;

#[cfg(not(target_arch = "wasm32"))]
use futures_lite::future::block_on;
use uniffi::deps::log::__private_api::log;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;

/**
 * Host context trait that defines the methods that the host context should implement,
 * i.e. iOS or Android calling code. This trait is used to resolve dynamic properties in the
 * CEL expression during evaluation, such as `computed.daysSinceEvent("event_name")` or similar.
 * Note: Since WASM async support in the browser is still not fully mature, we're using the
 * target_arch cfg to define the trait methods differently for WASM and non-WASM targets.
 */
#[cfg(target_arch = "wasm32")]
pub trait HostContext: Send + Sync {
    fn computed_property(&self, name: String, args: String) -> String;

    fn device_property(&self, name: String, args: String) -> String;
}

#[cfg(not(target_arch = "wasm32"))]
#[async_trait]
pub trait HostContext: Send + Sync {
    async fn computed_property(&self, name: String, args: String) -> String;

    async fn device_property(&self, name: String, args: String) -> String;
}

/**
 * Evaluate a CEL expression with the given AST
 * @param ast The AST Execution Context, serialized as JSON. This defines the AST, the variables, and the platform properties.
 * @param host The host context to use for resolving properties
 * @return The result of the evaluation, either "true" or "false"
 */
pub fn evaluate_ast_with_context(definition: String, host: Arc<dyn HostContext>) -> String {
    let data: Result<ASTExecutionContext, _> = serde_json::from_str(definition.as_str());
    let data = match data {
        Ok(data) => data,
        Err(_) => {
            let e: Result<_, String> =
                Err::<ASTExecutionContext, String>("Invalid execution context JSON".to_string());
            return serde_json::to_string(&e).unwrap();
        }
    };
    let host = host.clone();
    let res = execute_with(
        AST(data.expression.into()),
        data.variables,
        data.computed,
        data.device,
        host,
    )
    .map(|val| val.to_passable())
    .map_err(|err| err.to_string());
    serde_json::to_string(&res).unwrap()
}

/**
 * Evaluate a CEL expression with the given AST without any context
 * @param ast The AST of the expression, serialized as JSON. This AST should contain already resolved dynamic variables.
 * @return The result of the evaluation, either "true" or "false"
 */
pub fn evaluate_ast(ast: String) -> String {
    let data: Result<JSONExpression, _> = serde_json::from_str(ast.as_str());
    let data: JSONExpression = match data {
        Ok(data) => data,
        Err(_) => {
            let e: Result<_, String> =
                Err::<JSONExpression, String>("Invalid definition for AST Execution".to_string());
            return serde_json::to_string(&e).unwrap();
        }
    };
    let ctx = Context::default();
    let res = ctx
        .resolve(&data.into())
        .map(|val| DisplayableValue(val.clone()).to_passable())
        .map_err(|err| DisplayableError(err).to_string());
    serde_json::to_string(&res).unwrap()
}

/**
 * Evaluate a CEL expression with the given definition by compiling it first.
 * @param definition The definition of the expression, serialized as JSON. This defines the expression, the variables, and the platform properties.
 * @param host The host context to use for resolving properties
 * @return The result of the evaluation, either "true" or "false"
 */

pub fn evaluate_with_context(definition: String, host: Arc<dyn HostContext>) -> String {
    let data: Result<ExecutionContext, _> = serde_json::from_str(definition.as_str());
    let data: ExecutionContext = match data {
        Ok(data) => data,
        Err(_) => {
            let e: Result<ExecutionContext, String> =
                Err("Invalid execution context JSON".to_string());
            return serde_json::to_string(&e).unwrap();
        }
    };
    let compiled =
        Program::compile(data.expression.as_str()).map(|program| CompiledProgram(program));
    let result = match compiled {
        Ok(compiled) => execute_with(compiled, data.variables, data.computed, data.device, host)
            .map(|val| val.to_passable())
            .map_err(|err| err.to_string()),
        Err(e) => Err("Failed to compile expression".to_string()),
    };
    serde_json::to_string(&result).unwrap()
}

/**
 * Transforms a given CEL expression into a CEL AST, serialized as JSON.
 * @param expression The CEL expression to parse
 * @return The AST of the expression, serialized as JSON
 */
pub fn parse_to_ast(expression: String) -> String {
    let ast: Result<JSONExpression, _> = parse(expression.as_str()).map(|expr| expr.into());
    let ast = ast.map_err(|err| err.to_string());
    serde_json::to_string(&ast.unwrap()).unwrap()
}

/**
Type of expression to be executed, either a compiled program or an AST.
 */
enum ExecutableType {
    AST(Expression),
    CompiledProgram(Program),
}

/**
 * Execute a CEL expression, either compiled or pure AST; with the given context.
 * @param executable The executable type, either an AST or a compiled program
 * @param variables The variables to use in the expression
 * @param platform The platform properties or functions to use in the expression
 * @param host The host context to use for resolving properties
 */
fn execute_with(
    executable: ExecutableType,
    variables: PassableMap,
    computed: Option<HashMap<String, Vec<PassableValue>>>,
    device: Option<HashMap<String, Vec<PassableValue>>>,
    host: Arc<dyn HostContext + 'static>,
) -> Result<DisplayableValue, DisplayableError> {
    let host = host.clone();
    let host = Arc::new(Mutex::new(host));
    let mut ctx = Context::default();
    // Isolate device to re-bind later
    let device_map = variables.clone();
    let device_map = device_map
        .map
        .get("device")
        .clone()
        .unwrap_or(&PMap(HashMap::new()))
        .clone();

    // Add predefined variables locally to the context
    variables.map.iter().for_each(|it| {
        let _ = ctx.add_variable(it.0.as_str(), it.1.to_cel());
    });
    // Add maybe function
    ctx.add_function("maybe", maybe);

    // This function is used to extract the value of a property from the host context
    // As UniFFi doesn't support recursive enums yet, we have to pass it in as a
    // JSON serialized string of a PassableValue from Host and deserialize it here

    enum PropType {
        Computed,
        Device,
    }
    #[cfg(not(target_arch = "wasm32"))]
    fn prop_for(
        prop_type: PropType,
        name: Arc<String>,
        args: Option<Vec<PassableValue>>,
        ctx: &Arc<dyn HostContext>,
    ) -> Result<PassableValue, String> {
        // Get computed property
        let val = futures_lite::future::block_on(async move {
            let ctx = ctx.clone();
            let args = if let Some(args) = args {
                serde_json::to_string(&args)
            } else {
                serde_json::to_string::<Vec<PassableValue>>(&vec![])
            };
            match args {
                Ok(args) => match prop_type {
                    PropType::Computed => {
                        Ok(ctx.computed_property(name.clone().to_string(), args).await)
                    }
                    PropType::Device => {
                        Ok(ctx.device_property(name.clone().to_string(), args).await)
                    }
                },
                Err(e) => Err(ExecutionError::UndeclaredReference(name).to_string()),
            }
        });
        // Deserialize the value
        let passable: Result<PassableValue, String> = val
            .map(|val| serde_json::from_str(val.as_str()).unwrap_or(PassableValue::Null))
            .map_err(|err| err.to_string());

        passable
    }

    #[cfg(target_arch = "wasm32")]
    fn prop_for(
        prop_type: PropType,
        name: Arc<String>,
        args: Option<Vec<PassableValue>>,
        ctx: &Arc<dyn HostContext>,
    ) -> Option<PassableValue> {
        let ctx = ctx.clone();

        let val = match prop_type {
            PropType::Computed => ctx.computed_property(
                name.clone().to_string(),
                serde_json::to_string(&args)
                    .expect("Failed to serialize args for computed property"),
            ),
            PropType::Device => ctx.device_property(
                name.clone().to_string(),
                serde_json::to_string(&args)
                    .expect("Failed to serialize args for computed property"),
            ),
        };
        // Deserialize the value
        let passable: Option<PassableValue> =
            serde_json::from_str(val.as_str()).unwrap_or(Some(PassableValue::Null));

        passable
    }

    let computed = computed.unwrap_or(HashMap::new()).clone();

    // Create computed properties as a map of keys and function names
    let computed_host_properties: HashMap<Key, Value> = computed
        .iter()
        .map(|it| {
            let args = it.1.clone();
            let args = if args.is_empty() {
                None
            } else {
                Some(Box::new(PassableValue::List(args)))
            };
            let name = it.0.clone();
            (
                Key::String(Arc::new(name.clone())),
                Function(name, args).to_cel(),
            )
        })
        .collect();

    let device = device.unwrap_or(HashMap::new()).clone();

    // From defined properties the device properties
    let total_device_properties = if let PMap(map) = device_map {
        map
    } else {
        HashMap::new()
    };

    // Create device properties as a map of keys and function names
    let device_host_properties: HashMap<Key, Value> = device
        .iter()
        .map(|it| {
            let args = it.1.clone();
            let args = if args.is_empty() {
                None
            } else {
                Some(Box::new(PassableValue::List(args)))
            };
            let name = it.0.clone();
            (
                Key::String(Arc::new(name.clone())),
                Function(name, args).to_cel(),
            )
        })
        .chain(
            total_device_properties
                .iter()
                .map(|(k, v)| (Key::String(Arc::new(k.clone())), v.to_cel().clone())),
        )
        .collect();

    // Add the map to the `computed` object
    let _ = ctx.add_variable(
        "computed",
        Value::Map(Map {
            map: Arc::new(computed_host_properties),
        }),
    );

    // Add the map to the `device` object
    let _ = ctx.add_variable(
        "device",
        Value::Map(Map {
            map: Arc::new(device_host_properties),
        }),
    );

    let binding = device.clone();
    // Combine the device and computed properties
    let host_properties = binding
        .iter()
        .chain(computed.iter())
        .map(|(k, v)| (k.clone(), v.clone()))
        .into_iter();

    let mut device_properties_clone = device.clone().clone();
    // Add those functions to the context
    for it in host_properties {
        let mut value = device_properties_clone.clone();
        let key = it.0.clone();
        let host_clone = Arc::clone(&host); // Clone the Arc to pass into the closure
        let key_str = key.clone(); // Clone key for usage in the closure
        ctx.add_function(
            key_str.as_str(),
            move |ftx: &FunctionContext| -> Result<Value, ExecutionError> {
                let device = value.clone();
                let fx = ftx.clone();
                let name = fx.name.clone(); // Move the name into the closure
                let args = fx.args.clone(); // Clone the arguments
                let host = host_clone.lock(); // Lock the host for safe access
                match host {
                    Ok(host) => prop_for(
                        if device.contains_key(&it.0) {
                            PropType::Device
                        } else {
                            PropType::Computed
                        },
                        name.clone(),
                        Some(
                            args.iter()
                                .map(|expression| {
                                    DisplayableValue(ftx.ptx.resolve(expression).unwrap())
                                        .to_passable()
                                })
                                .collect(),
                        ),
                        &*host,
                    )
                    .map_or(Err(ExecutionError::UndeclaredReference(name)), |v| {
                        Ok(v.to_cel())
                    }),
                    Err(e) => {
                        let e = e.to_string();
                        let name = name.clone().to_string();
                        let error = ExecutionError::FunctionError {
                            function: name,
                            message: e,
                        };
                        Err(error)
                    }
                }
            },
        );
    }

    let val = match executable {
        AST(ast) => &ctx.resolve(&ast),
        CompiledProgram(program) => &program.execute(&ctx),
    };

    val.clone()
        .map(|val| DisplayableValue(val.clone()))
        .map_err(|err| DisplayableError(err))
}

pub fn maybe(
    ftx: &FunctionContext,
    This(_this): This<Value>,
    left: Expression,
    right: Expression,
) -> Result<Value, ExecutionError> {
    return ftx.ptx.resolve(&left).or_else(|_| ftx.ptx.resolve(&right));
}

// Wrappers around CEL values used so that we can create extensions on them
pub struct DisplayableValue(Value);

pub struct DisplayableError(ExecutionError);

impl fmt::Display for DisplayableValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.0 {
            Value::Int(i) => write!(f, "{}", i),
            Value::Float(x) => write!(f, "{}", x),
            Value::String(s) => write!(f, "{}", s),
            // Add more variants as needed
            Value::UInt(i) => write!(f, "{}", i),
            Value::Bytes(_) => {
                write!(f, "{}", "bytes go here")
            }
            Value::Bool(b) => write!(f, "{}", b),
            Value::Duration(d) => write!(f, "{}", d),
            Value::Timestamp(t) => write!(f, "{}", t),
            Value::Null => write!(f, "{}", "null"),
            Value::Function(name, _) => write!(f, "{}", name),
            Value::Map(map) => {
                let res: HashMap<String, String> = map
                    .map
                    .iter()
                    .map(|(k, v)| {
                        let key = DisplayableValue(k.try_into_value().unwrap().clone()).to_string();
                        let value = DisplayableValue(v.clone()).to_string().replace("\\", "");
                        (key, value)
                    })
                    .collect();
                let map = serde_json::to_string(&res).unwrap();
                write!(f, "{}", map)
            }
            Value::List(list) => write!(
                f,
                "{}",
                list.iter()
                    .map(|v| {
                        let key = DisplayableValue(v.clone());
                        return key.to_string();
                    })
                    .collect::<Vec<_>>()
                    .join(",\n ")
            ),
        }
    }
}

impl fmt::Display for DisplayableError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.to_string().as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct TestContext {
        map: HashMap<String, String>,
    }

    #[async_trait]
    impl HostContext for TestContext {
        async fn computed_property(&self, name: String, args: String) -> String {
            self.map.get(&name).unwrap().to_string()
        }

        async fn device_property(&self, name: String, args: String) -> String {
            self.map.get(&name).unwrap().to_string()
        }
    }

    #[tokio::test]
    async fn test_variables() {
        let ctx = Arc::new(TestContext {
            map: HashMap::new(),
        });
        let res = evaluate_with_context(
            r#"
        {
            "variables": {
             "map" : {
                    "foo": {"type": "int", "value": 100}
            }},
            "expression": "foo == 100"
        }

        "#
            .to_string(),
            ctx,
        );
        assert_eq!(res, "{\"Ok\":{\"type\":\"bool\",\"value\":true}}");
    }

    #[tokio::test]
    async fn test_execution_with_ctx() {
        let ctx = Arc::new(TestContext {
            map: HashMap::new(),
        });
        let res = evaluate_with_context(
            r#"
        {
            "variables": {
             "map" : {
                    "foo": {"type": "int", "value": 100},
                    "bar": {"type": "int", "value": 42}
            }},
            "expression": "foo + bar == 142"
        }

        "#
            .to_string(),
            ctx,
        );
        assert_eq!(res, "{\"Ok\":{\"type\":\"bool\",\"value\":true}}");
    }

    #[test]
    fn test_unknown_function_with_arg_fails_with_undeclared_ref() {
        let ctx = Arc::new(TestContext {
            map: HashMap::new(),
        });

        let res = evaluate_with_context(
            r#"
        {
            "variables": {
             "map" : {
                    "foo": {"type": "int", "value": 100}
            }},
            "expression": "test_custom_func(foo) == 101"
        }

        "#
            .to_string(),
            ctx,
        );
        assert_eq!(
            res,
            "{\"Err\":\"Undeclared reference to 'test_custom_func'\"}"
        );
    }

    #[test]
    fn test_list_contains() {
        let ctx = Arc::new(TestContext {
            map: HashMap::new(),
        });
        let res = evaluate_with_context(
            r#"
        {
            "variables": {
                 "map" : {
                    "numbers": {
                        "type" : "list",
                        "value" : [
                            {"type": "int", "value": 1},
                            {"type": "int", "value": 2},
                            {"type": "int", "value": 3}
                             ]
                       }
                 }
            },
            "expression": "numbers.contains(2)"
        }

        "#
            .to_string(),
            ctx,
        );
        assert_eq!(res, "{\"Ok\":{\"type\":\"bool\",\"value\":true}}");
    }

    #[tokio::test]
    async fn test_execution_with_map() {
        let ctx = Arc::new(TestContext {
            map: HashMap::new(),
        });
        let res = evaluate_with_context(
            r#"
        {
                    "variables": {
                        "map": {
                            "user": {
                                "type": "map",
                                "value": {
                                    "should_display": {
                                        "type": "bool",
                                        "value": true
                                    },
                                    "some_value": {
                                        "type": "uint",
                                        "value": 13
                                    }
                                }
                            }
                        }
                    },
                    "expression": "user.should_display == true && user.some_value > 12"
       }

        "#
            .to_string(),
            ctx,
        );
        println!("{}", res.clone());
        assert_eq!(res, "{\"Ok\":{\"type\":\"bool\",\"value\":true}}");
    }

    #[tokio::test]
    async fn test_execution_with_failure() {
        let ctx = Arc::new(TestContext {
            map: HashMap::new(),
        });
        let res = evaluate_with_context(
            r#"
        {
                    "variables": {
                        "map": {
                            "user": {
                                "type": "map",
                                "value": {
                                    "some_value": {
                                        "type": "uint",
                                        "value": 13
                                    }
                                }
                            }
                        }
                    },
                    "expression": "user.should_display == true && user.some_value > 12"
       }

        "#
            .to_string(),
            ctx,
        );
        println!("{}", res.clone());
        assert_eq!(res, "{\"Err\":\"No such key: should_display\"}");
    }

    #[tokio::test]
    async fn test_execution_with_null() {
        let ctx = Arc::new(TestContext {
            map: HashMap::new(),
        });
        let res = evaluate_with_context(
            r#"
        {
                    "variables": {
                        "map": {
                            "user": {
                                "type": "map",
                                "value": {
                                    "some_value": {
                                        "type": "Null",
                                        "value": null
                                    }
                                }
                            }
                        }
                    },
                    "expression": "user.should_display == true && user.some_value > 12"
       }

        "#
            .to_string(),
            ctx,
        );
        println!("{}", res.clone());
        assert_eq!(res, "{\"Err\":\"No such key: should_display\"}");
    }
    #[tokio::test]
    async fn test_execution_with_platform_computed_reference() {
        let days_since = PassableValue::UInt(7);
        let days_since = serde_json::to_string(&days_since).unwrap();
        let ctx = Arc::new(TestContext {
            map: [("minutesSince".to_string(), days_since)]
                .iter()
                .cloned()
                .collect(),
        });
        let res = evaluate_with_context(
            r#"
    {
        "variables": {
            "map": {}
        },
        "expression": "device.minutesSince('app_launch') == computed.minutesSince('app_install')",
        "computed": {
            "daysSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "minutesSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "hoursSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "monthsSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ]
        },
        "device": {
            "daysSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "minutesSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "hoursSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "monthsSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ]
        }
    }"#
            .to_string(),
            ctx,
        );
        println!("{}", res.clone());
        assert_eq!(res, "{\"Ok\":{\"type\":\"bool\",\"value\":true}}");
    }

    #[tokio::test]
    async fn test_execution_with_platform_device_function_and_property() {
        let days_since = PassableValue::UInt(7);
        let days_since = serde_json::to_string(&days_since).unwrap();
        let ctx = Arc::new(TestContext {
            map: [("minutesSince".to_string(), days_since)]
                .iter()
                .cloned()
                .collect(),
        });
        let res = evaluate_with_context(
            r#"
    {
        "variables": {
            "map": {
                "device": {
                    "type": "map",
                    "value": {
                        "trial_days": {
                            "type": "uint",
                            "value": 7
                        }
                    }
                }
            }
        },
        "expression": "computed.minutesSince('app_launch') == device.trial_days",
        "computed": {
            "daysSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "minutesSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "hoursSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "monthsSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ]
        },
        "device": {
            "daysSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "minutesSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "hoursSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ],
            "monthsSince": [
                {
                    "type": "string",
                    "value": "event_name"
                }
            ]
        }
    }"#
            .to_string(),
            ctx,
        );
        println!("{}", res.clone());
        assert_eq!(res, "{\"Ok\":{\"type\":\"bool\",\"value\":true}}");
    }

    #[test]
    fn test_parse_to_ast() {
        let expression = "device.daysSince(app_install) == 3";
        let ast_json = parse_to_ast(expression.to_string());
        println!("\nSerialized AST:");
        println!("{}", ast_json);
        // Deserialize back to JSONExpression
        let deserialized_json_expr: JSONExpression = serde_json::from_str(&ast_json).unwrap();

        // Convert back to original Expression
        let deserialized_expr: Expression = deserialized_json_expr.into();

        println!("\nDeserialized Expression:");
        println!("{:?}", deserialized_expr);

        let parsed_expression = parse(expression).unwrap();
        assert_eq!(parsed_expression, deserialized_expr);
        println!("\nOriginal and deserialized expressions are equal!");
    }
}