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