]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/higher.rs
Rustup field -> method transition of ..=
[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;
7 use rustc::lint::LateContext;
8 use syntax::ast;
9 use 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(expr: &hir::Expr) -> Option<Range> {
48     /// Find the field named `name` in the field. Always return `Some` for
49     /// convenience.
50     fn get_field<'a>(name: &str, fields: &'a [hir::Field]) -> Option<&'a hir::Expr> {
51         let expr = &fields.iter().find(|field| field.name.node == name)?.expr;
52
53         Some(expr)
54     }
55
56     // The range syntax is expanded to literal paths starting with `core` or `std`
57     // depending on
58     // `#[no_std]`. Testing both instead of resolving the paths.
59
60     match expr.node {
61         hir::ExprPath(ref path) => {
62             if match_qpath(path, &paths::RANGE_FULL_STD) || match_qpath(path, &paths::RANGE_FULL) {
63                 Some(Range {
64                     start: None,
65                     end: None,
66                     limits: ast::RangeLimits::HalfOpen,
67                 })
68             } else {
69                 None
70             }
71         },
72         hir::ExprCall(ref path, ref args) => if let hir::ExprPath(ref path) = path.node {
73             if match_qpath(path, &paths::RANGE_INCLUSIVE_STD_NEW) || match_qpath(path, &paths::RANGE_INCLUSIVE_NEW) {
74                 Some(Range {
75                     start: Some(&args[0]),
76                     end: Some(&args[1]),
77                     limits: ast::RangeLimits::Closed,
78                 })
79             } else {
80                 None
81             }
82         } else {
83             None
84         },
85         hir::ExprStruct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD)
86             || match_qpath(path, &paths::RANGE_FROM)
87         {
88             Some(Range {
89                 start: Some(get_field("start", fields)?),
90                 end: None,
91                 limits: ast::RangeLimits::HalfOpen,
92             })
93         } else if match_qpath(path, &paths::RANGE_STD) || match_qpath(path, &paths::RANGE) {
94             Some(Range {
95                 start: Some(get_field("start", fields)?),
96                 end: Some(get_field("end", fields)?),
97                 limits: ast::RangeLimits::HalfOpen,
98             })
99         } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
100             Some(Range {
101                 start: None,
102                 end: Some(get_field("end", fields)?),
103                 limits: ast::RangeLimits::Closed,
104             })
105         } else if match_qpath(path, &paths::RANGE_TO_STD) || match_qpath(path, &paths::RANGE_TO) {
106             Some(Range {
107                 start: None,
108                 end: Some(get_field("end", fields)?),
109                 limits: ast::RangeLimits::HalfOpen,
110             })
111         } else {
112             None
113         },
114         _ => None,
115     }
116 }
117
118 /// Checks if a `let` decl is from a `for` loop desugaring.
119 pub fn is_from_for_desugar(decl: &hir::Decl) -> bool {
120     // This will detect plain for-loops without an actual variable binding:
121     //
122     // ```
123     // for x in some_vec {
124     //   // do stuff
125     // }
126     // ```
127     if_chain! {
128         if let hir::DeclLocal(ref loc) = decl.node;
129         if let Some(ref expr) = loc.init;
130         if let hir::ExprMatch(_, _, hir::MatchSource::ForLoopDesugar) = expr.node;
131         then {
132             return true;
133         }
134     }
135
136     // This detects a variable binding in for loop to avoid `let_unit_value`
137     // lint (see issue #1964).
138     //
139     // ```
140     // for _ in vec![()] {
141     //   // anything
142     // }
143     // ```
144     if_chain! {
145         if let hir::DeclLocal(ref loc) = decl.node;
146         if let hir::LocalSource::ForLoopDesugar = loc.source;
147         then {
148             return true;
149         }
150     }
151
152     false
153 }
154
155 /// Recover the essential nodes of a desugared for loop:
156 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
157 pub fn for_loop(expr: &hir::Expr) -> Option<(&hir::Pat, &hir::Expr, &hir::Expr)> {
158     if_chain! {
159         if let hir::ExprMatch(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.node;
160         if let hir::ExprCall(_, ref iterargs) = iterexpr.node;
161         if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
162         if let hir::ExprLoop(ref block, _, _) = arms[0].body.node;
163         if block.expr.is_none();
164         if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
165         if let hir::StmtDecl(ref decl, _) = let_stmt.node;
166         if let hir::DeclLocal(ref decl) = decl.node;
167         if let hir::StmtExpr(ref expr, _) = body.node;
168         then {
169             return Some((&*decl.pat, &iterargs[0], expr));
170         }
171     }
172     None
173 }
174
175 /// Represent the pre-expansion arguments of a `vec!` invocation.
176 pub enum VecArgs<'a> {
177     /// `vec![elem; len]`
178     Repeat(&'a hir::Expr, &'a hir::Expr),
179     /// `vec![a, b, c]`
180     Vec(&'a [hir::Expr]),
181 }
182
183 /// Returns the arguments of the `vec!` macro if this expression was expanded
184 /// from `vec!`.
185 pub fn vec_macro<'e>(cx: &LateContext, expr: &'e hir::Expr) -> Option<VecArgs<'e>> {
186     if_chain! {
187         if let hir::ExprCall(ref fun, ref args) = expr.node;
188         if let hir::ExprPath(ref path) = fun.node;
189         if is_expn_of(fun.span, "vec").is_some();
190         if let Some(fun_def_id) = opt_def_id(resolve_node(cx, path, fun.hir_id));
191         then {
192             return if match_def_path(cx.tcx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
193                 // `vec![elem; size]` case
194                 Some(VecArgs::Repeat(&args[0], &args[1]))
195             }
196             else if match_def_path(cx.tcx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
197                 // `vec![a, b, c]` case
198                 if_chain! {
199                     if let hir::ExprBox(ref boxed) = args[0].node;
200                     if let hir::ExprArray(ref args) = boxed.node;
201                     then {
202                         return Some(VecArgs::Vec(&*args));
203                     }
204                 }
205
206                 None
207             }
208             else {
209                 None
210             };
211         }
212     }
213
214     None
215 }