]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/higher.rs
Merge commit '928e72dd10749875cbd412f74bfbfd7765dbcd8a' into clippyup
[rust.git] / clippy_utils / src / 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::{is_expn_of, match_def_path, paths};
7 use if_chain::if_chain;
8 use rustc_ast::ast;
9 use rustc_hir as hir;
10 use rustc_hir::{BorrowKind, Expr, ExprKind, StmtKind, UnOp};
11 use rustc_lint::LateContext;
12 use rustc_span::source_map::Span;
13
14 /// Converts a hir binary operator to the corresponding `ast` type.
15 #[must_use]
16 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
17     match op {
18         hir::BinOpKind::Eq => ast::BinOpKind::Eq,
19         hir::BinOpKind::Ge => ast::BinOpKind::Ge,
20         hir::BinOpKind::Gt => ast::BinOpKind::Gt,
21         hir::BinOpKind::Le => ast::BinOpKind::Le,
22         hir::BinOpKind::Lt => ast::BinOpKind::Lt,
23         hir::BinOpKind::Ne => ast::BinOpKind::Ne,
24         hir::BinOpKind::Or => ast::BinOpKind::Or,
25         hir::BinOpKind::Add => ast::BinOpKind::Add,
26         hir::BinOpKind::And => ast::BinOpKind::And,
27         hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
28         hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
29         hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
30         hir::BinOpKind::Div => ast::BinOpKind::Div,
31         hir::BinOpKind::Mul => ast::BinOpKind::Mul,
32         hir::BinOpKind::Rem => ast::BinOpKind::Rem,
33         hir::BinOpKind::Shl => ast::BinOpKind::Shl,
34         hir::BinOpKind::Shr => ast::BinOpKind::Shr,
35         hir::BinOpKind::Sub => ast::BinOpKind::Sub,
36     }
37 }
38
39 /// Represent a range akin to `ast::ExprKind::Range`.
40 #[derive(Debug, Copy, Clone)]
41 pub struct Range<'a> {
42     /// The lower bound of the range, or `None` for ranges such as `..X`.
43     pub start: Option<&'a hir::Expr<'a>>,
44     /// The upper bound of the range, or `None` for ranges such as `X..`.
45     pub end: Option<&'a hir::Expr<'a>>,
46     /// Whether the interval is open or closed.
47     pub limits: ast::RangeLimits,
48 }
49
50 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
51 pub fn range<'a>(expr: &'a hir::Expr<'_>) -> Option<Range<'a>> {
52     /// Finds the field named `name` in the field. Always return `Some` for
53     /// convenience.
54     fn get_field<'c>(name: &str, fields: &'c [hir::Field<'_>]) -> Option<&'c hir::Expr<'c>> {
55         let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
56
57         Some(expr)
58     }
59
60     match expr.kind {
61         hir::ExprKind::Call(ref path, ref args)
62             if matches!(
63                 path.kind,
64                 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
65             ) =>
66         {
67             Some(Range {
68                 start: Some(&args[0]),
69                 end: Some(&args[1]),
70                 limits: ast::RangeLimits::Closed,
71             })
72         },
73         hir::ExprKind::Struct(ref path, ref fields, None) => match path {
74             hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
75                 start: None,
76                 end: None,
77                 limits: ast::RangeLimits::HalfOpen,
78             }),
79             hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
80                 start: Some(get_field("start", fields)?),
81                 end: None,
82                 limits: ast::RangeLimits::HalfOpen,
83             }),
84             hir::QPath::LangItem(hir::LangItem::Range, _) => Some(Range {
85                 start: Some(get_field("start", fields)?),
86                 end: Some(get_field("end", fields)?),
87                 limits: ast::RangeLimits::HalfOpen,
88             }),
89             hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
90                 start: None,
91                 end: Some(get_field("end", fields)?),
92                 limits: ast::RangeLimits::Closed,
93             }),
94             hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
95                 start: None,
96                 end: Some(get_field("end", fields)?),
97                 limits: ast::RangeLimits::HalfOpen,
98             }),
99             _ => None,
100         },
101         _ => None,
102     }
103 }
104
105 /// Checks if a `let` statement is from a `for` loop desugaring.
106 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
107     // This will detect plain for-loops without an actual variable binding:
108     //
109     // ```
110     // for x in some_vec {
111     //     // do stuff
112     // }
113     // ```
114     if_chain! {
115         if let Some(ref expr) = local.init;
116         if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
117         then {
118             return true;
119         }
120     }
121
122     // This detects a variable binding in for loop to avoid `let_unit_value`
123     // lint (see issue #1964).
124     //
125     // ```
126     // for _ in vec![()] {
127     //     // anything
128     // }
129     // ```
130     if let hir::LocalSource::ForLoopDesugar = local.source {
131         return true;
132     }
133
134     false
135 }
136
137 /// Recover the essential nodes of a desugared for loop as well as the entire span:
138 /// `for pat in arg { body }` becomes `(pat, arg, body)`. Return `(pat, arg, body, span)`.
139 pub fn for_loop<'tcx>(
140     expr: &'tcx hir::Expr<'tcx>,
141 ) -> Option<(&hir::Pat<'_>, &'tcx hir::Expr<'tcx>, &'tcx hir::Expr<'tcx>, Span)> {
142     if_chain! {
143         if let hir::ExprKind::Match(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.kind;
144         if let hir::ExprKind::Call(_, ref iterargs) = iterexpr.kind;
145         if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
146         if let hir::ExprKind::Loop(ref block, ..) = arms[0].body.kind;
147         if block.expr.is_none();
148         if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
149         if let hir::StmtKind::Local(ref local) = let_stmt.kind;
150         if let hir::StmtKind::Expr(ref expr) = body.kind;
151         then {
152             return Some((&*local.pat, &iterargs[0], expr, arms[0].span));
153         }
154     }
155     None
156 }
157
158 /// Recover the essential nodes of a desugared while loop:
159 /// `while cond { body }` becomes `(cond, body)`.
160 pub fn while_loop<'tcx>(expr: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx hir::Expr<'tcx>, &'tcx hir::Expr<'tcx>)> {
161     if_chain! {
162         if let hir::ExprKind::Loop(hir::Block { expr: Some(expr), .. }, _, hir::LoopSource::While, _) = &expr.kind;
163         if let hir::ExprKind::Match(cond, arms, hir::MatchSource::WhileDesugar) = &expr.kind;
164         if let hir::ExprKind::DropTemps(cond) = &cond.kind;
165         if let [hir::Arm { body, .. }, ..] = &arms[..];
166         then {
167             return Some((cond, body));
168         }
169     }
170     None
171 }
172
173 /// Represent the pre-expansion arguments of a `vec!` invocation.
174 pub enum VecArgs<'a> {
175     /// `vec![elem; len]`
176     Repeat(&'a hir::Expr<'a>, &'a hir::Expr<'a>),
177     /// `vec![a, b, c]`
178     Vec(&'a [hir::Expr<'a>]),
179 }
180
181 /// Returns the arguments of the `vec!` macro if this expression was expanded
182 /// from `vec!`.
183 pub fn vec_macro<'e>(cx: &LateContext<'_>, expr: &'e hir::Expr<'_>) -> Option<VecArgs<'e>> {
184     if_chain! {
185         if let hir::ExprKind::Call(ref fun, ref args) = expr.kind;
186         if let hir::ExprKind::Path(ref qpath) = fun.kind;
187         if is_expn_of(fun.span, "vec").is_some();
188         if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
189         then {
190             return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
191                 // `vec![elem; size]` case
192                 Some(VecArgs::Repeat(&args[0], &args[1]))
193             }
194             else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
195                 // `vec![a, b, c]` case
196                 if_chain! {
197                     if let hir::ExprKind::Box(ref boxed) = args[0].kind;
198                     if let hir::ExprKind::Array(ref args) = boxed.kind;
199                     then {
200                         return Some(VecArgs::Vec(&*args));
201                     }
202                 }
203
204                 None
205             }
206             else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
207                 Some(VecArgs::Vec(&[]))
208             }
209             else {
210                 None
211             };
212         }
213     }
214
215     None
216 }
217
218 /// Extract args from an assert-like macro.
219 /// Currently working with:
220 /// - `assert!`, `assert_eq!` and `assert_ne!`
221 /// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
222 /// For example:
223 /// `assert!(expr)` will return Some([expr])
224 /// `debug_assert_eq!(a, b)` will return Some([a, b])
225 pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
226     /// Try to match the AST for a pattern that contains a match, for example when two args are
227     /// compared
228     fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
229         if_chain! {
230             if let ExprKind::Match(ref headerexpr, _, _) = &matchblock_expr.kind;
231             if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
232             if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
233             if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
234             then {
235                 return Some(vec![lhs, rhs]);
236             }
237         }
238         None
239     }
240
241     if let ExprKind::Block(ref block, _) = e.kind {
242         if block.stmts.len() == 1 {
243             if let StmtKind::Semi(ref matchexpr) = block.stmts.get(0)?.kind {
244                 // macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
245                 if_chain! {
246                     if let ExprKind::If(ref clause, _, _)  = matchexpr.kind;
247                     if let ExprKind::Unary(UnOp::Not, condition) = clause.kind;
248                     then {
249                         return Some(vec![condition]);
250                     }
251                 }
252
253                 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
254                 if_chain! {
255                     if let ExprKind::Block(ref matchblock,_) = matchexpr.kind;
256                     if let Some(ref matchblock_expr) = matchblock.expr;
257                     then {
258                         return ast_matchblock(matchblock_expr);
259                     }
260                 }
261             }
262         } else if let Some(matchblock_expr) = block.expr {
263             // macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
264             return ast_matchblock(&matchblock_expr);
265         }
266     }
267     None
268 }