Add operator precedence for pretty printer
Previously it just added parentheses in excess. e.g. ((1 + 2) + 3) + 4
This commit is contained in:
parent
c67a34b9e5
commit
c0c6af7f07
1 changed files with 25 additions and 2 deletions
|
@ -1555,6 +1555,21 @@ impl<'a> State<'a> {
|
||||||
self.pclose()
|
self.pclose()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
|
||||||
|
binop: ast::BinOp) -> bool {
|
||||||
|
match sub_expr.node {
|
||||||
|
ast::ExprBinary(ref sub_op, _, _) => {
|
||||||
|
if ast_util::operator_prec(sub_op.node) <
|
||||||
|
ast_util::operator_prec(binop.node) {
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
|
pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
|
||||||
let needs_par = needs_parentheses(expr);
|
let needs_par = needs_parentheses(expr);
|
||||||
if needs_par {
|
if needs_par {
|
||||||
|
@ -1670,10 +1685,18 @@ impl<'a> State<'a> {
|
||||||
op: ast::BinOp,
|
op: ast::BinOp,
|
||||||
lhs: &ast::Expr,
|
lhs: &ast::Expr,
|
||||||
rhs: &ast::Expr) -> io::Result<()> {
|
rhs: &ast::Expr) -> io::Result<()> {
|
||||||
try!(self.print_expr_maybe_paren(lhs));
|
if self.check_expr_bin_needs_paren(lhs, op) {
|
||||||
|
try!(self.print_expr_maybe_paren(lhs));
|
||||||
|
} else {
|
||||||
|
try!(self.print_expr(lhs));
|
||||||
|
}
|
||||||
try!(space(&mut self.s));
|
try!(space(&mut self.s));
|
||||||
try!(self.word_space(ast_util::binop_to_string(op.node)));
|
try!(self.word_space(ast_util::binop_to_string(op.node)));
|
||||||
self.print_expr_maybe_paren(rhs)
|
if self.check_expr_bin_needs_paren(rhs, op) {
|
||||||
|
self.print_expr_maybe_paren(rhs)
|
||||||
|
} else {
|
||||||
|
self.print_expr(rhs)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_expr_unary(&mut self,
|
fn print_expr_unary(&mut self,
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue