Skip to content

Commit fe792d9

Browse files
committed
Auto merge of #10809 - nyurik:match-unsafe, r=Jarcho
Fix missing block for unsafe code If a block is declared as unsafe, it needs an extra layer of curly braces around it. Fixes #10808 This code adds handling for `UnsafeSource::UserProvided` block, i.e. `unsafe { ... }`. Note that we do not handle the `UnsafeSource::CompilerGenerated` as it seems to not be possible to generate that with the user code (?), or at least doesn't seem to be needed to be handled explicitly. There is an issue with this code: it does not add an extra indentation for the unsafe blocks. I think this is a relatively minor concern for such an edge case, and should probably be done by a separate PR (fixing compile bug is more important than getting styling perfect especially when `rustfmt` will fix it anyway) ```rust // original code unsafe { ... } // code that is now generated by this PR { unsafe { ... } } // what we would ideally like to get { unsafe { ... } } ``` changelog: [`single_match`](https://rust-lang.github.io/rust-clippy/master/#single_match): Fix suggestion for `unsafe` blocks
2 parents ec2f2d5 + ed935de commit fe792d9

7 files changed

+640
-10
lines changed

clippy_utils/src/source.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
use rustc_data_structures::sync::Lrc;
66
use rustc_errors::Applicability;
7-
use rustc_hir::{Expr, ExprKind};
7+
use rustc_hir::{BlockCheckMode, Expr, ExprKind, UnsafeSource};
88
use rustc_lint::{LateContext, LintContext};
99
use rustc_session::Session;
1010
use rustc_span::source_map::{original_sp, SourceMap};
@@ -71,11 +71,16 @@ pub fn expr_block<T: LintContext>(
7171
app: &mut Applicability,
7272
) -> String {
7373
let (code, from_macro) = snippet_block_with_context(cx, expr.span, outer, default, indent_relative_to, app);
74-
if from_macro {
75-
format!("{{ {code} }}")
76-
} else if let ExprKind::Block(_, _) = expr.kind {
74+
if !from_macro &&
75+
let ExprKind::Block(block, _) = expr.kind &&
76+
block.rules != BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
77+
{
7778
format!("{code}")
7879
} else {
80+
// FIXME: add extra indent for the unsafe blocks:
81+
// original code: unsafe { ... }
82+
// result code: { unsafe { ... } }
83+
// desired code: {\n unsafe { ... }\n}
7984
format!("{{ {code} }}")
8085
}
8186
}

tests/ui/single_match.fixed

+209
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
//@run-rustfix
2+
#![warn(clippy::single_match)]
3+
#![allow(unused, clippy::uninlined_format_args, clippy::redundant_pattern_matching)]
4+
fn dummy() {}
5+
6+
fn single_match() {
7+
let x = Some(1u8);
8+
9+
if let Some(y) = x {
10+
println!("{:?}", y);
11+
};
12+
13+
let x = Some(1u8);
14+
if let Some(y) = x { println!("{:?}", y) }
15+
16+
let z = (1u8, 1u8);
17+
if let (2..=3, 7..=9) = z { dummy() };
18+
19+
// Not linted (pattern guards used)
20+
match x {
21+
Some(y) if y == 0 => println!("{:?}", y),
22+
_ => (),
23+
}
24+
25+
// Not linted (no block with statements in the single arm)
26+
match z {
27+
(2..=3, 7..=9) => println!("{:?}", z),
28+
_ => println!("nope"),
29+
}
30+
}
31+
32+
enum Foo {
33+
Bar,
34+
Baz(u8),
35+
}
36+
use std::borrow::Cow;
37+
use Foo::*;
38+
39+
fn single_match_know_enum() {
40+
let x = Some(1u8);
41+
let y: Result<_, i8> = Ok(1i8);
42+
43+
if let Some(y) = x { dummy() };
44+
45+
if let Ok(y) = y { dummy() };
46+
47+
let c = Cow::Borrowed("");
48+
49+
if let Cow::Borrowed(..) = c { dummy() };
50+
51+
let z = Foo::Bar;
52+
// no warning
53+
match z {
54+
Bar => println!("42"),
55+
Baz(_) => (),
56+
}
57+
58+
match z {
59+
Baz(_) => println!("42"),
60+
Bar => (),
61+
}
62+
}
63+
64+
// issue #173
65+
fn if_suggestion() {
66+
let x = "test";
67+
if x == "test" { println!() }
68+
69+
#[derive(PartialEq, Eq)]
70+
enum Foo {
71+
A,
72+
B,
73+
C(u32),
74+
}
75+
76+
let x = Foo::A;
77+
if x == Foo::A { println!() }
78+
79+
const FOO_C: Foo = Foo::C(0);
80+
if x == FOO_C { println!() }
81+
82+
if x == Foo::A { println!() }
83+
84+
let x = &x;
85+
if x == &Foo::A { println!() }
86+
87+
enum Bar {
88+
A,
89+
B,
90+
}
91+
impl PartialEq for Bar {
92+
fn eq(&self, rhs: &Self) -> bool {
93+
matches!((self, rhs), (Self::A, Self::A) | (Self::B, Self::B))
94+
}
95+
}
96+
impl Eq for Bar {}
97+
98+
let x = Bar::A;
99+
if let Bar::A = x { println!() }
100+
101+
// issue #7038
102+
struct X;
103+
let x = Some(X);
104+
if let None = x { println!() };
105+
}
106+
107+
// See: issue #8282
108+
fn ranges() {
109+
enum E {
110+
V,
111+
}
112+
let x = (Some(E::V), Some(42));
113+
114+
// Don't lint, because the `E` enum can be extended with additional fields later. Thus, the
115+
// proposed replacement to `if let Some(E::V)` may hide non-exhaustive warnings that appeared
116+
// because of `match` construction.
117+
match x {
118+
(Some(E::V), _) => {},
119+
(None, _) => {},
120+
}
121+
122+
// lint
123+
if let (Some(_), _) = x {}
124+
125+
// lint
126+
if let (Some(E::V), _) = x { todo!() }
127+
128+
// lint
129+
if let (.., Some(E::V), _) = (Some(42), Some(E::V), Some(42)) {}
130+
131+
// Don't lint, see above.
132+
match (Some(E::V), Some(E::V), Some(E::V)) {
133+
(.., Some(E::V), _) => {},
134+
(.., None, _) => {},
135+
}
136+
137+
// Don't lint, see above.
138+
match (Some(E::V), Some(E::V), Some(E::V)) {
139+
(Some(E::V), ..) => {},
140+
(None, ..) => {},
141+
}
142+
143+
// Don't lint, see above.
144+
match (Some(E::V), Some(E::V), Some(E::V)) {
145+
(_, Some(E::V), ..) => {},
146+
(_, None, ..) => {},
147+
}
148+
}
149+
150+
fn skip_type_aliases() {
151+
enum OptionEx {
152+
Some(i32),
153+
None,
154+
}
155+
enum ResultEx {
156+
Err(i32),
157+
Ok(i32),
158+
}
159+
160+
use OptionEx::{None, Some};
161+
use ResultEx::{Err, Ok};
162+
163+
// don't lint
164+
match Err(42) {
165+
Ok(_) => dummy(),
166+
Err(_) => (),
167+
};
168+
169+
// don't lint
170+
match Some(1i32) {
171+
Some(_) => dummy(),
172+
None => (),
173+
};
174+
}
175+
176+
macro_rules! single_match {
177+
($num:literal) => {
178+
match $num {
179+
15 => println!("15"),
180+
_ => (),
181+
}
182+
};
183+
}
184+
185+
fn main() {
186+
single_match!(5);
187+
188+
// Don't lint
189+
let _ = match Some(0) {
190+
#[cfg(feature = "foo")]
191+
Some(10) => 11,
192+
Some(x) => x,
193+
_ => 0,
194+
};
195+
}
196+
197+
fn issue_10808(bar: Option<i32>) {
198+
if let Some(v) = bar { unsafe {
199+
let r = &v as *const i32;
200+
println!("{}", *r);
201+
} }
202+
203+
if let Some(v) = bar {
204+
unsafe {
205+
let r = &v as *const i32;
206+
println!("{}", *r);
207+
}
208+
}
209+
}

tests/ui/single_match.rs

+23-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
//@run-rustfix
12
#![warn(clippy::single_match)]
2-
#![allow(clippy::uninlined_format_args)]
3-
3+
#![allow(unused, clippy::uninlined_format_args, clippy::redundant_pattern_matching)]
44
fn dummy() {}
55

66
fn single_match() {
@@ -244,3 +244,24 @@ fn main() {
244244
_ => 0,
245245
};
246246
}
247+
248+
fn issue_10808(bar: Option<i32>) {
249+
match bar {
250+
Some(v) => unsafe {
251+
let r = &v as *const i32;
252+
println!("{}", *r);
253+
},
254+
_ => {},
255+
}
256+
257+
match bar {
258+
#[rustfmt::skip]
259+
Some(v) => {
260+
unsafe {
261+
let r = &v as *const i32;
262+
println!("{}", *r);
263+
}
264+
},
265+
_ => {},
266+
}
267+
}

tests/ui/single_match.stderr

+43-1
Original file line numberDiff line numberDiff line change
@@ -155,5 +155,47 @@ LL | | (..) => {},
155155
LL | | }
156156
| |_____^ help: try this: `if let (.., Some(E::V), _) = (Some(42), Some(E::V), Some(42)) {}`
157157

158-
error: aborting due to 16 previous errors
158+
error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`
159+
--> $DIR/single_match.rs:249:5
160+
|
161+
LL | / match bar {
162+
LL | | Some(v) => unsafe {
163+
LL | | let r = &v as *const i32;
164+
LL | | println!("{}", *r);
165+
LL | | },
166+
LL | | _ => {},
167+
LL | | }
168+
| |_____^
169+
|
170+
help: try this
171+
|
172+
LL ~ if let Some(v) = bar { unsafe {
173+
LL + let r = &v as *const i32;
174+
LL + println!("{}", *r);
175+
LL + } }
176+
|
177+
178+
error: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`
179+
--> $DIR/single_match.rs:257:5
180+
|
181+
LL | / match bar {
182+
LL | | #[rustfmt::skip]
183+
LL | | Some(v) => {
184+
LL | | unsafe {
185+
... |
186+
LL | | _ => {},
187+
LL | | }
188+
| |_____^
189+
|
190+
help: try this
191+
|
192+
LL ~ if let Some(v) = bar {
193+
LL + unsafe {
194+
LL + let r = &v as *const i32;
195+
LL + println!("{}", *r);
196+
LL + }
197+
LL + }
198+
|
199+
200+
error: aborting due to 18 previous errors
159201

0 commit comments

Comments
 (0)