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