1#![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#[derive(Clone, Eq, PartialEq)]
62pub enum Expression {
63 Field(FieldNode),
67 LastField(LastFieldNode),
71 And(AndNode),
75 Or(OrNode),
79 Not(NotNode),
83 Op(OpNode),
87 Literal(LiteralNode),
91 Function(FunctionNode),
95 Iif(IifNode),
99 List(ListNode),
103}
104
105impl Expression {
106 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 pub fn $as_ref_name(&self) -> Option<&$node_type> {
210 match self {
211 Expression::$discriminant(node) => Some(node),
212 _ => None,
213 }
214 }
215
216 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#[derive(Clone, Eq, PartialEq)]
250#[non_exhaustive]
251pub struct FieldNode {
252 pub name: String,
254 span: Option<Span>,
255}
256
257impl FieldNode {
258 pub fn new(name: impl ToString) -> Self {
260 FieldNode {
261 name: name.to_string(),
262 span: None,
263 }
264 }
265
266 pub fn name(&self) -> &str {
268 &self.name
269 }
270
271 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#[derive(Clone, Eq, PartialEq)]
296#[non_exhaustive]
297pub struct LastFieldNode {
298 pub name: String,
300 span: Option<Span>,
301}
302
303impl LastFieldNode {
304 pub fn new(name: impl ToString) -> Self {
306 LastFieldNode {
307 name: name.to_string(),
308 span: None,
309 }
310 }
311
312 pub fn name(&self) -> &str {
314 &self.name
315 }
316
317 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#[derive(Clone, Eq, PartialEq)]
342#[non_exhaustive]
343pub struct AndNode {
344 pub children: Vec<Expression>,
346 span: Option<Span>,
347}
348
349impl AndNode {
350 pub fn new(children: impl Expressions) -> Self {
352 AndNode {
353 children: children.to_vec(),
354 span: None,
355 }
356 }
357
358 pub fn iter(&self) -> impl Iterator<Item = &Expression> {
360 self.children.iter()
361 }
362
363 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#[derive(Clone, Eq, PartialEq)]
392#[non_exhaustive]
393pub struct OrNode {
394 pub children: Vec<Expression>,
396 span: Option<Span>,
397}
398
399impl OrNode {
400 pub fn new(children: impl Expressions) -> Self {
402 OrNode {
403 children: children.to_vec(),
404 span: None,
405 }
406 }
407
408 pub fn iter(&self) -> impl Iterator<Item = &Expression> {
410 self.children.iter()
411 }
412
413 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#[derive(Clone, Eq, PartialEq)]
442#[non_exhaustive]
443pub struct NotNode {
444 pub expression: Box<Expression>,
446 span: Option<Span>,
447}
448
449impl NotNode {
450 pub fn new(expression: impl Into<Box<Expression>>) -> Self {
452 NotNode {
453 expression: expression.into(),
454 span: None,
455 }
456 }
457
458 pub fn expression(&self) -> &Expression {
460 &self.expression
461 }
462
463 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#[derive(Clone, Eq, PartialEq)]
481#[non_exhaustive]
482pub struct OpNode {
483 pub left: Box<Expression>,
485 pub op: ExpressionOp,
487 pub right: Box<Expression>,
489 op_span: Option<Span>,
490}
491
492impl OpNode {
493 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 pub fn left(&self) -> &Expression {
509 &self.left
510 }
511 pub fn right(&self) -> &Expression {
513 &self.right
514 }
515 pub fn op(&self) -> &ExpressionOp {
517 &self.op
518 }
519
520 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 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#[derive(Clone, Eq, PartialEq)]
564#[non_exhaustive]
565pub struct LiteralNode {
566 pub value: Value,
568 span: Option<Span>,
569}
570
571impl LiteralNode {
572 pub fn new(value: Value) -> Self {
574 LiteralNode { value, span: None }
575 }
576
577 pub fn value(&self) -> &Value {
579 &self.value
580 }
581
582 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#[derive(Clone, Eq, PartialEq)]
598#[non_exhaustive]
599pub struct FunctionNode {
600 pub name: String,
602 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 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 pub fn name(&self) -> &str {
623 &self.name
624 }
625
626 pub fn iter(&self) -> impl Iterator<Item = &Expression> {
628 self.arguments.iter()
629 }
630
631 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#[derive(Clone, Eq, PartialEq)]
651#[non_exhaustive]
652pub struct IifNode {
653 pub test_expression: Box<Expression>,
655 pub true_expression: Box<Expression>,
657 pub false_expression: Box<Expression>,
659 span: Option<Span>,
660}
661
662impl IifNode {
663 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 pub fn test(&self) -> &Expression {
679 &self.test_expression
680 }
681
682 pub fn t(&self) -> &Expression {
684 &self.true_expression
685 }
686
687 pub fn f(&self) -> &Expression {
689 &self.false_expression
690 }
691
692 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#[derive(Clone, Eq, PartialEq)]
712#[non_exhaustive]
713pub struct ListNode {
714 pub items: Vec<Expression>,
716 span: Option<Span>,
717}
718
719impl ListNode {
720 pub fn new(items: impl Expressions) -> Self {
722 ListNode {
723 items: items.to_vec(),
724 span: None,
725 }
726 }
727
728 pub fn iter(&self) -> impl Iterator<Item = &Expression> {
730 self.items.iter()
731 }
732
733 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
762pub enum ExpressionOp {
763 Add,
765 Sub,
767 Mul,
769 Div,
771 Mod,
773 Concat,
775 Lt,
777 Lte,
779 Gt,
781 Gte,
783 Eq,
785 Ne,
787 Contains,
789 In,
791}
792
793impl ExpressionOp {
794 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 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 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 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 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 return Ok(Cow::Owned(Value::Bool(false)));
1099 }
1100 Value::Bool(true) => {
1101 }
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 return Ok(Cow::Owned(Value::Bool(true)));
1116 }
1117 Value::Bool(false) => {
1118 }
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
1174pub trait Expressions {
1177 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#[derive(Debug)]
1194pub enum Error {
1195 LastUsedWithoutPreviousValue,
1197 InvalidType,
1199 NotImplemented,
1201 InvalidNumber,
1203 DivideByZero,
1205 UnknownFunction(String),
1207 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#[allow(unused_variables)]
1266pub trait Visitor {
1267 fn visit_expression_in(&mut self, expression: &mut Expression) {}
1269 fn visit_expression_out(&mut self, expression: &mut Expression) {}
1271
1272 fn visit_field_node(&mut self, node: &mut FieldNode) {}
1274 fn visit_last_field_node(&mut self, node: &mut LastFieldNode) {}
1276 fn visit_and_node_in(&mut self, node: &mut AndNode) {}
1278 fn visit_and_node_out(&mut self, node: &mut AndNode) {}
1280 fn visit_or_node_in(&mut self, node: &mut OrNode) {}
1282 fn visit_or_node_out(&mut self, node: &mut OrNode) {}
1284 fn visit_not_node_in(&mut self, node: &mut NotNode) {}
1286 fn visit_not_node_out(&mut self, node: &mut NotNode) {}
1288 fn visit_op_node_in(&mut self, node: &mut OpNode) {}
1290 fn visit_op_node_out(&mut self, node: &mut OpNode) {}
1292 fn visit_literal_node(&mut self, node: &mut LiteralNode) {}
1294 fn visit_function_node_in(&mut self, node: &mut FunctionNode) {}
1296 fn visit_function_node_out(&mut self, node: &mut FunctionNode) {}
1298 fn visit_iif_node_in(&mut self, node: &mut IifNode) {}
1300 fn visit_iif_node_out(&mut self, node: &mut IifNode) {}
1302 fn visit_list_node_in(&mut self, node: &mut ListNode) {}
1304 fn visit_list_node_out(&mut self, node: &mut ListNode) {}
1306
1307 fn visit_field_expression(&mut self, expression: &mut Expression) {}
1309 fn visit_last_field_expression(&mut self, expression: &mut Expression) {}
1311 fn visit_and_expression_in(&mut self, expression: &mut Expression) {}
1313 fn visit_and_expression_out(&mut self, expression: &mut Expression) {}
1315 fn visit_or_expression_in(&mut self, expression: &mut Expression) {}
1317 fn visit_or_expression_out(&mut self, expression: &mut Expression) {}
1319 fn visit_not_expression_in(&mut self, expression: &mut Expression) {}
1321 fn visit_not_expression_out(&mut self, expression: &mut Expression) {}
1323 fn visit_op_expression_in(&mut self, expression: &mut Expression) {}
1325 fn visit_op_expression_out(&mut self, expression: &mut Expression) {}
1327 fn visit_literal_expression(&mut self, expression: &mut Expression) {}
1329 fn visit_function_expression_in(&mut self, expression: &mut Expression) {}
1331 fn visit_function_expression_out(&mut self, expression: &mut Expression) {}
1333 fn visit_iif_expression_in(&mut self, expression: &mut Expression) {}
1335 fn visit_iif_expression_out(&mut self, expression: &mut Expression) {}
1337 fn visit_list_expression_in(&mut self, expression: &mut Expression) {}
1339 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}