diff --git a/src/lib.rs b/src/lib.rs index a69ae10..089dbe1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -594,6 +594,13 @@ mod tests { assert_eq!(tree.parse_node(), Err(Error::CommaNotWithFunction)); } + + #[test] + fn test_eval_issue_2() { + assert_eq!(eval("2 * (4 + 0) + 4"), Ok(to_value(12))); + assert_eq!(eval("2 * (2 + 2) + (1 + 3)"), Ok(to_value(12))); + assert_eq!(eval("2 * (4) + (4)"), Ok(to_value(12))); + } } #[cfg(all(feature = "unstable", test))] diff --git a/src/node/mod.rs b/src/node/mod.rs index c5c4eb9..5ed1a01 100644 --- a/src/node/mod.rs +++ b/src/node/mod.rs @@ -14,7 +14,7 @@ pub struct Node { impl Node { pub fn new(operator: Operator) -> Node { Node { - operator: operator, + operator, children: Vec::new(), closed: false, } @@ -47,7 +47,7 @@ impl Node { } } - pub fn is_value_or_enough(&self) -> bool { + pub fn is_value_or_full_children(&self) -> bool { if self.operator.is_value_or_ident() { true } else if self.operator.can_have_child() { @@ -57,6 +57,10 @@ impl Node { } } + pub fn is_unclosed_arithmetic(&self) -> bool { + return !self.closed && self.operator.can_have_child() && self.operator.can_have_child() + } + pub fn is_unclosed_function(&self) -> bool { match self.operator { Operator::Function(_) => !self.closed, diff --git a/src/tree/mod.rs b/src/tree/mod.rs index 0494c50..2456dd6 100644 --- a/src/tree/mod.rs +++ b/src/tree/mod.rs @@ -205,7 +205,7 @@ impl Tree { Operator::Rem(priority) => { if !parsing_nodes.is_empty() { let prev = parsing_nodes.pop().unwrap(); - if prev.is_value_or_enough() { + if prev.is_value_or_full_children() { if prev.operator.get_priority() < priority && !prev.closed { parsing_nodes.extend_from_slice(&rob_to(prev, operator.to_node())); } else { @@ -468,7 +468,7 @@ fn append_value_to_last_node(parsing_nodes: &mut Vec, } else if prev.is_left_square_bracket() { parsing_nodes.push(prev); parsing_nodes.push(node); - } else if prev.is_value_or_enough() { + } else if prev.is_value_or_full_children() { return Err(Error::DuplicateValueNode); } else if prev.is_enough() { parsing_nodes.push(prev); @@ -535,6 +535,9 @@ fn close_bracket(parsing_nodes: &mut Vec, bracket: Operator) -> Result<(), penult.closed = true; penult.add_child(current); parsing_nodes.push(penult); + } else if penult.is_unclosed_arithmetic() { + penult.add_child(current); + parsing_nodes.push(penult); } else { parsing_nodes.push(penult); parsing_nodes.push(current);