Skip to content

Commit c0c6af7

Browse files
committed
Add operator precedence for pretty printer
Previously it just added parentheses in excess. e.g. ((1 + 2) + 3) + 4
1 parent c67a34b commit c0c6af7

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/libsyntax/print/pprust.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1555,6 +1555,21 @@ impl<'a> State<'a> {
15551555
self.pclose()
15561556
}
15571557

1558+
pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1559+
binop: ast::BinOp) -> bool {
1560+
match sub_expr.node {
1561+
ast::ExprBinary(ref sub_op, _, _) => {
1562+
if ast_util::operator_prec(sub_op.node) <
1563+
ast_util::operator_prec(binop.node) {
1564+
true
1565+
} else {
1566+
false
1567+
}
1568+
}
1569+
_ => true
1570+
}
1571+
}
1572+
15581573
pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
15591574
let needs_par = needs_parentheses(expr);
15601575
if needs_par {
@@ -1670,10 +1685,18 @@ impl<'a> State<'a> {
16701685
op: ast::BinOp,
16711686
lhs: &ast::Expr,
16721687
rhs: &ast::Expr) -> io::Result<()> {
1673-
try!(self.print_expr_maybe_paren(lhs));
1688+
if self.check_expr_bin_needs_paren(lhs, op) {
1689+
try!(self.print_expr_maybe_paren(lhs));
1690+
} else {
1691+
try!(self.print_expr(lhs));
1692+
}
16741693
try!(space(&mut self.s));
16751694
try!(self.word_space(ast_util::binop_to_string(op.node)));
1676-
self.print_expr_maybe_paren(rhs)
1695+
if self.check_expr_bin_needs_paren(rhs, op) {
1696+
self.print_expr_maybe_paren(rhs)
1697+
} else {
1698+
self.print_expr(rhs)
1699+
}
16771700
}
16781701

16791702
fn print_expr_unary(&mut self,

0 commit comments

Comments
 (0)