]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/higher.rs
Merge pull request #2821 from mati865/rust-2018-migration
[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(missing_docs_in_private_items)]
5
6 use rustc::{hir, ty};
7 use rustc::lint::LateContext;
8 use syntax::ast;
9 use crate::utils::{is_expn_of, match_def_path, match_qpath, opt_def_id, paths, resolve_node};
10
11 /// Convert a hir binary operator to the corresponding `ast` type.
12 pub fn binop(op: hir::BinOp_) -> ast::BinOpKind {
13     match op {
14         hir::BiEq => ast::BinOpKind::Eq,
15         hir::BiGe => ast::BinOpKind::Ge,
16         hir::BiGt => ast::BinOpKind::Gt,
17         hir::BiLe => ast::BinOpKind::Le,
18         hir::BiLt => ast::BinOpKind::Lt,
19         hir::BiNe => ast::BinOpKind::Ne,
20         hir::BiOr => ast::BinOpKind::Or,
21         hir::BiAdd => ast::BinOpKind::Add,
22         hir::BiAnd => ast::BinOpKind::And,
23         hir::BiBitAnd => ast::BinOpKind::BitAnd,
24         hir::BiBitOr => ast::BinOpKind::BitOr,
25         hir::BiBitXor => ast::BinOpKind::BitXor,
26         hir::BiDiv => ast::BinOpKind::Div,
27         hir::BiMul => ast::BinOpKind::Mul,
28         hir::BiRem => ast::BinOpKind::Rem,
29         hir::BiShl => ast::BinOpKind::Shl,
30         hir::BiShr => ast::BinOpKind::Shr,
31         hir::BiSub => ast::BinOpKind::Sub,
32     }
33 }
34
35 /// Represent a range akin to `ast::ExprKind::Range`.
36 #[derive(Debug, Copy, Clone)]
37 pub struct Range<'a> {
38     /// The lower bound of the range, or `None` for ranges such as `..X`.
39     pub start: Option<&'a hir::Expr>,
40     /// The upper bound of the range, or `None` for ranges such as `X..`.
41     pub end: Option<&'a hir::Expr>,
42     /// Whether the interval is open or closed.
43     pub limits: ast::RangeLimits,
44 }
45
46 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
47 pub fn range<'a, 'b, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'b hir::Expr) -> Option<Range<'b>> {
48
49     let def_path = match cx.tables.expr_ty(expr).sty {
50         ty::TyAdt(def, _) => cx.tcx.def_path(def.did),
51         _ => return None,
52     };
53
54     // sanity checks for std::ops::RangeXXXX
55     if def_path.data.len() != 3 {
56         return None;
57     }
58     if def_path.data.get(0)?.data.as_interned_str() != "ops" {
59         return None;
60     }
61     if def_path.data.get(1)?.data.as_interned_str() != "range" {
62         return None;
63     }
64     let type_name = def_path.data.get(2)?.data.as_interned_str();
65     let range_types = [
66         "RangeFrom",
67         "RangeFull",
68         "RangeInclusive",
69         "Range",
70         "RangeTo",
71         "RangeToInclusive",
72     ];
73     if !range_types.contains(&&*type_name.as_str()) {
74         return None;
75     }
76
77     /// Find the field named `name` in the field. Always return `Some` for
78     /// convenience.
79     fn get_field<'a>(name: &str, fields: &'a [hir::Field]) -> Option<&'a hir::Expr> {
80         let expr = &fields.iter().find(|field| field.ident.name == name)?.expr;
81
82         Some(expr)
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::ExprPath(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::ExprCall(ref path, ref args) => if let hir::ExprPath(ref path) = path.node {
102             if match_qpath(path, &paths::RANGE_INCLUSIVE_STD_NEW) || match_qpath(path, &paths::RANGE_INCLUSIVE_NEW) {
103                 Some(Range {
104                     start: Some(&args[0]),
105                     end: Some(&args[1]),
106                     limits: ast::RangeLimits::Closed,
107                 })
108             } else {
109                 None
110             }
111         } else {
112             None
113         },
114         hir::ExprStruct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD)
115             || match_qpath(path, &paths::RANGE_FROM)
116         {
117             Some(Range {
118                 start: Some(get_field("start", fields)?),
119                 end: None,
120                 limits: ast::RangeLimits::HalfOpen,
121             })
122         } else if match_qpath(path, &paths::RANGE_STD) || match_qpath(path, &paths::RANGE) {
123             Some(Range {
124                 start: Some(get_field("start", fields)?),
125                 end: Some(get_field("end", fields)?),
126                 limits: ast::RangeLimits::HalfOpen,
127             })
128         } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
129             Some(Range {
130                 start: None,
131                 end: Some(get_field("end", fields)?),
132                 limits: ast::RangeLimits::Closed,
133             })
134         } else if match_qpath(path, &paths::RANGE_TO_STD) || match_qpath(path, &paths::RANGE_TO) {
135             Some(Range {
136                 start: None,
137                 end: Some(get_field("end", fields)?),
138                 limits: ast::RangeLimits::HalfOpen,
139             })
140         } else {
141             None
142         },
143         _ => None,
144     }
145 }
146
147 /// Checks if a `let` decl is from a `for` loop desugaring.
148 pub fn is_from_for_desugar(decl: &hir::Decl) -> bool {
149     // This will detect plain for-loops without an actual variable binding:
150     //
151     // ```
152     // for x in some_vec {
153     //   // do stuff
154     // }
155     // ```
156     if_chain! {
157         if let hir::DeclLocal(ref loc) = decl.node;
158         if let Some(ref expr) = loc.init;
159         if let hir::ExprMatch(_, _, hir::MatchSource::ForLoopDesugar) = expr.node;
160         then {
161             return true;
162         }
163     }
164
165     // This detects a variable binding in for loop to avoid `let_unit_value`
166     // lint (see issue #1964).
167     //
168     // ```
169     // for _ in vec![()] {
170     //   // anything
171     // }
172     // ```
173     if_chain! {
174         if let hir::DeclLocal(ref loc) = decl.node;
175         if let hir::LocalSource::ForLoopDesugar = loc.source;
176         then {
177             return true;
178         }
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::ExprMatch(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.node;
189         if let hir::ExprCall(_, ref iterargs) = iterexpr.node;
190         if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
191         if let hir::ExprLoop(ref block, _, _) = arms[0].body.node;
192         if block.expr.is_none();
193         if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
194         if let hir::StmtDecl(ref decl, _) = let_stmt.node;
195         if let hir::DeclLocal(ref decl) = decl.node;
196         if let hir::StmtExpr(ref expr, _) = body.node;
197         then {
198             return Some((&*decl.pat, &iterargs[0], expr));
199         }
200     }
201     None
202 }
203
204 /// Represent the pre-expansion arguments of a `vec!` invocation.
205 pub enum VecArgs<'a> {
206     /// `vec![elem; len]`
207     Repeat(&'a hir::Expr, &'a hir::Expr),
208     /// `vec![a, b, c]`
209     Vec(&'a [hir::Expr]),
210 }
211
212 /// Returns the arguments of the `vec!` macro if this expression was expanded
213 /// from `vec!`.
214 pub fn vec_macro<'e>(cx: &LateContext, expr: &'e hir::Expr) -> Option<VecArgs<'e>> {
215     if_chain! {
216         if let hir::ExprCall(ref fun, ref args) = expr.node;
217         if let hir::ExprPath(ref path) = fun.node;
218         if is_expn_of(fun.span, "vec").is_some();
219         if let Some(fun_def_id) = opt_def_id(resolve_node(cx, path, fun.hir_id));
220         then {
221             return if match_def_path(cx.tcx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
222                 // `vec![elem; size]` case
223                 Some(VecArgs::Repeat(&args[0], &args[1]))
224             }
225             else if match_def_path(cx.tcx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
226                 // `vec![a, b, c]` case
227                 if_chain! {
228                     if let hir::ExprBox(ref boxed) = args[0].node;
229                     if let hir::ExprArray(ref args) = boxed.node;
230                     then {
231                         return Some(VecArgs::Vec(&*args));
232                     }
233                 }
234
235                 None
236             }
237             else {
238                 None
239             };
240         }
241     }
242
243     None
244 }