]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/higher.rs
Merge pull request #3303 from shssoichiro/3069-unnecessary-fold-pattern-guard
[rust.git] / clippy_lints / src / utils / higher.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 //! This module contains functions for retrieve the original AST from lowered
12 //! `hir`.
13
14 #![deny(clippy::missing_docs_in_private_items)]
15
16 use if_chain::if_chain;
17 use crate::rustc::{hir, ty};
18 use crate::rustc::lint::LateContext;
19 use crate::syntax::ast;
20 use crate::utils::{is_expn_of, match_def_path, match_qpath, opt_def_id, paths, resolve_node};
21
22 /// Convert a hir binary operator to the corresponding `ast` type.
23 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
24     match op {
25         hir::BinOpKind::Eq => ast::BinOpKind::Eq,
26         hir::BinOpKind::Ge => ast::BinOpKind::Ge,
27         hir::BinOpKind::Gt => ast::BinOpKind::Gt,
28         hir::BinOpKind::Le => ast::BinOpKind::Le,
29         hir::BinOpKind::Lt => ast::BinOpKind::Lt,
30         hir::BinOpKind::Ne => ast::BinOpKind::Ne,
31         hir::BinOpKind::Or => ast::BinOpKind::Or,
32         hir::BinOpKind::Add => ast::BinOpKind::Add,
33         hir::BinOpKind::And => ast::BinOpKind::And,
34         hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
35         hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
36         hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
37         hir::BinOpKind::Div => ast::BinOpKind::Div,
38         hir::BinOpKind::Mul => ast::BinOpKind::Mul,
39         hir::BinOpKind::Rem => ast::BinOpKind::Rem,
40         hir::BinOpKind::Shl => ast::BinOpKind::Shl,
41         hir::BinOpKind::Shr => ast::BinOpKind::Shr,
42         hir::BinOpKind::Sub => ast::BinOpKind::Sub,
43     }
44 }
45
46 /// Represent a range akin to `ast::ExprKind::Range`.
47 #[derive(Debug, Copy, Clone)]
48 pub struct Range<'a> {
49     /// The lower bound of the range, or `None` for ranges such as `..X`.
50     pub start: Option<&'a hir::Expr>,
51     /// The upper bound of the range, or `None` for ranges such as `X..`.
52     pub end: Option<&'a hir::Expr>,
53     /// Whether the interval is open or closed.
54     pub limits: ast::RangeLimits,
55 }
56
57 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
58 pub fn range<'a, 'b, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'b hir::Expr) -> Option<Range<'b>> {
59     /// Find the field named `name` in the field. Always return `Some` for
60     /// convenience.
61     fn get_field<'a>(name: &str, fields: &'a [hir::Field]) -> Option<&'a hir::Expr> {
62         let expr = &fields.iter().find(|field| field.ident.name == name)?.expr;
63
64         Some(expr)
65     }
66
67
68     let def_path = match cx.tables.expr_ty(expr).sty {
69         ty::Adt(def, _) => cx.tcx.def_path(def.did),
70         _ => return None,
71     };
72
73     // sanity checks for std::ops::RangeXXXX
74     if def_path.data.len() != 3 {
75         return None;
76     }
77     if def_path.data.get(0)?.data.as_interned_str() != "ops" {
78         return None;
79     }
80     if def_path.data.get(1)?.data.as_interned_str() != "range" {
81         return None;
82     }
83     let type_name = def_path.data.get(2)?.data.as_interned_str();
84     let range_types = [
85         "RangeFrom",
86         "RangeFull",
87         "RangeInclusive",
88         "Range",
89         "RangeTo",
90         "RangeToInclusive",
91     ];
92     if !range_types.contains(&&*type_name.as_str()) {
93         return None;
94     }
95
96     // The range syntax is expanded to literal paths starting with `core` or `std`
97     // depending on
98     // `#[no_std]`. Testing both instead of resolving the paths.
99
100     match expr.node {
101         hir::ExprKind::Path(ref path) => {
102             if match_qpath(path, &paths::RANGE_FULL_STD) || match_qpath(path, &paths::RANGE_FULL) {
103                 Some(Range {
104                     start: None,
105                     end: None,
106                     limits: ast::RangeLimits::HalfOpen,
107                 })
108             } else {
109                 None
110             }
111         },
112         hir::ExprKind::Call(ref path, ref args) => if let hir::ExprKind::Path(ref path) = path.node {
113             if match_qpath(path, &paths::RANGE_INCLUSIVE_STD_NEW) || match_qpath(path, &paths::RANGE_INCLUSIVE_NEW) {
114                 Some(Range {
115                     start: Some(&args[0]),
116                     end: Some(&args[1]),
117                     limits: ast::RangeLimits::Closed,
118                 })
119             } else {
120                 None
121             }
122         } else {
123             None
124         },
125         hir::ExprKind::Struct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD)
126             || match_qpath(path, &paths::RANGE_FROM)
127         {
128             Some(Range {
129                 start: Some(get_field("start", fields)?),
130                 end: None,
131                 limits: ast::RangeLimits::HalfOpen,
132             })
133         } else if match_qpath(path, &paths::RANGE_STD) || match_qpath(path, &paths::RANGE) {
134             Some(Range {
135                 start: Some(get_field("start", fields)?),
136                 end: Some(get_field("end", fields)?),
137                 limits: ast::RangeLimits::HalfOpen,
138             })
139         } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
140             Some(Range {
141                 start: None,
142                 end: Some(get_field("end", fields)?),
143                 limits: ast::RangeLimits::Closed,
144             })
145         } else if match_qpath(path, &paths::RANGE_TO_STD) || match_qpath(path, &paths::RANGE_TO) {
146             Some(Range {
147                 start: None,
148                 end: Some(get_field("end", fields)?),
149                 limits: ast::RangeLimits::HalfOpen,
150             })
151         } else {
152             None
153         },
154         _ => None,
155     }
156 }
157
158 /// Checks if a `let` decl is from a `for` loop desugaring.
159 pub fn is_from_for_desugar(decl: &hir::Decl) -> bool {
160     // This will detect plain for-loops without an actual variable binding:
161     //
162     // ```
163     // for x in some_vec {
164     //   // do stuff
165     // }
166     // ```
167     if_chain! {
168         if let hir::DeclKind::Local(ref loc) = decl.node;
169         if let Some(ref expr) = loc.init;
170         if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.node;
171         then {
172             return true;
173         }
174     }
175
176     // This detects a variable binding in for loop to avoid `let_unit_value`
177     // lint (see issue #1964).
178     //
179     // ```
180     // for _ in vec![()] {
181     //   // anything
182     // }
183     // ```
184     if_chain! {
185         if let hir::DeclKind::Local(ref loc) = decl.node;
186         if let hir::LocalSource::ForLoopDesugar = loc.source;
187         then {
188             return true;
189         }
190     }
191
192     false
193 }
194
195 /// Recover the essential nodes of a desugared for loop:
196 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
197 pub fn for_loop(expr: &hir::Expr) -> Option<(&hir::Pat, &hir::Expr, &hir::Expr)> {
198     if_chain! {
199         if let hir::ExprKind::Match(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.node;
200         if let hir::ExprKind::Call(_, ref iterargs) = iterexpr.node;
201         if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
202         if let hir::ExprKind::Loop(ref block, _, _) = arms[0].body.node;
203         if block.expr.is_none();
204         if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
205         if let hir::StmtKind::Decl(ref decl, _) = let_stmt.node;
206         if let hir::DeclKind::Local(ref decl) = decl.node;
207         if let hir::StmtKind::Expr(ref expr, _) = body.node;
208         then {
209             return Some((&*decl.pat, &iterargs[0], expr));
210         }
211     }
212     None
213 }
214
215 /// Represent the pre-expansion arguments of a `vec!` invocation.
216 pub enum VecArgs<'a> {
217     /// `vec![elem; len]`
218     Repeat(&'a hir::Expr, &'a hir::Expr),
219     /// `vec![a, b, c]`
220     Vec(&'a [hir::Expr]),
221 }
222
223 /// Returns the arguments of the `vec!` macro if this expression was expanded
224 /// from `vec!`.
225 pub fn vec_macro<'e>(cx: &LateContext<'_, '_>, expr: &'e hir::Expr) -> Option<VecArgs<'e>> {
226     if_chain! {
227         if let hir::ExprKind::Call(ref fun, ref args) = expr.node;
228         if let hir::ExprKind::Path(ref path) = fun.node;
229         if is_expn_of(fun.span, "vec").is_some();
230         if let Some(fun_def_id) = opt_def_id(resolve_node(cx, path, fun.hir_id));
231         then {
232             return if match_def_path(cx.tcx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
233                 // `vec![elem; size]` case
234                 Some(VecArgs::Repeat(&args[0], &args[1]))
235             }
236             else if match_def_path(cx.tcx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
237                 // `vec![a, b, c]` case
238                 if_chain! {
239                     if let hir::ExprKind::Box(ref boxed) = args[0].node;
240                     if let hir::ExprKind::Array(ref args) = boxed.node;
241                     then {
242                         return Some(VecArgs::Vec(&*args));
243                     }
244                 }
245
246                 None
247             }
248             else {
249                 None
250             };
251         }
252     }
253
254     None
255 }