Skip to content

Commit 29b5058

Browse files
committed
Insert parentheses around binary operation with attribute
1 parent 6008f48 commit 29b5058

File tree

1 file changed

+37
-12
lines changed
  • compiler/rustc_ast_pretty/src/pprust/state

1 file changed

+37
-12
lines changed

compiler/rustc_ast_pretty/src/pprust/state/expr.rs

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -386,18 +386,43 @@ impl<'a> State<'a> {
386386

387387
let ib = self.ibox(INDENT_UNIT);
388388

389-
// The Match subexpression in `match x {} - 1` must be parenthesized if
390-
// it is the leftmost subexpression in a statement:
391-
//
392-
// (match x {}) - 1;
393-
//
394-
// But not otherwise:
395-
//
396-
// let _ = match x {} - 1;
397-
//
398-
// Same applies to a small set of other expression kinds which eagerly
399-
// terminate a statement which opens with them.
400-
let needs_par = fixup.would_cause_statement_boundary(expr);
389+
let needs_par = {
390+
// The Match subexpression in `match x {} - 1` must be parenthesized
391+
// if it is the leftmost subexpression in a statement:
392+
//
393+
// (match x {}) - 1;
394+
//
395+
// But not otherwise:
396+
//
397+
// let _ = match x {} - 1;
398+
//
399+
// Same applies to a small set of other expression kinds which
400+
// eagerly terminate a statement which opens with them.
401+
fixup.would_cause_statement_boundary(expr)
402+
} || {
403+
// If a binary operation ends up with an attribute, such as
404+
// resulting from the following macro expansion, then parentheses
405+
// are required so that the attribute encompasses the right
406+
// subexpression and not just the left one.
407+
//
408+
// #![feature(stmt_expr_attributes)]
409+
//
410+
// macro_rules! add_attr {
411+
// ($e:expr) => { #[attr] $e };
412+
// }
413+
//
414+
// let _ = add_attr!(1 + 1);
415+
//
416+
// We must pretty-print `#[attr] (1 + 1)` not `#[attr] 1 + 1`.
417+
!attrs.is_empty()
418+
&& matches!(
419+
expr.kind,
420+
ast::ExprKind::Binary(..)
421+
| ast::ExprKind::Cast(..)
422+
| ast::ExprKind::Assign(..)
423+
| ast::ExprKind::AssignOp(..)
424+
)
425+
};
401426
if needs_par {
402427
self.popen();
403428
fixup = FixupContext::default();

0 commit comments

Comments
 (0)