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