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