rets_expression/
lib.rs

1//! An implementation of [RCP 19][rcp19] (RETS Validation Expressions) from the [RESO Transport
2//! group][transport].
3//!
4//! [transport]: https://github.com/RESOStandards/transport
5//! [rcp19]: https://github.com/RESOStandards/transport/blob/main/web-api-validation-expression.md
6//!
7//! ## Example
8//!
9//! ```
10//! use rets_expression::{Expression, Engine, EvaluateContext};
11//! use serde_json::json;
12//!
13//! // Parse an expression
14//! let expression = "MlsStatus .IN. ('Active', 'Pending') .AND. (ListPrice >= 1 .OR. LAST MlsStatus = 'Incomplete')"
15//!     .parse::<Expression>()
16//!     .unwrap();
17//!
18//! // Create the property data to run the expression against
19//! let value = json!({
20//!     "MlsStatus": "Active",
21//!     "ListPrice": 1000000
22//! });
23//! // Create the previous property data to run the expression against (for when the expression
24//! // includes references to previous data, like `LAST FieldName`)
25//! let previous_value = json!({
26//!     "MlsStatus": "Incomplete",
27//!     "ListPrice": 0
28//! });
29//!
30//! // Create a default engine and a context in which to evaluate the expression
31//! let engine = Engine::default();
32//! let context = EvaluateContext::new(&engine, &value).with_previous(&previous_value);
33//!
34//! // Evaluate the expression!
35//! let value = expression.apply(context).unwrap();
36//! assert_eq!(value.into_owned(), json!(true));
37//! ```
38#![cfg_attr(not(feature = "std"), no_std)]
39#![deny(missing_docs)]
40extern crate alloc;
41
42use alloc::{
43    borrow::Cow,
44    boxed::Box,
45    collections::BTreeMap,
46    format,
47    string::{String, ToString},
48    vec::Vec,
49};
50use chrono::{DateTime, NaiveDate};
51pub use context::{Engine, EvaluateContext};
52use core::str::FromStr;
53use serde_json::Value;
54
55mod context;
56mod formatter;
57pub mod function;
58mod parser;
59
60/// An expression that can be inspected or evaluated
61#[derive(Clone, Eq, PartialEq)]
62pub enum Expression {
63    /// A node representing a reference to a field
64    ///
65    /// E.g. `MlsStatus`
66    Field(FieldNode),
67    /// A node representing a reference to a field from the previous value
68    ///
69    /// E.g. `LAST MlsStatus`
70    LastField(LastFieldNode),
71    /// A node representing the logical conjunction of two or more expressions
72    ///
73    /// E.g. `A .AND. B`
74    And(AndNode),
75    /// A node representing the logical disjunction of two or more expressions
76    ///
77    /// E.g. `A .OR. B`
78    Or(OrNode),
79    /// A node representing the logical negation of an expression
80    ///
81    /// E.g. `.NOT. A`
82    Not(NotNode),
83    /// A node representing a binary operation
84    ///
85    /// E.g. `A + B`
86    Op(OpNode),
87    /// A node representing a literal value
88    ///
89    /// E.g. `.TRUE.`
90    Literal(LiteralNode),
91    /// A node representing a function call
92    ///
93    /// E.g. `SUBSTR('A', 1, 2)`
94    Function(FunctionNode),
95    /// A node representing the special `IIF` conditional syntax
96    ///
97    /// E.g. `IIF(A, B, C)`
98    Iif(IifNode),
99    /// A node representing a list of items
100    ///
101    /// E.g. `(1, 2, 3)`
102    List(ListNode),
103}
104
105impl Expression {
106    /// Visit this node with the provided visitor
107    pub fn accept(&mut self, visitor: &mut impl Visitor) {
108        loop {
109            visitor.visit_expression_in(self);
110            match self {
111                Expression::Field(_) => {
112                    visitor.visit_field_expression(self);
113                    if let Some(node) = self.as_field_mut() {
114                        node.accept(visitor);
115                    } else {
116                        continue;
117                    }
118                }
119                Expression::LastField(_) => {
120                    visitor.visit_last_field_expression(self);
121                    if let Some(node) = self.as_last_field_mut() {
122                        node.accept(visitor);
123                    } else {
124                        continue;
125                    }
126                }
127                Expression::And(_) => {
128                    visitor.visit_and_expression_in(self);
129                    if let Some(node) = self.as_and_mut() {
130                        node.accept(visitor);
131                    } else {
132                        continue;
133                    }
134                    visitor.visit_and_expression_out(self);
135                }
136                Expression::Or(_) => {
137                    visitor.visit_or_expression_in(self);
138                    if let Some(node) = self.as_or_mut() {
139                        node.accept(visitor);
140                    } else {
141                        continue;
142                    }
143                    visitor.visit_or_expression_out(self);
144                }
145                Expression::Not(_) => {
146                    visitor.visit_not_expression_in(self);
147                    if let Some(node) = self.as_not_mut() {
148                        node.accept(visitor);
149                    } else {
150                        continue;
151                    }
152                    visitor.visit_not_expression_out(self);
153                }
154                Expression::Op(_) => {
155                    visitor.visit_op_expression_in(self);
156                    if let Some(node) = self.as_op_mut() {
157                        node.accept(visitor);
158                    } else {
159                        continue;
160                    }
161                    visitor.visit_op_expression_out(self);
162                }
163                Expression::Literal(_) => {
164                    visitor.visit_literal_expression(self);
165                    if let Some(node) = self.as_literal_mut() {
166                        node.accept(visitor);
167                    } else {
168                        continue;
169                    }
170                }
171                Expression::Function(_) => {
172                    visitor.visit_function_expression_in(self);
173                    if let Some(node) = self.as_function_mut() {
174                        node.accept(visitor);
175                    } else {
176                        continue;
177                    }
178                    visitor.visit_function_expression_out(self);
179                }
180                Expression::Iif(_) => {
181                    visitor.visit_iif_expression_in(self);
182                    if let Some(node) = self.as_iif_mut() {
183                        node.accept(visitor);
184                    } else {
185                        continue;
186                    }
187                    visitor.visit_iif_expression_out(self);
188                }
189                Expression::List(_) => {
190                    visitor.visit_list_expression_in(self);
191                    if let Some(node) = self.as_list_mut() {
192                        node.accept(visitor);
193                    } else {
194                        continue;
195                    }
196                    visitor.visit_list_expression_out(self);
197                }
198            }
199            visitor.visit_expression_out(self);
200            break;
201        }
202    }
203}
204
205macro_rules! define_as_function {
206    ($as_ref_name:ident, $as_mut_name:ident, $discriminant:ident, $node_type:ty) => {
207        /// If the [Expression] is a X, returns a reference to the associated Y. Returns `None`
208        /// otherwise.
209        pub fn $as_ref_name(&self) -> Option<&$node_type> {
210            match self {
211                Expression::$discriminant(node) => Some(node),
212                _ => None,
213            }
214        }
215
216        /// If the [Expression] is a X, returns a mutable reference to the associated Y. Returns
217        /// `None` otherwise.
218        pub fn $as_mut_name(&mut self) -> Option<&mut $node_type> {
219            match self {
220                Expression::$discriminant(node) => Some(node),
221                _ => None,
222            }
223        }
224    };
225}
226
227impl Expression {
228    define_as_function!(as_field, as_field_mut, Field, FieldNode);
229    define_as_function!(as_last_field, as_last_field_mut, LastField, LastFieldNode);
230    define_as_function!(as_and, as_and_mut, And, AndNode);
231    define_as_function!(as_or, as_or_mut, Or, OrNode);
232    define_as_function!(as_not, as_not_mut, Not, NotNode);
233    define_as_function!(as_op, as_op_mut, Op, OpNode);
234    define_as_function!(as_literal, as_literal_mut, Literal, LiteralNode);
235    define_as_function!(as_function, as_function_mut, Function, FunctionNode);
236    define_as_function!(as_iif, as_iif_mut, Iif, IifNode);
237    define_as_function!(as_list, as_list_mut, List, ListNode);
238}
239
240#[derive(Clone, Eq, PartialEq)]
241struct Span {
242    start: usize,
243    end: usize,
244}
245
246/// A node representing a reference to a field
247///
248/// E.g. `MlsStatus`
249#[derive(Clone, Eq, PartialEq)]
250#[non_exhaustive]
251pub struct FieldNode {
252    /// The name of the field that is being referenced
253    pub name: String,
254    span: Option<Span>,
255}
256
257impl FieldNode {
258    /// Create a new node
259    pub fn new(name: impl ToString) -> Self {
260        FieldNode {
261            name: name.to_string(),
262            span: None,
263        }
264    }
265
266    /// The name of the field that is being referenced
267    pub fn name(&self) -> &str {
268        &self.name
269    }
270
271    /// Visit this node with the provided visitor
272    pub fn accept(&mut self, visitor: &mut impl Visitor) {
273        visitor.visit_field_node(self)
274    }
275}
276
277impl From<FieldNode> for Expression {
278    fn from(node: FieldNode) -> Expression {
279        Expression::Field(node)
280    }
281}
282
283impl<T> From<T> for FieldNode
284where
285    T: ToString,
286{
287    fn from(name: T) -> Self {
288        FieldNode::new(name)
289    }
290}
291
292/// A node representing a reference to a field from the previous value
293///
294/// E.g. `LAST MlsStatus`
295#[derive(Clone, Eq, PartialEq)]
296#[non_exhaustive]
297pub struct LastFieldNode {
298    /// The name of the field that is being referenced
299    pub name: String,
300    span: Option<Span>,
301}
302
303impl LastFieldNode {
304    /// Create a new node
305    pub fn new(name: impl ToString) -> Self {
306        LastFieldNode {
307            name: name.to_string(),
308            span: None,
309        }
310    }
311
312    /// The name of the field that is being referenced
313    pub fn name(&self) -> &str {
314        &self.name
315    }
316
317    /// Visit this node with the provided visitor
318    pub fn accept(&mut self, visitor: &mut impl Visitor) {
319        visitor.visit_last_field_node(self)
320    }
321}
322
323impl From<LastFieldNode> for Expression {
324    fn from(node: LastFieldNode) -> Expression {
325        Expression::LastField(node)
326    }
327}
328
329impl<T> From<T> for LastFieldNode
330where
331    T: ToString,
332{
333    fn from(name: T) -> Self {
334        LastFieldNode::new(name)
335    }
336}
337
338/// A node representing the logical conjunction of two or more expressions
339///
340/// E.g. `A .AND. B`
341#[derive(Clone, Eq, PartialEq)]
342#[non_exhaustive]
343pub struct AndNode {
344    /// The expressions that are and-ed together
345    pub children: Vec<Expression>,
346    span: Option<Span>,
347}
348
349impl AndNode {
350    /// Create a new node
351    pub fn new(children: impl Expressions) -> Self {
352        AndNode {
353            children: children.to_vec(),
354            span: None,
355        }
356    }
357
358    /// An iterator over the expressions
359    pub fn iter(&self) -> impl Iterator<Item = &Expression> {
360        self.children.iter()
361    }
362
363    /// Visit this node with the provided visitor
364    pub fn accept(&mut self, visitor: &mut impl Visitor) {
365        visitor.visit_and_node_in(self);
366        for child in &mut self.children {
367            child.accept(visitor)
368        }
369        visitor.visit_and_node_out(self);
370    }
371}
372
373impl From<AndNode> for Expression {
374    fn from(node: AndNode) -> Expression {
375        Expression::And(node)
376    }
377}
378
379impl<T> From<T> for AndNode
380where
381    T: Expressions,
382{
383    fn from(expressions: T) -> Self {
384        AndNode::new(expressions)
385    }
386}
387
388/// A node representing the logical disjunction of two or more expressions
389///
390/// E.g. `A .OR. B`
391#[derive(Clone, Eq, PartialEq)]
392#[non_exhaustive]
393pub struct OrNode {
394    /// The expressions that are or-ed together
395    pub children: Vec<Expression>,
396    span: Option<Span>,
397}
398
399impl OrNode {
400    /// Create a new node
401    pub fn new(children: impl Expressions) -> Self {
402        OrNode {
403            children: children.to_vec(),
404            span: None,
405        }
406    }
407
408    /// An iterator over the expressions
409    pub fn iter(&self) -> impl Iterator<Item = &Expression> {
410        self.children.iter()
411    }
412
413    /// Visit this node with the provided visitor
414    pub fn accept(&mut self, visitor: &mut impl Visitor) {
415        visitor.visit_or_node_in(self);
416        for child in &mut self.children {
417            child.accept(visitor)
418        }
419        visitor.visit_or_node_out(self);
420    }
421}
422
423impl From<OrNode> for Expression {
424    fn from(node: OrNode) -> Expression {
425        Expression::Or(node)
426    }
427}
428
429impl<T> From<T> for OrNode
430where
431    T: Expressions,
432{
433    fn from(expressions: T) -> Self {
434        OrNode::new(expressions)
435    }
436}
437
438/// A node representing the logical negation of an expression
439///
440/// E.g. `.NOT. A`
441#[derive(Clone, Eq, PartialEq)]
442#[non_exhaustive]
443pub struct NotNode {
444    /// The negated expression
445    pub expression: Box<Expression>,
446    span: Option<Span>,
447}
448
449impl NotNode {
450    /// Create a new node
451    pub fn new(expression: impl Into<Box<Expression>>) -> Self {
452        NotNode {
453            expression: expression.into(),
454            span: None,
455        }
456    }
457
458    /// The negated expression
459    pub fn expression(&self) -> &Expression {
460        &self.expression
461    }
462
463    /// Visit this node with the provided visitor
464    pub fn accept(&mut self, visitor: &mut impl Visitor) {
465        visitor.visit_not_node_in(self);
466        self.expression.accept(visitor);
467        visitor.visit_not_node_out(self);
468    }
469}
470
471impl From<NotNode> for Expression {
472    fn from(node: NotNode) -> Expression {
473        Expression::Not(node)
474    }
475}
476
477/// A node representing a binary operation
478///
479/// E.g. `A + B`
480#[derive(Clone, Eq, PartialEq)]
481#[non_exhaustive]
482pub struct OpNode {
483    /// The expression on the left of the operation
484    pub left: Box<Expression>,
485    /// The operation to perform
486    pub op: ExpressionOp,
487    /// The expression on the left of the operation
488    pub right: Box<Expression>,
489    op_span: Option<Span>,
490}
491
492impl OpNode {
493    /// Create a new node
494    pub fn new(
495        left: impl Into<Box<Expression>>,
496        op: ExpressionOp,
497        right: impl Into<Box<Expression>>,
498    ) -> Self {
499        OpNode {
500            left: left.into(),
501            op,
502            right: right.into(),
503            op_span: None,
504        }
505    }
506
507    /// The expression on the left of the operation
508    pub fn left(&self) -> &Expression {
509        &self.left
510    }
511    /// The expression on the left of the operation
512    pub fn right(&self) -> &Expression {
513        &self.right
514    }
515    /// The operation being performed
516    pub fn op(&self) -> &ExpressionOp {
517        &self.op
518    }
519
520    /// Visit this node with the provided visitor
521    pub fn accept(&mut self, visitor: &mut impl Visitor) {
522        visitor.visit_op_node_in(self);
523        self.left.accept(visitor);
524        self.right.accept(visitor);
525        visitor.visit_op_node_out(self);
526    }
527}
528
529macro_rules! convenience_op_node {
530    ($ident:ident, $op:expr) => {
531        /// Create a new node
532        pub fn $ident(
533            left: impl Into<Box<Expression>>,
534            right: impl Into<Box<Expression>>,
535        ) -> OpNode {
536            OpNode::new(left, $op, right)
537        }
538    };
539}
540
541impl OpNode {
542    convenience_op_node!(add, ExpressionOp::Add);
543    convenience_op_node!(sub, ExpressionOp::Sub);
544    convenience_op_node!(mul, ExpressionOp::Mul);
545    convenience_op_node!(div, ExpressionOp::Div);
546    convenience_op_node!(gt, ExpressionOp::Gt);
547    convenience_op_node!(gte, ExpressionOp::Gte);
548    convenience_op_node!(lt, ExpressionOp::Lt);
549    convenience_op_node!(lte, ExpressionOp::Lte);
550    convenience_op_node!(eq, ExpressionOp::Eq);
551    convenience_op_node!(ne, ExpressionOp::Ne);
552}
553
554impl From<OpNode> for Expression {
555    fn from(node: OpNode) -> Expression {
556        Expression::Op(node)
557    }
558}
559
560/// A node representing a literal value
561///
562/// E.g. `.TRUE.`
563#[derive(Clone, Eq, PartialEq)]
564#[non_exhaustive]
565pub struct LiteralNode {
566    /// The literal value
567    pub value: Value,
568    span: Option<Span>,
569}
570
571impl LiteralNode {
572    /// Create a new node
573    pub fn new(value: Value) -> Self {
574        LiteralNode { value, span: None }
575    }
576
577    /// The literal value
578    pub fn value(&self) -> &Value {
579        &self.value
580    }
581
582    /// Visit this node with the provided visitor
583    pub fn accept(&mut self, visitor: &mut impl Visitor) {
584        visitor.visit_literal_node(self);
585    }
586}
587
588impl From<LiteralNode> for Expression {
589    fn from(node: LiteralNode) -> Expression {
590        Expression::Literal(node)
591    }
592}
593
594/// A node representing a function call
595///
596/// E.g. `SUBSTR('A', 1, 2)`
597#[derive(Clone, Eq, PartialEq)]
598#[non_exhaustive]
599pub struct FunctionNode {
600    /// The name of the function to execute
601    pub name: String,
602    /// The arguments to the function
603    pub arguments: Vec<Expression>,
604    name_span: Option<Span>,
605    left_parens_span: Option<Span>,
606    right_parens_span: Option<Span>,
607}
608
609impl FunctionNode {
610    /// Create a new node
611    pub fn new(name: impl ToString, arguments: impl Expressions) -> Self {
612        FunctionNode {
613            name: name.to_string(),
614            arguments: arguments.to_vec(),
615            name_span: None,
616            left_parens_span: None,
617            right_parens_span: None,
618        }
619    }
620
621    /// The name of the function to execute
622    pub fn name(&self) -> &str {
623        &self.name
624    }
625
626    /// An iterator over the arguments of the function
627    pub fn iter(&self) -> impl Iterator<Item = &Expression> {
628        self.arguments.iter()
629    }
630
631    /// Visit this node with the provided visitor
632    pub fn accept(&mut self, visitor: &mut impl Visitor) {
633        visitor.visit_function_node_in(self);
634        for argument in &mut self.arguments {
635            argument.accept(visitor);
636        }
637        visitor.visit_function_node_out(self);
638    }
639}
640
641impl From<FunctionNode> for Expression {
642    fn from(node: FunctionNode) -> Expression {
643        Expression::Function(node)
644    }
645}
646
647/// A node representing the special `IIF` conditional syntax
648///
649/// E.g. `IIF(A, B, C)`
650#[derive(Clone, Eq, PartialEq)]
651#[non_exhaustive]
652pub struct IifNode {
653    /// The expression that represents the test or the conditional
654    pub test_expression: Box<Expression>,
655    /// The expression to execute if the test returns true
656    pub true_expression: Box<Expression>,
657    /// The expression to execute if the test returns false
658    pub false_expression: Box<Expression>,
659    span: Option<Span>,
660}
661
662impl IifNode {
663    /// Create a new node
664    pub fn new(
665        test: impl Into<Box<Expression>>,
666        t: impl Into<Box<Expression>>,
667        f: impl Into<Box<Expression>>,
668    ) -> Self {
669        IifNode {
670            test_expression: test.into(),
671            true_expression: t.into(),
672            false_expression: f.into(),
673            span: None,
674        }
675    }
676
677    /// The expression that represents the test or the conditional
678    pub fn test(&self) -> &Expression {
679        &self.test_expression
680    }
681
682    /// The expression to execute if the test returns true
683    pub fn t(&self) -> &Expression {
684        &self.true_expression
685    }
686
687    /// The expression to execute if the test returns false
688    pub fn f(&self) -> &Expression {
689        &self.false_expression
690    }
691
692    /// Visit this node with the provided visitor
693    pub fn accept(&mut self, visitor: &mut impl Visitor) {
694        visitor.visit_iif_node_in(self);
695        self.test_expression.accept(visitor);
696        self.true_expression.accept(visitor);
697        self.false_expression.accept(visitor);
698        visitor.visit_iif_node_out(self);
699    }
700}
701
702impl From<IifNode> for Expression {
703    fn from(node: IifNode) -> Expression {
704        Expression::Iif(node)
705    }
706}
707
708/// A node representing a list of items
709///
710/// E.g. `(1, 2, 3)`
711#[derive(Clone, Eq, PartialEq)]
712#[non_exhaustive]
713pub struct ListNode {
714    /// The items in the list
715    pub items: Vec<Expression>,
716    span: Option<Span>,
717}
718
719impl ListNode {
720    /// Create a new node
721    pub fn new(items: impl Expressions) -> Self {
722        ListNode {
723            items: items.to_vec(),
724            span: None,
725        }
726    }
727
728    /// Iterate over the expressions in the list
729    pub fn iter(&self) -> impl Iterator<Item = &Expression> {
730        self.items.iter()
731    }
732
733    /// Visit this node with the provided visitor
734    pub fn accept(&mut self, visitor: &mut impl Visitor) {
735        visitor.visit_list_node_in(self);
736        for argument in &mut self.items {
737            argument.accept(visitor);
738        }
739        visitor.visit_list_node_out(self);
740    }
741}
742
743impl From<ListNode> for Expression {
744    fn from(node: ListNode) -> Expression {
745        Expression::List(node)
746    }
747}
748
749impl FromStr for Expression {
750    type Err = String;
751
752    fn from_str(s: &str) -> Result<Self, Self::Err> {
753        match parser::parse::parse(s) {
754            Ok(expr) => Ok(expr),
755            Err(s) => Err(s),
756        }
757    }
758}
759
760/// A binary operation in an [`OpNode`]
761#[derive(Copy, Clone, Debug, Eq, PartialEq)]
762pub enum ExpressionOp {
763    /// Add two expressions `A + B`
764    Add,
765    /// Subtract one expression from another `A - B`
766    Sub,
767    /// Multiple two expressions `A * B`
768    Mul,
769    /// Divide one expression by another `A / B`
770    Div,
771    /// Take the modulus of one number with another `A .MOD. B`
772    Mod,
773    /// Concatenate two strings `A || B`
774    Concat,
775    /// Compare two expressions using a less-than comparison `A < B`
776    Lt,
777    /// Compare two expressions using a less-than-or-equal-to comparison `A <= B`
778    Lte,
779    /// Compare two expressions using a greater-than comparison `A > B`
780    Gt,
781    /// Compare two expressions using a greater-than-or-equal-to comparison `A >= B`
782    Gte,
783    /// Compare two expressions using an equal-to comparison `A = B`
784    Eq,
785    /// Compare two expressions using a not-equal-to comparison `A != B`
786    Ne,
787    /// Determine if one expression contains another expression `A .CONTAINS. B`
788    Contains,
789    /// Determine if one expression is in another expression `A .IN. B`
790    In,
791}
792
793impl ExpressionOp {
794    /// Apply the operation to two values
795    pub fn apply(self, left: &Value, right: &Value) -> Result<Value, Error> {
796        fn boolean(input: bool) -> Result<Value, Error> {
797            Ok(Value::Bool(input))
798        }
799
800        fn number<F, I, T1, T2>(
801            left: &serde_json::Number,
802            right: &serde_json::Number,
803            f: F,
804            i: I,
805        ) -> Result<Value, Error>
806        where
807            F: Fn(f64, f64) -> T1,
808            I: Fn(i64, i64) -> T2,
809            T1: Into<serde_json::Value>,
810            T2: Into<serde_json::Value>,
811        {
812            // If both are i64s, treat them call the function for i64s
813            if let (Some(i_left), Some(i_right)) = (left.as_i64(), right.as_i64()) {
814                return Ok(i(i_left, i_right).into());
815            }
816
817            let f_left = left.as_f64().ok_or(Error::InvalidNumber)?;
818            let f_right = right.as_f64().ok_or(Error::InvalidNumber)?;
819            Ok(f(f_left, f_right).into())
820        }
821
822        fn string(input: String) -> Result<Value, Error> {
823            Ok(Value::String(input))
824        }
825
826        fn number_res<F, I, T1, T2>(
827            left: &serde_json::Number,
828            right: &serde_json::Number,
829            f: F,
830            i: I,
831        ) -> Result<Value, Error>
832        where
833            F: Fn(f64, f64) -> Result<T1, Error>,
834            I: Fn(i64, i64) -> Result<T2, Error>,
835            T1: Into<serde_json::Value>,
836            T2: Into<serde_json::Value>,
837        {
838            // If both are i64s, treat them call the function for i64s
839            if let (Some(i_left), Some(i_right)) = (left.as_i64(), right.as_i64()) {
840                return Ok(i(i_left, i_right)?.into());
841            }
842
843            let f_left = left.as_f64().ok_or(Error::InvalidNumber)?;
844            let f_right = right.as_f64().ok_or(Error::InvalidNumber)?;
845            Ok(f(f_left, f_right)?.into())
846        }
847
848        fn add_date_number(left: &str, right: &serde_json::Number) -> Result<Value, Error> {
849            if let Ok(date) = NaiveDate::parse_from_str(left, "%Y-%m-%d") {
850                let days = right.as_f64().ok_or(Error::InvalidNumber)? as u64;
851                let new_date = date
852                    .checked_add_days(chrono::Days::new(days))
853                    .ok_or(Error::InvalidType)?;
854                Ok(Value::String(new_date.format("%Y-%m-%d").to_string()))
855            } else if let Ok(timestamp) = DateTime::parse_from_rfc3339(left) {
856                let days = right.as_f64().ok_or(Error::InvalidNumber)?;
857                let milliseconds = (days * 24.0 * 60.0 * 60.0 * 1000.0) as i64;
858                let new_timestamp = timestamp
859                    .checked_add_signed(chrono::Duration::milliseconds(milliseconds))
860                    .ok_or(Error::InvalidType)?;
861                Ok(Value::String(
862                    new_timestamp.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
863                ))
864            } else {
865                Err(Error::InvalidType)
866            }
867        }
868
869        fn add_number_date(left: &serde_json::Number, right: &str) -> Result<Value, Error> {
870            add_date_number(right, left)
871        }
872
873        fn subtract_date_number(left: &str, right: &serde_json::Number) -> Result<Value, Error> {
874            if let Ok(date) = NaiveDate::parse_from_str(left, "%Y-%m-%d") {
875                let days = right.as_f64().ok_or(Error::InvalidNumber)? as u64;
876                let new_date = date
877                    .checked_sub_days(chrono::Days::new(days))
878                    .ok_or(Error::InvalidType)?;
879                Ok(Value::String(new_date.format("%Y-%m-%d").to_string()))
880            } else if let Ok(timestamp) = DateTime::parse_from_rfc3339(left) {
881                let days = right.as_f64().ok_or(Error::InvalidNumber)?;
882                let milliseconds = (days * 24.0 * 60.0 * 60.0 * 1000.0) as i64;
883                let new_timestamp = timestamp
884                    .checked_sub_signed(chrono::Duration::milliseconds(milliseconds))
885                    .ok_or(Error::InvalidType)?;
886                Ok(Value::String(
887                    new_timestamp.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
888                ))
889            } else {
890                Err(Error::InvalidType)
891            }
892        }
893
894        fn subtract_date_date(left: &str, right: &str) -> Result<Value, Error> {
895            if let (Ok(left), Ok(right)) = (
896                NaiveDate::parse_from_str(left, "%Y-%m-%d"),
897                NaiveDate::parse_from_str(right, "%Y-%m-%d"),
898            ) {
899                let duration = left.signed_duration_since(right);
900                Ok(Value::Number(serde_json::Number::from(duration.num_days())))
901            } else if let (Ok(left), Ok(right)) = (
902                DateTime::parse_from_rfc3339(left),
903                DateTime::parse_from_rfc3339(right),
904            ) {
905                let duration = left.signed_duration_since(right);
906                let millis = duration.num_milliseconds();
907                let days = millis as f64 / (1000.0 * 60.0 * 60.0 * 24.0);
908                Ok(Value::Number(
909                    serde_json::Number::from_f64(days).ok_or(Error::InvalidNumber)?,
910                ))
911            } else {
912                Err(Error::InvalidType)
913            }
914        }
915
916        match (self, left, right) {
917            (Self::Eq, Value::Null, Value::Null) => boolean(true),
918            (Self::Eq, Value::Null, _) => boolean(false),
919            (Self::Eq, _, Value::Null) => boolean(false),
920            (Self::Eq, Value::Bool(ref a), Value::Bool(ref b)) => boolean(a == b),
921            (Self::Eq, Value::Number(ref a), Value::Number(ref b)) => {
922                number(a, b, |a, b| a == b, |a, b| a == b)
923            }
924            (Self::Eq, Value::String(ref a), Value::String(ref b)) => boolean(a == b),
925            (Self::Eq, _, _) => boolean(false),
926
927            (Self::Ne, Value::Null, Value::Null) => boolean(false),
928            (Self::Ne, Value::Null, _) => boolean(true),
929            (Self::Ne, _, Value::Null) => boolean(true),
930            (Self::Ne, Value::Bool(ref a), Value::Bool(ref b)) => boolean(a != b),
931            (Self::Ne, Value::Number(ref a), Value::Number(ref b)) => {
932                number(a, b, |a, b| a != b, |a, b| a != b)
933            }
934            (Self::Ne, Value::String(ref a), Value::String(ref b)) => boolean(a != b),
935            (Self::Ne, _, _) => boolean(true),
936
937            (Self::Lt, Value::Null, Value::Null) => boolean(false),
938            (Self::Lt, Value::Null, _) => boolean(true),
939            (Self::Lt, _, Value::Null) => boolean(false),
940            (Self::Lt, Value::Bool(ref a), Value::Bool(ref b)) => boolean(a < b),
941            (Self::Lt, Value::Number(ref a), Value::Number(ref b)) => {
942                number(a, b, |a, b| a < b, |a, b| a < b)
943            }
944            (Self::Lt, Value::String(ref a), Value::String(ref b)) => boolean(a < b),
945            (Self::Lt, _, _) => Err(Error::InvalidType),
946
947            (Self::Lte, Value::Null, Value::Null) => boolean(true),
948            (Self::Lte, Value::Null, _) => boolean(true),
949            (Self::Lte, _, Value::Null) => boolean(false),
950            (Self::Lte, Value::Bool(ref a), Value::Bool(ref b)) => boolean(a <= b),
951            (Self::Lte, Value::Number(ref a), Value::Number(ref b)) => {
952                number(a, b, |a, b| a <= b, |a, b| a <= b)
953            }
954            (Self::Lte, Value::String(ref a), Value::String(ref b)) => boolean(a <= b),
955            (Self::Lte, _, _) => Err(Error::InvalidType),
956
957            (Self::Gt, Value::Null, Value::Null) => boolean(false),
958            (Self::Gt, Value::Null, _) => boolean(false),
959            (Self::Gt, _, Value::Null) => boolean(true),
960            (Self::Gt, Value::Bool(ref a), Value::Bool(ref b)) => boolean(a > b),
961            (Self::Gt, Value::Number(ref a), Value::Number(ref b)) => {
962                number(a, b, |a, b| a > b, |a, b| a > b)
963            }
964            (Self::Gt, Value::String(ref a), Value::String(ref b)) => boolean(a > b),
965            (Self::Gt, _, _) => Err(Error::InvalidType),
966
967            (Self::Gte, Value::Null, Value::Null) => boolean(true),
968            (Self::Gte, Value::Null, _) => boolean(false),
969            (Self::Gte, _, Value::Null) => boolean(true),
970            (Self::Gte, Value::Bool(ref a), Value::Bool(ref b)) => boolean(a >= b),
971            (Self::Gte, Value::Number(ref a), Value::Number(ref b)) => {
972                number(a, b, |a, b| a >= b, |a, b| a >= b)
973            }
974            (Self::Gte, Value::String(ref a), Value::String(ref b)) => boolean(a >= b),
975            (Self::Gte, _, _) => Err(Error::InvalidType),
976
977            (Self::Add, Value::Number(ref a), Value::Number(ref b)) => {
978                number(a, b, |a, b| a + b, |a, b| a + b)
979            }
980            (Self::Add, Value::String(ref s), Value::Number(ref t)) => add_date_number(s, t),
981            (Self::Add, Value::Number(ref t), Value::String(ref s)) => add_number_date(t, s),
982            (Self::Add, _, _) => Err(Error::InvalidType),
983
984            (Self::Sub, Value::Number(ref a), Value::Number(ref b)) => {
985                number(a, b, |a, b| a - b, |a, b| a - b)
986            }
987            (Self::Sub, Value::String(ref s), Value::Number(ref t)) => subtract_date_number(s, t),
988            (Self::Sub, Value::String(ref s), Value::String(ref t)) => subtract_date_date(s, t),
989            (Self::Sub, _, _) => Err(Error::InvalidType),
990
991            (Self::Mul, Value::Number(ref a), Value::Number(ref b)) => {
992                number(a, b, |a, b| a * b, |a, b| a * b)
993            }
994            (Self::Mul, _, _) => Err(Error::InvalidType),
995
996            (Self::Div, Value::Number(ref a), Value::Number(ref b)) => number_res(
997                a,
998                b,
999                |a, b| {
1000                    if b == 0.0 {
1001                        return Err(Error::DivideByZero);
1002                    }
1003                    Ok(a / b)
1004                },
1005                |a, b| {
1006                    if b == 0 {
1007                        return Err(Error::DivideByZero);
1008                    }
1009                    Ok(a / b)
1010                },
1011            ),
1012            (Self::Div, _, _) => Err(Error::InvalidType),
1013
1014            (Self::Mod, Value::Number(ref a), Value::Number(ref b)) => {
1015                number(a, b, |a, b| a % b, |a, b| a % b)
1016            }
1017            (Self::Mod, _, _) => Err(Error::InvalidType),
1018
1019            (Self::Concat, Value::String(ref a), Value::String(ref b)) => string(format!("{a}{b}")),
1020            (Self::Concat, _, _) => Err(Error::InvalidType),
1021
1022            (Self::Contains, Value::Array(ref left), right) => {
1023                boolean(left.iter().any(|item| item == right))
1024            }
1025            (Self::Contains, _, _) => Err(Error::InvalidType),
1026
1027            (Self::In, left, Value::Array(ref right)) => {
1028                boolean(right.iter().any(|item| item == left))
1029            }
1030            (Self::In, _, _) => Err(Error::InvalidType),
1031        }
1032    }
1033}
1034
1035impl Expression {
1036    /// Run the expression to completion and return the result
1037    pub fn apply<'expr, 'val, T>(
1038        &'expr self,
1039        context: EvaluateContext<'_, 'val, T>,
1040    ) -> Result<Cow<'val, Value>, Error>
1041    where
1042        'expr: 'val,
1043    {
1044        self.apply_with_locals(context, &BTreeMap::default())
1045    }
1046
1047    /// Run the expression to completion and return the result
1048    ///
1049    /// Locals can be used to augment or override the provided JSON values.
1050    pub fn apply_with_locals<'expr, 'val, T>(
1051        &'expr self,
1052        context: EvaluateContext<'_, 'val, T>,
1053        locals: &BTreeMap<&'expr str, Cow<'val, Value>>,
1054    ) -> Result<Cow<'val, Value>, Error>
1055    where
1056        'expr: 'val,
1057    {
1058        let mut context = context;
1059        self.apply_with_locals_inner(&mut context, locals)
1060    }
1061
1062    fn apply_with_locals_inner<'expr, 'val, T>(
1063        &'expr self,
1064        context: &mut EvaluateContext<'_, 'val, T>,
1065        locals: &BTreeMap<&'expr str, Cow<'val, Value>>,
1066    ) -> Result<Cow<'val, Value>, Error>
1067    where
1068        'expr: 'val,
1069    {
1070        match self {
1071            Expression::Field(ref node) => {
1072                if let Some(local) = locals.get(node.name()) {
1073                    Ok(local.clone())
1074                } else {
1075                    Ok(context
1076                        .value()
1077                        .get(node.name())
1078                        .map(Cow::Borrowed)
1079                        .unwrap_or_else(|| Cow::Owned(Value::Null)))
1080                }
1081            }
1082            Expression::LastField(ref node) => {
1083                if let Some(previous_value) = context.previous_value() {
1084                    Ok(previous_value
1085                        .get(node.name())
1086                        .map(Cow::Borrowed)
1087                        .unwrap_or_else(|| Cow::Owned(Value::Null)))
1088                } else {
1089                    Err(Error::LastUsedWithoutPreviousValue)
1090                }
1091            }
1092            Expression::And(exprs) => {
1093                for expr in exprs.iter() {
1094                    let result = expr.apply_with_locals_inner(context, locals)?;
1095                    match result.as_ref() {
1096                        Value::Bool(false) => {
1097                            // Early return false
1098                            return Ok(Cow::Owned(Value::Bool(false)));
1099                        }
1100                        Value::Bool(true) => {
1101                            // Keep making sure all are true
1102                        }
1103                        _ => return Err(Error::InvalidType),
1104                    }
1105                }
1106
1107                Ok(Cow::Owned(Value::Bool(true)))
1108            }
1109            Expression::Or(exprs) => {
1110                for expr in exprs.iter() {
1111                    let result = expr.apply_with_locals_inner(context, locals)?;
1112                    match result.as_ref() {
1113                        Value::Bool(true) => {
1114                            // Early return true
1115                            return Ok(Cow::Owned(Value::Bool(true)));
1116                        }
1117                        Value::Bool(false) => {
1118                            // Keep searching for a true
1119                        }
1120                        _ => return Err(Error::InvalidType),
1121                    }
1122                }
1123
1124                Ok(Cow::Owned(Value::Bool(false)))
1125            }
1126            Expression::Iif(ref node) => {
1127                let value = node.test().apply_with_locals_inner(context, locals)?;
1128                match value.as_ref() {
1129                    Value::Bool(true) => node.t().apply_with_locals_inner(context, locals),
1130                    Value::Bool(false) => node.f().apply_with_locals_inner(context, locals),
1131                    _ => Err(Error::InvalidType),
1132                }
1133            }
1134            Expression::Op(node) => {
1135                let value1 = node.left().apply_with_locals_inner(context, locals)?;
1136                let value2 = node.right().apply_with_locals_inner(context, locals)?;
1137                node.op()
1138                    .apply(value1.as_ref(), value2.as_ref())
1139                    .map(Cow::Owned)
1140            }
1141            Expression::Literal(ref node) => Ok(Cow::Borrowed(node.value())),
1142            Expression::Not(ref node) => {
1143                let value = node.expression().apply_with_locals_inner(context, locals)?;
1144                match value.as_ref() {
1145                    Value::Bool(ref b) => Ok(Cow::Owned(Value::Bool(!b))),
1146                    _ => Err(Error::InvalidType),
1147                }
1148            }
1149            Expression::Function(ref node) => {
1150                let args = node
1151                    .iter()
1152                    .map(|expression| expression.apply_with_locals_inner(context, locals))
1153                    .collect::<Result<Vec<_>, _>>()?;
1154
1155                let function = context
1156                    .engine()
1157                    .function(node.name())
1158                    .ok_or_else(|| Error::UnknownFunction(node.name().to_string()))?;
1159                function
1160                    .evaluate(context.function_context(), args)
1161                    .map_err(Error::Function)
1162            }
1163            Expression::List(ref node) => {
1164                let args = node
1165                    .iter()
1166                    .map(|expression| expression.apply_with_locals_inner(context, locals))
1167                    .collect::<Result<Vec<_>, _>>()?;
1168                Ok(Cow::Owned(serde_json::json!(args)))
1169            }
1170        }
1171    }
1172}
1173
1174/// A trait that represents a list of expressions that can be used when creating nodes like
1175/// [`AndNode`] or [`FunctionNode`].
1176pub trait Expressions {
1177    /// Create a list of expressions
1178    fn to_vec(self) -> Vec<Expression>;
1179}
1180
1181impl Expressions for Vec<Expression> {
1182    fn to_vec(self) -> Vec<Expression> {
1183        self
1184    }
1185}
1186impl<const N: usize> Expressions for [Expression; N] {
1187    fn to_vec(self) -> Vec<Expression> {
1188        self.into_iter().collect()
1189    }
1190}
1191
1192/// An error that occured while evaluating an expression
1193#[derive(Debug)]
1194pub enum Error {
1195    /// `LAST FieldName` was used but no previous value was provided
1196    LastUsedWithoutPreviousValue,
1197    /// The expression expected a certain type, but the value was not the expected type
1198    InvalidType,
1199    /// Some aspect of evaluation is not implemented
1200    NotImplemented,
1201    /// The expression did not result in a number that can be used
1202    InvalidNumber,
1203    /// The expression attempted to divide by zero
1204    DivideByZero,
1205    /// A function call was used to a function that does not exist
1206    UnknownFunction(String),
1207    /// A function call failed
1208    Function(function::FunctionError),
1209}
1210
1211impl core::fmt::Display for Error {
1212    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1213        match self {
1214            Error::LastUsedWithoutPreviousValue => {
1215                f.write_str("`LAST FieldName` was used but no previous value was provided")
1216            }
1217            Error::InvalidType => f.write_str("Invalid type"),
1218            Error::NotImplemented => f.write_str("Not implemented"),
1219            Error::InvalidNumber => f.write_str("Invalid number"),
1220            Error::DivideByZero => f.write_str("Divide by zero"),
1221            Error::UnknownFunction(name) => write!(f, "Unknown function: {name}"),
1222            Error::Function(err) => write!(f, "Error while executing function: {err}"),
1223        }
1224    }
1225}
1226
1227impl core::error::Error for Error {}
1228
1229/// Visit nodes in the Expression
1230///
1231/// Use this to transform expressions or to inspect the structure of expressions without recursively
1232/// evaluating them.
1233///
1234/// ## Example
1235///
1236/// ```
1237/// use rets_expression::{Expression, Visitor, FunctionNode, LiteralNode};
1238/// let mut expression = "5 .IN. (1, 2, Three, LAST Four, Five)"
1239///     .parse::<Expression>()
1240///     .unwrap();
1241///
1242/// /// A visitor that rewrites native lists into `LIST` function calls.
1243/// struct RewriteNativeListVisitor;
1244///
1245/// impl Visitor for RewriteNativeListVisitor {
1246///     fn visit_list_expression_in(&mut self, expression: &mut Expression) {
1247///         let list_expression = std::mem::replace(
1248///             expression,
1249///             Expression::Literal(LiteralNode::new(serde_json::Value::Null)),
1250///         );
1251///         let Expression::List(list_node) = list_expression else {
1252///             unreachable!()
1253///         };
1254///         let function_node = FunctionNode::new("LIST", list_node.items);
1255///         let function_expression = Expression::from(function_node);
1256///         *expression = function_expression;
1257///     }
1258/// }
1259///
1260/// expression.accept(&mut RewriteNativeListVisitor);
1261///
1262/// let serialized = expression.serialize().unwrap();
1263/// assert_eq!(serialized, "5 .IN. LIST(1, 2, Three, LAST Four, Five)");
1264/// ```
1265#[allow(unused_variables)]
1266pub trait Visitor {
1267    /// Called when the visitor visits an expression before calling any of the other visit methods
1268    fn visit_expression_in(&mut self, expression: &mut Expression) {}
1269    /// Called then the visitor visits an expression after calling all of the other visit methods
1270    fn visit_expression_out(&mut self, expression: &mut Expression) {}
1271
1272    /// Called when the visitor visits a [`FieldNode`]
1273    fn visit_field_node(&mut self, node: &mut FieldNode) {}
1274    /// Called when the visitor visits a [`LastFieldNode`]
1275    fn visit_last_field_node(&mut self, node: &mut LastFieldNode) {}
1276    /// Called when the visitor visits an [`AndNode`] before visiting its children
1277    fn visit_and_node_in(&mut self, node: &mut AndNode) {}
1278    /// Called when the visitor visits an [`AndNode`] after visiting its children
1279    fn visit_and_node_out(&mut self, node: &mut AndNode) {}
1280    /// Called when the visitor visits an [`OrNode`] before visiting its children
1281    fn visit_or_node_in(&mut self, node: &mut OrNode) {}
1282    /// Called when the visitor visits an [`OrNode`] after visiting its children
1283    fn visit_or_node_out(&mut self, node: &mut OrNode) {}
1284    /// Called when the visitor visits a [`NotNode`] before visiting its child
1285    fn visit_not_node_in(&mut self, node: &mut NotNode) {}
1286    /// Called when the visitor visits a [`NotNode`] after visiting its child
1287    fn visit_not_node_out(&mut self, node: &mut NotNode) {}
1288    /// Called when the visitor visits an [`OpNode`] before visiting its children
1289    fn visit_op_node_in(&mut self, node: &mut OpNode) {}
1290    /// Called when the visitor visits an [`OpNode`] after visiting its children
1291    fn visit_op_node_out(&mut self, node: &mut OpNode) {}
1292    /// Called when the visitor visits a [`LiteralNode`]
1293    fn visit_literal_node(&mut self, node: &mut LiteralNode) {}
1294    /// Called when the visitor visits a [`FunctionNode`] before visiting its children
1295    fn visit_function_node_in(&mut self, node: &mut FunctionNode) {}
1296    /// Called when the visitor visits a [`FunctionNode`] after visiting its children
1297    fn visit_function_node_out(&mut self, node: &mut FunctionNode) {}
1298    /// Called when the visitor visits a [`IifNode`] before visiting its children
1299    fn visit_iif_node_in(&mut self, node: &mut IifNode) {}
1300    /// Called when the visitor visits a [`IifNode`] after visiting its children
1301    fn visit_iif_node_out(&mut self, node: &mut IifNode) {}
1302    /// Called when the visitor visits a [`ListNode`] before visiting its children
1303    fn visit_list_node_in(&mut self, node: &mut ListNode) {}
1304    /// Called when the visitor visits a [`ListNode`] after visiting its children
1305    fn visit_list_node_out(&mut self, node: &mut ListNode) {}
1306
1307    /// Called when the visitor visits an expression representing a [`FieldNode`]
1308    fn visit_field_expression(&mut self, expression: &mut Expression) {}
1309    /// Called when the visitor visits an expression representing a [`LastFieldNode`]
1310    fn visit_last_field_expression(&mut self, expression: &mut Expression) {}
1311    /// Called when the visitor visits ann expression representing a [`AndNode`] before visiting its children
1312    fn visit_and_expression_in(&mut self, expression: &mut Expression) {}
1313    /// Called when the visitor visits ann expression representing a [`AndNode`] after visiting its children
1314    fn visit_and_expression_out(&mut self, expression: &mut Expression) {}
1315    /// Called when the visitor visits ann expression representing a [`OrNode`] before visiting its children
1316    fn visit_or_expression_in(&mut self, expression: &mut Expression) {}
1317    /// Called when the visitor visits ann expression representing a [`OrNode`] after visiting its children
1318    fn visit_or_expression_out(&mut self, expression: &mut Expression) {}
1319    /// Called when the visitor visits an expression representing a [`NotNode`] before visiting its child
1320    fn visit_not_expression_in(&mut self, expression: &mut Expression) {}
1321    /// Called when the visitor visits an expression representing a [`NotNode`] after visiting its child
1322    fn visit_not_expression_out(&mut self, expression: &mut Expression) {}
1323    /// Called when the visitor visits ann expression representing a [`OpNode`] before visiting its children
1324    fn visit_op_expression_in(&mut self, expression: &mut Expression) {}
1325    /// Called when the visitor visits ann expression representing a [`OpNode`] after visiting its children
1326    fn visit_op_expression_out(&mut self, expression: &mut Expression) {}
1327    /// Called when the visitor visits an expression representing a [`LiteralNode`]
1328    fn visit_literal_expression(&mut self, expression: &mut Expression) {}
1329    /// Called when the visitor visits an expression representing a [`FunctionNode`] before visiting its children
1330    fn visit_function_expression_in(&mut self, expression: &mut Expression) {}
1331    /// Called when the visitor visits an expression representing a [`FunctionNode`] after visiting its children
1332    fn visit_function_expression_out(&mut self, expression: &mut Expression) {}
1333    /// Called when the visitor visits an expression representing a [`IifNode`] before visiting its children
1334    fn visit_iif_expression_in(&mut self, expression: &mut Expression) {}
1335    /// Called when the visitor visits an expression representing a [`IifNode`] after visiting its children
1336    fn visit_iif_expression_out(&mut self, expression: &mut Expression) {}
1337    /// Called when the visitor visits an expression representing a [`ListNode`] before visiting its children
1338    fn visit_list_expression_in(&mut self, expression: &mut Expression) {}
1339    /// Called when the visitor visits an expression representing a [`ListNode`] after visiting its children
1340    fn visit_list_expression_out(&mut self, expression: &mut Expression) {}
1341}
1342
1343#[cfg(all(feature = "std", test))]
1344mod tests {
1345    use super::*;
1346    use serde_json::json;
1347
1348    #[test]
1349    fn test_basic() {
1350        let value = json!({
1351            "X": 1700,
1352            "Y": 400,
1353            "Z": 1700,
1354        });
1355        let previous_value = json!({
1356            "X": 1700,
1357            "Y": 300,
1358        });
1359
1360        let expression = "X = LAST X .AND. Y = LAST Y .OR. X = Z"
1361            .parse::<Expression>()
1362            .unwrap();
1363
1364        let engine = Engine::default();
1365
1366        let context = EvaluateContext::new(&engine, &value).with_previous(&previous_value);
1367        let value = expression.apply(context).unwrap();
1368        assert_eq!(value.into_owned(), json!(true));
1369    }
1370
1371    #[test]
1372    fn test_visitor() {
1373        let mut expression = "5 .IN. (1, 2, Three, LAST Four, Five)"
1374            .parse::<Expression>()
1375            .unwrap();
1376
1377        struct RewriteNativeListVisitor;
1378
1379        impl Visitor for RewriteNativeListVisitor {
1380            fn visit_list_expression_in(&mut self, expression: &mut Expression) {
1381                let list_expression = std::mem::replace(
1382                    expression,
1383                    Expression::Literal(LiteralNode::new(serde_json::Value::Null)),
1384                );
1385                let Expression::List(list_node) = list_expression else {
1386                    unreachable!()
1387                };
1388                let function_node = FunctionNode::new("LIST", list_node.items);
1389                let function_expression = Expression::from(function_node);
1390                *expression = function_expression;
1391            }
1392        }
1393
1394        expression.accept(&mut RewriteNativeListVisitor);
1395
1396        let serialized = expression.serialize().unwrap();
1397        assert_eq!(serialized, "5 .IN. LIST(1, 2, Three, LAST Four, Five)");
1398    }
1399}