about summary refs log tree commit diff
path: root/compiler
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2024-05-12 22:06:34 +0000
committerbors <bors@rust-lang.org>2024-05-12 22:06:34 +0000
commitecbe3fd550fccd2cba17ea7e86539bf3e0bfc618 (patch)
treec3fe72599d5318f82b14fe186bdf7a6b67935dcb /compiler
parentef0027897d2e9014766fb47dce9ddbb925d2f540 (diff)
parent94cc82c088b9301dc4dcf84ce127a64bbd77dddf (diff)
Auto merge of #125051 - dtolnay:printletelse, r=compiler-errors
Pretty-print let-else with added parenthesization when needed

Rustc used to produce invalid syntax for the following code, which is problematic because it means we cannot apply rustfmt to the output of `-Zunpretty=expanded`.

```rust
macro_rules! expr {
    ($e:expr) => { $e };
}

fn main() {
    let _ = expr!(loop {}) else { return; };
}
```

```console
$ rustc repro.rs -Zunpretty=expanded | rustfmt
error: `loop...else` loops are not supported
 --> <stdin>:9:29
  |
9 | fn main() { let _ = loop {} else { return; }; }
  |                     ----    ^^^^^^^^^^^^^^^^
  |                     |
  |                     `else` is attached to this loop
  |
  = note: consider moving this `else` clause to a separate `if` statement and use a `bool` variable to control if it should run
```
Diffstat (limited to 'compiler')
-rw-r--r--compiler/rustc_ast_pretty/src/pprust/state.rs6
1 files changed, 5 insertions, 1 deletions
diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs
index 2c176828c84..b7bdb2e14a6 100644
--- a/compiler/rustc_ast_pretty/src/pprust/state.rs
+++ b/compiler/rustc_ast_pretty/src/pprust/state.rs
@@ -1238,7 +1238,11 @@ impl<'a> State<'a> {
                 if let Some((init, els)) = loc.kind.init_else_opt() {
                     self.nbsp();
                     self.word_space("=");
-                    self.print_expr(init, FixupContext::default());
+                    self.print_expr_cond_paren(
+                        init,
+                        els.is_some() && classify::expr_trailing_brace(init).is_some(),
+                        FixupContext::default(),
+                    );
                     if let Some(els) = els {
                         self.cbox(INDENT_UNIT);
                         self.ibox(INDENT_UNIT);