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