Skip to content

Commit 45a0aa4

Browse files
committed
Pretty print parens around casts on the LHS of '<'
When pretty printing a cast expression occuring on the LHS of a '<' or '<<' expression, we should add parens around the cast. Otherwise, the '<'/'<<' gets interpreted as the beginning of the generics for the type on the RHS of the cast.
1 parent 59d4845 commit 45a0aa4

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/librustc/hir/print.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1253,6 +1253,15 @@ impl<'a> State<'a> {
12531253
Fixity::None => (prec + 1, prec + 1),
12541254
};
12551255

1256+
let left_prec = match (&lhs.node, op.node) {
1257+
// These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1258+
// the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1259+
// of `(x as i32) < ...`. We need to convince it _not_ to do that.
1260+
(&hir::ExprCast { .. }, hir::BinOp_::BiLt) |
1261+
(&hir::ExprCast { .. }, hir::BinOp_::BiShl) => parser::PREC_FORCE_PAREN,
1262+
_ => left_prec,
1263+
};
1264+
12561265
self.print_expr_maybe_paren(lhs, left_prec)?;
12571266
self.s.space()?;
12581267
self.word_space(op.node.as_str())?;

src/libsyntax/print/pprust.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1986,6 +1986,15 @@ impl<'a> State<'a> {
19861986
Fixity::None => (prec + 1, prec + 1),
19871987
};
19881988

1989+
let left_prec = match (&lhs.node, op.node) {
1990+
// These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1991+
// the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1992+
// of `(x as i32) < ...`. We need to convince it _not_ to do that.
1993+
(&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1994+
(&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1995+
_ => left_prec,
1996+
};
1997+
19891998
self.print_expr_maybe_paren(lhs, left_prec)?;
19901999
self.s.space()?;
19912000
self.word_space(op.node.to_string())?;

0 commit comments

Comments
 (0)