Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 86abfb4

Browse files
Fix expressions with multiple operators. (#12)
* Fix expressions with multiple operators. Expressions such as ``1 +2;`` or ``300*200`` work, but expressions which have multiple operations do not work. For example: ``1+2+3+4`` does not work, and has to be put in a chain of parentheses to get it to work. The other valid expressions are getting evaluated to the value of the first operator, for instance, ``1*2*3`` becomes 2, by evaluating 1*2 and so on. This can be solved by adding a loop, converting the first two expressions into ``lhs`` and continuing until there are no more ``pair``s. * Added tests * Fixed test Fixed mistake in making assertion of ``1 +たす 2 +たす3 == 2+たす2+たす3`` * Style correction. * Update parser.rs Yet another attempt to make rustfmt happy.
1 parent 6f0d232 commit 86abfb4

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

‎calculator/src/parser.rs

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,22 @@ fn build_ast_from_expr(pair: pest::iterators::Pair<Rule>) -> Node {
3636
Rule::BinaryExpr => {
3737
let mut pair = pair.into_inner();
3838
let lhspair = pair.next().unwrap();
39-
let lhs = build_ast_from_term(lhspair);
40-
let op = pair.next().unwrap();
39+
let mutlhs = build_ast_from_term(lhspair);
40+
let mutop = pair.next().unwrap();
4141
let rhspair = pair.next().unwrap();
42-
let rhs = build_ast_from_term(rhspair);
43-
parse_binary_expr(op, lhs, rhs)
42+
let mut rhs = build_ast_from_term(rhspair);
43+
let mut retval = parse_binary_expr(op, lhs, rhs);
44+
loop {
45+
let pair_buf = pair.next();
46+
if pair_buf != None {
47+
op = pair_buf.unwrap();
48+
lhs = retval;
49+
rhs = build_ast_from_term(pair.next().unwrap());
50+
retval = parse_binary_expr(op, lhs, rhs);
51+
} else {
52+
return retval;
53+
}
54+
}
4455
}
4556
unknown => panic!("Unknown expr: {:?}", unknown),
4657
}
@@ -163,4 +174,20 @@ mod tests {
163174
test_expr("1 + 2 + 3 + 4", "1 + (2 + (3 + 4))");
164175
test_expr("1 + 2 + 3 - 4", "(1 + 2) + (3 - 4)");
165176
}
177+
178+
#[test]
179+
fn multiple_operators() {
180+
assert_eq!(
181+
parse("1+2+3").unwrap(),
182+
vec![Node::BinaryExpr {
183+
op: Operator::Plus,
184+
lhs: Box::new(Node::BinaryExpr {
185+
op: Operator::Plus,
186+
lhs: Box::new(Node::Int(1)),
187+
rhs: Box::new(Node::Int(2)),
188+
}),
189+
rhs: Box::new(Node::Int(3)),
190+
}]
191+
)
192+
}
166193
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /