]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unnested_or_patterns.rs
Rollup merge of #96557 - nbdd0121:const, r=oli-obk
[rust.git] / clippy_lints / src / unnested_or_patterns.rs
1 #![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
2
3 use clippy_utils::ast_utils::{eq_field_pat, eq_id, eq_maybe_qself, eq_pat, eq_path};
4 use clippy_utils::diagnostics::span_lint_and_then;
5 use clippy_utils::{meets_msrv, msrvs, over};
6 use rustc_ast::mut_visit::*;
7 use rustc_ast::ptr::P;
8 use rustc_ast::{self as ast, Mutability, Pat, PatKind, PatKind::*, DUMMY_NODE_ID};
9 use rustc_ast_pretty::pprust;
10 use rustc_errors::Applicability;
11 use rustc_lint::{EarlyContext, EarlyLintPass};
12 use rustc_semver::RustcVersion;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::DUMMY_SP;
15
16 use std::cell::Cell;
17 use std::mem;
18
19 declare_clippy_lint! {
20     /// ### What it does
21     /// Checks for unnested or-patterns, e.g., `Some(0) | Some(2)` and
22     /// suggests replacing the pattern with a nested one, `Some(0 | 2)`.
23     ///
24     /// Another way to think of this is that it rewrites patterns in
25     /// *disjunctive normal form (DNF)* into *conjunctive normal form (CNF)*.
26     ///
27     /// ### Why is this bad?
28     /// In the example above, `Some` is repeated, which unnecessarily complicates the pattern.
29     ///
30     /// ### Example
31     /// ```rust
32     /// fn main() {
33     ///     if let Some(0) | Some(2) = Some(0) {}
34     /// }
35     /// ```
36     /// Use instead:
37     /// ```rust
38     /// fn main() {
39     ///     if let Some(0 | 2) = Some(0) {}
40     /// }
41     /// ```
42     #[clippy::version = "1.46.0"]
43     pub UNNESTED_OR_PATTERNS,
44     pedantic,
45     "unnested or-patterns, e.g., `Foo(Bar) | Foo(Baz) instead of `Foo(Bar | Baz)`"
46 }
47
48 #[derive(Clone, Copy)]
49 pub struct UnnestedOrPatterns {
50     msrv: Option<RustcVersion>,
51 }
52
53 impl UnnestedOrPatterns {
54     #[must_use]
55     pub fn new(msrv: Option<RustcVersion>) -> Self {
56         Self { msrv }
57     }
58 }
59
60 impl_lint_pass!(UnnestedOrPatterns => [UNNESTED_OR_PATTERNS]);
61
62 impl EarlyLintPass for UnnestedOrPatterns {
63     fn check_arm(&mut self, cx: &EarlyContext<'_>, a: &ast::Arm) {
64         if meets_msrv(self.msrv.as_ref(), &msrvs::OR_PATTERNS) {
65             lint_unnested_or_patterns(cx, &a.pat);
66         }
67     }
68
69     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
70         if meets_msrv(self.msrv.as_ref(), &msrvs::OR_PATTERNS) {
71             if let ast::ExprKind::Let(pat, _, _) = &e.kind {
72                 lint_unnested_or_patterns(cx, pat);
73             }
74         }
75     }
76
77     fn check_param(&mut self, cx: &EarlyContext<'_>, p: &ast::Param) {
78         if meets_msrv(self.msrv.as_ref(), &msrvs::OR_PATTERNS) {
79             lint_unnested_or_patterns(cx, &p.pat);
80         }
81     }
82
83     fn check_local(&mut self, cx: &EarlyContext<'_>, l: &ast::Local) {
84         if meets_msrv(self.msrv.as_ref(), &msrvs::OR_PATTERNS) {
85             lint_unnested_or_patterns(cx, &l.pat);
86         }
87     }
88
89     extract_msrv_attr!(EarlyContext);
90 }
91
92 fn lint_unnested_or_patterns(cx: &EarlyContext<'_>, pat: &Pat) {
93     if let Ident(.., None) | Lit(_) | Wild | Path(..) | Range(..) | Rest | MacCall(_) = pat.kind {
94         // This is a leaf pattern, so cloning is unprofitable.
95         return;
96     }
97
98     let mut pat = P(pat.clone());
99
100     // Nix all the paren patterns everywhere so that they aren't in our way.
101     remove_all_parens(&mut pat);
102
103     // Transform all unnested or-patterns into nested ones, and if there were none, quit.
104     if !unnest_or_patterns(&mut pat) {
105         return;
106     }
107
108     span_lint_and_then(cx, UNNESTED_OR_PATTERNS, pat.span, "unnested or-patterns", |db| {
109         insert_necessary_parens(&mut pat);
110         db.span_suggestion_verbose(
111             pat.span,
112             "nest the patterns",
113             pprust::pat_to_string(&pat),
114             Applicability::MachineApplicable,
115         );
116     });
117 }
118
119 /// Remove all `(p)` patterns in `pat`.
120 fn remove_all_parens(pat: &mut P<Pat>) {
121     struct Visitor;
122     impl MutVisitor for Visitor {
123         fn visit_pat(&mut self, pat: &mut P<Pat>) {
124             noop_visit_pat(pat, self);
125             let inner = match &mut pat.kind {
126                 Paren(i) => mem::replace(&mut i.kind, Wild),
127                 _ => return,
128             };
129             pat.kind = inner;
130         }
131     }
132     Visitor.visit_pat(pat);
133 }
134
135 /// Insert parens where necessary according to Rust's precedence rules for patterns.
136 fn insert_necessary_parens(pat: &mut P<Pat>) {
137     struct Visitor;
138     impl MutVisitor for Visitor {
139         fn visit_pat(&mut self, pat: &mut P<Pat>) {
140             use ast::{BindingMode::*, Mutability::*};
141             noop_visit_pat(pat, self);
142             let target = match &mut pat.kind {
143                 // `i @ a | b`, `box a | b`, and `& mut? a | b`.
144                 Ident(.., Some(p)) | Box(p) | Ref(p, _) if matches!(&p.kind, Or(ps) if ps.len() > 1) => p,
145                 Ref(p, Not) if matches!(p.kind, Ident(ByValue(Mut), ..)) => p, // `&(mut x)`
146                 _ => return,
147             };
148             target.kind = Paren(P(take_pat(target)));
149         }
150     }
151     Visitor.visit_pat(pat);
152 }
153
154 /// Unnest or-patterns `p0 | ... | p1` in the pattern `pat`.
155 /// For example, this would transform `Some(0) | FOO | Some(2)` into `Some(0 | 2) | FOO`.
156 fn unnest_or_patterns(pat: &mut P<Pat>) -> bool {
157     struct Visitor {
158         changed: bool,
159     }
160     impl MutVisitor for Visitor {
161         fn visit_pat(&mut self, p: &mut P<Pat>) {
162             // This is a bottom up transformation, so recurse first.
163             noop_visit_pat(p, self);
164
165             // Don't have an or-pattern? Just quit early on.
166             let alternatives = match &mut p.kind {
167                 Or(ps) => ps,
168                 _ => return,
169             };
170
171             // Collapse or-patterns directly nested in or-patterns.
172             let mut idx = 0;
173             let mut this_level_changed = false;
174             while idx < alternatives.len() {
175                 let inner = if let Or(ps) = &mut alternatives[idx].kind {
176                     mem::take(ps)
177                 } else {
178                     idx += 1;
179                     continue;
180                 };
181                 this_level_changed = true;
182                 alternatives.splice(idx..=idx, inner);
183             }
184
185             // Focus on `p_n` and then try to transform all `p_i` where `i > n`.
186             let mut focus_idx = 0;
187             while focus_idx < alternatives.len() {
188                 this_level_changed |= transform_with_focus_on_idx(alternatives, focus_idx);
189                 focus_idx += 1;
190             }
191             self.changed |= this_level_changed;
192
193             // Deal with `Some(Some(0)) | Some(Some(1))`.
194             if this_level_changed {
195                 noop_visit_pat(p, self);
196             }
197         }
198     }
199
200     let mut visitor = Visitor { changed: false };
201     visitor.visit_pat(pat);
202     visitor.changed
203 }
204
205 /// Match `$scrutinee` against `$pat` and extract `$then` from it.
206 /// Panics if there is no match.
207 macro_rules! always_pat {
208     ($scrutinee:expr, $pat:pat => $then:expr) => {
209         match $scrutinee {
210             $pat => $then,
211             _ => unreachable!(),
212         }
213     };
214 }
215
216 /// Focus on `focus_idx` in `alternatives`,
217 /// attempting to extend it with elements of the same constructor `C`
218 /// in `alternatives[focus_idx + 1..]`.
219 fn transform_with_focus_on_idx(alternatives: &mut Vec<P<Pat>>, focus_idx: usize) -> bool {
220     // Extract the kind; we'll need to make some changes in it.
221     let mut focus_kind = mem::replace(&mut alternatives[focus_idx].kind, PatKind::Wild);
222     // We'll focus on `alternatives[focus_idx]`,
223     // so we're draining from `alternatives[focus_idx + 1..]`.
224     let start = focus_idx + 1;
225
226     // We're trying to find whatever kind (~"constructor") we found in `alternatives[start..]`.
227     let changed = match &mut focus_kind {
228         // These pattern forms are "leafs" and do not have sub-patterns.
229         // Therefore they are not some form of constructor `C`,
230         // with which a pattern `C(p_0)` may be formed,
231         // which we would want to join with other `C(p_j)`s.
232         Ident(.., None) | Lit(_) | Wild | Path(..) | Range(..) | Rest | MacCall(_)
233         // Skip immutable refs, as grouping them saves few characters,
234         // and almost always requires adding parens (increasing noisiness).
235         // In the case of only two patterns, replacement adds net characters.
236         | Ref(_, Mutability::Not)
237         // Dealt with elsewhere.
238         | Or(_) | Paren(_) => false,
239         // Transform `box x | ... | box y` into `box (x | y)`.
240         //
241         // The cases below until `Slice(...)` deal with *singleton* products.
242         // These patterns have the shape `C(p)`, and not e.g., `C(p0, ..., pn)`.
243         Box(target) => extend_with_matching(
244             target, start, alternatives,
245             |k| matches!(k, Box(_)),
246             |k| always_pat!(k, Box(p) => p),
247         ),
248         // Transform `&mut x | ... | &mut y` into `&mut (x | y)`.
249         Ref(target, Mutability::Mut) => extend_with_matching(
250             target, start, alternatives,
251             |k| matches!(k, Ref(_, Mutability::Mut)),
252             |k| always_pat!(k, Ref(p, _) => p),
253         ),
254         // Transform `b @ p0 | ... b @ p1` into `b @ (p0 | p1)`.
255         Ident(b1, i1, Some(target)) => extend_with_matching(
256             target, start, alternatives,
257             // Binding names must match.
258             |k| matches!(k, Ident(b2, i2, Some(_)) if b1 == b2 && eq_id(*i1, *i2)),
259             |k| always_pat!(k, Ident(_, _, Some(p)) => p),
260         ),
261         // Transform `[pre, x, post] | ... | [pre, y, post]` into `[pre, x | y, post]`.
262         Slice(ps1) => extend_with_matching_product(
263             ps1, start, alternatives,
264             |k, ps1, idx| matches!(k, Slice(ps2) if eq_pre_post(ps1, ps2, idx)),
265             |k| always_pat!(k, Slice(ps) => ps),
266         ),
267         // Transform `(pre, x, post) | ... | (pre, y, post)` into `(pre, x | y, post)`.
268         Tuple(ps1) => extend_with_matching_product(
269             ps1, start, alternatives,
270             |k, ps1, idx| matches!(k, Tuple(ps2) if eq_pre_post(ps1, ps2, idx)),
271             |k| always_pat!(k, Tuple(ps) => ps),
272         ),
273         // Transform `S(pre, x, post) | ... | S(pre, y, post)` into `S(pre, x | y, post)`.
274         TupleStruct(qself1, path1, ps1) => extend_with_matching_product(
275             ps1, start, alternatives,
276             |k, ps1, idx| matches!(
277                 k,
278                 TupleStruct(qself2, path2, ps2)
279                     if eq_maybe_qself(qself1, qself2) && eq_path(path1, path2) && eq_pre_post(ps1, ps2, idx)
280             ),
281             |k| always_pat!(k, TupleStruct(_, _, ps) => ps),
282         ),
283         // Transform a record pattern `S { fp_0, ..., fp_n }`.
284         Struct(qself1, path1, fps1, rest1) => extend_with_struct_pat(qself1, path1, fps1, *rest1, start, alternatives),
285     };
286
287     alternatives[focus_idx].kind = focus_kind;
288     changed
289 }
290
291 /// Here we focusing on a record pattern `S { fp_0, ..., fp_n }`.
292 /// In particular, for a record pattern, the order in which the field patterns is irrelevant.
293 /// So when we fixate on some `ident_k: pat_k`, we try to find `ident_k` in the other pattern
294 /// and check that all `fp_i` where `i ∈ ((0...n) \ k)` between two patterns are equal.
295 fn extend_with_struct_pat(
296     qself1: &Option<ast::QSelf>,
297     path1: &ast::Path,
298     fps1: &mut [ast::PatField],
299     rest1: bool,
300     start: usize,
301     alternatives: &mut Vec<P<Pat>>,
302 ) -> bool {
303     (0..fps1.len()).any(|idx| {
304         let pos_in_2 = Cell::new(None); // The element `k`.
305         let tail_or = drain_matching(
306             start,
307             alternatives,
308             |k| {
309                 matches!(k, Struct(qself2, path2, fps2, rest2)
310                 if rest1 == *rest2 // If one struct pattern has `..` so must the other.
311                 && eq_maybe_qself(qself1, qself2)
312                 && eq_path(path1, path2)
313                 && fps1.len() == fps2.len()
314                 && fps1.iter().enumerate().all(|(idx_1, fp1)| {
315                     if idx_1 == idx {
316                         // In the case of `k`, we merely require identical field names
317                         // so that we will transform into `ident_k: p1_k | p2_k`.
318                         let pos = fps2.iter().position(|fp2| eq_id(fp1.ident, fp2.ident));
319                         pos_in_2.set(pos);
320                         pos.is_some()
321                     } else {
322                         fps2.iter().any(|fp2| eq_field_pat(fp1, fp2))
323                     }
324                 }))
325             },
326             // Extract `p2_k`.
327             |k| always_pat!(k, Struct(_, _, mut fps, _) => fps.swap_remove(pos_in_2.take().unwrap()).pat),
328         );
329         extend_with_tail_or(&mut fps1[idx].pat, tail_or)
330     })
331 }
332
333 /// Like `extend_with_matching` but for products with > 1 factor, e.g., `C(p_0, ..., p_n)`.
334 /// Here, the idea is that we fixate on some `p_k` in `C`,
335 /// allowing it to vary between two `targets` and `ps2` (returned by `extract`),
336 /// while also requiring `ps1[..n] ~ ps2[..n]` (pre) and `ps1[n + 1..] ~ ps2[n + 1..]` (post),
337 /// where `~` denotes semantic equality.
338 fn extend_with_matching_product(
339     targets: &mut [P<Pat>],
340     start: usize,
341     alternatives: &mut Vec<P<Pat>>,
342     predicate: impl Fn(&PatKind, &[P<Pat>], usize) -> bool,
343     extract: impl Fn(PatKind) -> Vec<P<Pat>>,
344 ) -> bool {
345     (0..targets.len()).any(|idx| {
346         let tail_or = drain_matching(
347             start,
348             alternatives,
349             |k| predicate(k, targets, idx),
350             |k| extract(k).swap_remove(idx),
351         );
352         extend_with_tail_or(&mut targets[idx], tail_or)
353     })
354 }
355
356 /// Extract the pattern from the given one and replace it with `Wild`.
357 /// This is meant for temporarily swapping out the pattern for manipulation.
358 fn take_pat(from: &mut Pat) -> Pat {
359     let dummy = Pat {
360         id: DUMMY_NODE_ID,
361         kind: Wild,
362         span: DUMMY_SP,
363         tokens: None,
364     };
365     mem::replace(from, dummy)
366 }
367
368 /// Extend `target` as an or-pattern with the alternatives
369 /// in `tail_or` if there are any and return if there were.
370 fn extend_with_tail_or(target: &mut Pat, tail_or: Vec<P<Pat>>) -> bool {
371     fn extend(target: &mut Pat, mut tail_or: Vec<P<Pat>>) {
372         match target {
373             // On an existing or-pattern in the target, append to it.
374             Pat { kind: Or(ps), .. } => ps.append(&mut tail_or),
375             // Otherwise convert the target to an or-pattern.
376             target => {
377                 let mut init_or = vec![P(take_pat(target))];
378                 init_or.append(&mut tail_or);
379                 target.kind = Or(init_or);
380             },
381         }
382     }
383
384     let changed = !tail_or.is_empty();
385     if changed {
386         // Extend the target.
387         extend(target, tail_or);
388     }
389     changed
390 }
391
392 // Extract all inner patterns in `alternatives` matching our `predicate`.
393 // Only elements beginning with `start` are considered for extraction.
394 fn drain_matching(
395     start: usize,
396     alternatives: &mut Vec<P<Pat>>,
397     predicate: impl Fn(&PatKind) -> bool,
398     extract: impl Fn(PatKind) -> P<Pat>,
399 ) -> Vec<P<Pat>> {
400     let mut tail_or = vec![];
401     let mut idx = 0;
402     for pat in alternatives.drain_filter(|p| {
403         // Check if we should extract, but only if `idx >= start`.
404         idx += 1;
405         idx > start && predicate(&p.kind)
406     }) {
407         tail_or.push(extract(pat.into_inner().kind));
408     }
409     tail_or
410 }
411
412 fn extend_with_matching(
413     target: &mut Pat,
414     start: usize,
415     alternatives: &mut Vec<P<Pat>>,
416     predicate: impl Fn(&PatKind) -> bool,
417     extract: impl Fn(PatKind) -> P<Pat>,
418 ) -> bool {
419     extend_with_tail_or(target, drain_matching(start, alternatives, predicate, extract))
420 }
421
422 /// Are the patterns in `ps1` and `ps2` equal save for `ps1[idx]` compared to `ps2[idx]`?
423 fn eq_pre_post(ps1: &[P<Pat>], ps2: &[P<Pat>], idx: usize) -> bool {
424     ps1.len() == ps2.len()
425         && ps1[idx].is_rest() == ps2[idx].is_rest() // Avoid `[x, ..] | [x, 0]` => `[x, .. | 0]`.
426         && over(&ps1[..idx], &ps2[..idx], |l, r| eq_pat(l, r))
427         && over(&ps1[idx + 1..], &ps2[idx + 1..], |l, r| eq_pat(l, r))
428 }