Skip to content

Commit 8f1b0aa

Browse files
committed
Auto merge of #27613 - GSam:binop, r=nrc
In the case where there are no paren in the AST, the pretty printer doesn't correctly print binary operations where precedence is concerned. Parenthesis may be missing due to some kind of expansion or manipulation of the AST. Example: Pretty printer prints Expr(*, Expr(+, 1, 1), 2) as 1 + 1 * 2, as opposed to (1 + 1) * 2 r? @nrc
2 parents b1d07bb + 22baa46 commit 8f1b0aa

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/libsyntax/print/pprust.rs

Lines changed: 30 additions & 3 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(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(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,
@@ -1730,7 +1753,11 @@ impl<'a> State<'a> {
17301753
try!(self.print_literal(&**lit));
17311754
}
17321755
ast::ExprCast(ref expr, ref ty) => {
1733-
try!(self.print_expr(&**expr));
1756+
if let ast::ExprCast(..) = expr.node {
1757+
try!(self.print_expr(&**expr));
1758+
} else {
1759+
try!(self.print_expr_maybe_paren(&**expr));
1760+
}
17341761
try!(space(&mut self.s));
17351762
try!(self.word_space("as"));
17361763
try!(self.print_type(&**ty));

0 commit comments

Comments
 (0)