Skip to content

Commit

Permalink
Pretty print parens around casts on the LHS of '<'
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
harpocrates committed Nov 5, 2017
1 parent 59d4845 commit 45a0aa4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/librustc/hir/print.rs
Expand Up @@ -1253,6 +1253,15 @@ impl<'a> State<'a> {
Fixity::None => (prec + 1, prec + 1),
};

let left_prec = match (&lhs.node, op.node) {
// These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
// the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
// of `(x as i32) < ...`. We need to convince it _not_ to do that.
(&hir::ExprCast { .. }, hir::BinOp_::BiLt) |
(&hir::ExprCast { .. }, hir::BinOp_::BiShl) => parser::PREC_FORCE_PAREN,
_ => left_prec,
};

self.print_expr_maybe_paren(lhs, left_prec)?;
self.s.space()?;
self.word_space(op.node.as_str())?;
Expand Down
9 changes: 9 additions & 0 deletions src/libsyntax/print/pprust.rs
Expand Up @@ -1986,6 +1986,15 @@ impl<'a> State<'a> {
Fixity::None => (prec + 1, prec + 1),
};

let left_prec = match (&lhs.node, op.node) {
// These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
// the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
// of `(x as i32) < ...`. We need to convince it _not_ to do that.
(&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
(&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
_ => left_prec,
};

self.print_expr_maybe_paren(lhs, left_prec)?;
self.s.space()?;
self.word_space(op.node.to_string())?;
Expand Down

0 comments on commit 45a0aa4

Please sign in to comment.