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