Skip to content

Fix expressions with multiple operators. #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 21, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions calculator/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,22 @@ fn build_ast_from_expr(pair: pest::iterators::Pair<Rule>) -> Node {
Rule::BinaryExpr => {
let mut pair = pair.into_inner();
let lhspair = pair.next().unwrap();
let lhs = build_ast_from_term(lhspair);
let op = pair.next().unwrap();
let mut lhs = build_ast_from_term(lhspair);
let mut op = pair.next().unwrap();
let rhspair = pair.next().unwrap();
let rhs = build_ast_from_term(rhspair);
parse_binary_expr(op, lhs, rhs)
let mut rhs = build_ast_from_term(rhspair);
let mut retval = parse_binary_expr(op, lhs, rhs);
loop {
let pair_buf = pair.next();
if pair_buf != None {
op = pair_buf.unwrap();
lhs = retval;
rhs = build_ast_from_term(pair.next().unwrap());
retval = parse_binary_expr(op, lhs, rhs);
} else {
return retval;
}
}
}
unknown => panic!("Unknown expr: {:?}", unknown),
}
Expand Down Expand Up @@ -163,4 +174,20 @@ mod tests {
test_expr("1 + 2 + 3 + 4", "1 + (2 + (3 + 4))");
test_expr("1 + 2 + 3 - 4", "(1 + 2) + (3 - 4)");
}

#[test]
fn multiple_operators() {
assert_eq!(
parse("1+2+3").unwrap(),
vec![Node::BinaryExpr {
op: Operator::Plus,
lhs: Box::new(Node::BinaryExpr {
op: Operator::Plus,
lhs: Box::new(Node::Int(1)),
rhs: Box::new(Node::Int(2)),
}),
rhs: Box::new(Node::Int(3)),
}]
)
}
}