Skip to content

Commit 888365d

Browse files
authored
Don't use labeled block as top-level blocks (#14102)
Labeled blocks cannot be used as-is in the "then" or "else" part of an `if` expression. They must be enclosed in an anonymous block. Fix #14099 changelog: [`match_bool`]: fix suggestion when the rewritten block has a label
2 parents 7cda242 + b827529 commit 888365d

File tree

4 files changed

+38
-3
lines changed

4 files changed

+38
-3
lines changed

clippy_utils/src/source.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ impl SourceFileRange {
293293
}
294294
}
295295

296-
/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
296+
/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block` with no label.
297297
pub fn expr_block(
298298
sess: &impl HasSession,
299299
expr: &Expr<'_>,
@@ -304,7 +304,7 @@ pub fn expr_block(
304304
) -> String {
305305
let (code, from_macro) = snippet_block_with_context(sess, expr.span, outer, default, indent_relative_to, app);
306306
if !from_macro
307-
&& let ExprKind::Block(block, _) = expr.kind
307+
&& let ExprKind::Block(block, None) = expr.kind
308308
&& block.rules != BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
309309
{
310310
format!("{code}")

tests/ui/match_bool.fixed

+6
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,10 @@ fn match_bool() {
5555
if !(!test && option == 5) { println!("Hello") };
5656
}
5757

58+
fn issue14099() {
59+
if true { 'a: {
60+
break 'a;
61+
} }
62+
}
63+
5864
fn main() {}

tests/ui/match_bool.rs

+10
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,14 @@ fn match_bool() {
103103
};
104104
}
105105

106+
fn issue14099() {
107+
match true {
108+
//~^ ERROR: `match` on a boolean expression
109+
true => 'a: {
110+
break 'a;
111+
},
112+
_ => (),
113+
}
114+
}
115+
106116
fn main() {}

tests/ui/match_bool.stderr

+20-1
Original file line numberDiff line numberDiff line change
@@ -164,5 +164,24 @@ LL | | _ => println!("Hello"),
164164
LL | | };
165165
| |_____^ help: consider using an `if`/`else` expression: `if !(!test && option == 5) { println!("Hello") }`
166166

167-
error: aborting due to 12 previous errors
167+
error: `match` on a boolean expression
168+
--> tests/ui/match_bool.rs:107:5
169+
|
170+
LL | / match true {
171+
LL | |
172+
LL | | true => 'a: {
173+
LL | | break 'a;
174+
LL | | },
175+
LL | | _ => (),
176+
LL | | }
177+
| |_____^
178+
|
179+
help: consider using an `if`/`else` expression
180+
|
181+
LL ~ if true { 'a: {
182+
LL + break 'a;
183+
LL + } }
184+
|
185+
186+
error: aborting due to 13 previous errors
168187

0 commit comments

Comments
 (0)