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