]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/higher.rs
Rollup merge of #81588 - xfix:delete-doc-alias, r=Mark-Simulacrum
[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(hir::Block { expr: Some(expr), .. }, _, hir::LoopSource::While, _) = &expr.kind;
162         if let hir::ExprKind::Match(cond, arms, hir::MatchSource::WhileDesugar) = &expr.kind;
163         if let hir::ExprKind::DropTemps(cond) = &cond.kind;
164         if let [hir::Arm { body, .. }, ..] = &arms[..];
165         then {
166             return Some((cond, body));
167         }
168     }
169     None
170 }
171
172 /// Represent the pre-expansion arguments of a `vec!` invocation.
173 pub enum VecArgs<'a> {
174     /// `vec![elem; len]`
175     Repeat(&'a hir::Expr<'a>, &'a hir::Expr<'a>),
176     /// `vec![a, b, c]`
177     Vec(&'a [hir::Expr<'a>]),
178 }
179
180 /// Returns the arguments of the `vec!` macro if this expression was expanded
181 /// from `vec!`.
182 pub fn vec_macro<'e>(cx: &LateContext<'_>, expr: &'e hir::Expr<'_>) -> Option<VecArgs<'e>> {
183     if_chain! {
184         if let hir::ExprKind::Call(ref fun, ref args) = expr.kind;
185         if let hir::ExprKind::Path(ref qpath) = fun.kind;
186         if is_expn_of(fun.span, "vec").is_some();
187         if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
188         then {
189             return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
190                 // `vec![elem; size]` case
191                 Some(VecArgs::Repeat(&args[0], &args[1]))
192             }
193             else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
194                 // `vec![a, b, c]` case
195                 if_chain! {
196                     if let hir::ExprKind::Box(ref boxed) = args[0].kind;
197                     if let hir::ExprKind::Array(ref args) = boxed.kind;
198                     then {
199                         return Some(VecArgs::Vec(&*args));
200                     }
201                 }
202
203                 None
204             }
205             else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
206                 Some(VecArgs::Vec(&[]))
207             }
208             else {
209                 None
210             };
211         }
212     }
213
214     None
215 }
216
217 /// Extract args from an assert-like macro.
218 /// Currently working with:
219 /// - `assert!`, `assert_eq!` and `assert_ne!`
220 /// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
221 /// For example:
222 /// `assert!(expr)` will return Some([expr])
223 /// `debug_assert_eq!(a, b)` will return Some([a, b])
224 pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
225     /// Try to match the AST for a pattern that contains a match, for example when two args are
226     /// compared
227     fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
228         if_chain! {
229             if let ExprKind::Match(ref headerexpr, _, _) = &matchblock_expr.kind;
230             if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
231             if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
232             if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
233             then {
234                 return Some(vec![lhs, rhs]);
235             }
236         }
237         None
238     }
239
240     if let ExprKind::Block(ref block, _) = e.kind {
241         if block.stmts.len() == 1 {
242             if let StmtKind::Semi(ref matchexpr) = block.stmts.get(0)?.kind {
243                 // macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
244                 if_chain! {
245                     if let ExprKind::If(ref clause, _, _)  = matchexpr.kind;
246                     if let ExprKind::Unary(UnOp::UnNot, condition) = clause.kind;
247                     then {
248                         return Some(vec![condition]);
249                     }
250                 }
251
252                 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
253                 if_chain! {
254                     if let ExprKind::Block(ref matchblock,_) = matchexpr.kind;
255                     if let Some(ref matchblock_expr) = matchblock.expr;
256                     then {
257                         return ast_matchblock(matchblock_expr);
258                     }
259                 }
260             }
261         } else if let Some(matchblock_expr) = block.expr {
262             // macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
263             return ast_matchblock(&matchblock_expr);
264         }
265     }
266     None
267 }