1 //! This module contains functions for retrieve the original AST from lowered
4 #![deny(clippy::missing_docs_in_private_items)]
6 use crate::{is_expn_of, match_def_path, paths};
7 use if_chain::if_chain;
10 use rustc_hir::{BorrowKind, Expr, ExprKind, StmtKind, UnOp};
11 use rustc_lint::LateContext;
12 use rustc_span::source_map::Span;
14 /// Converts a hir binary operator to the corresponding `ast` type.
16 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
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,
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,
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
54 fn get_field<'c>(name: &str, fields: &'c [hir::ExprField<'_>]) -> Option<&'c hir::Expr<'c>> {
55 let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
61 hir::ExprKind::Call(ref path, ref args)
64 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
68 start: Some(&args[0]),
70 limits: ast::RangeLimits::Closed,
73 hir::ExprKind::Struct(ref path, ref fields, None) => match path {
74 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
77 limits: ast::RangeLimits::HalfOpen,
79 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
80 start: Some(get_field("start", fields)?),
82 limits: ast::RangeLimits::HalfOpen,
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,
89 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
91 end: Some(get_field("end", fields)?),
92 limits: ast::RangeLimits::Closed,
94 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
96 end: Some(get_field("end", fields)?),
97 limits: ast::RangeLimits::HalfOpen,
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:
110 // for x in some_vec {
115 if let Some(ref expr) = local.init;
116 if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
122 // This detects a variable binding in for loop to avoid `let_unit_value`
123 // lint (see issue #1964).
126 // for _ in vec![()] {
130 if let hir::LocalSource::ForLoopDesugar = local.source {
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)> {
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;
152 return Some((&*local.pat, &iterargs[0], expr, arms[0].span));
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>)> {
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[..];
167 return Some((cond, body));
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>),
178 Vec(&'a [hir::Expr<'a>]),
181 /// Returns the arguments of the `vec!` macro if this expression was expanded
183 pub fn vec_macro<'e>(cx: &LateContext<'_>, expr: &'e hir::Expr<'_>) -> Option<VecArgs<'e>> {
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();
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]))
194 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
195 // `vec![a, b, c]` case
197 if let hir::ExprKind::Box(ref boxed) = args[0].kind;
198 if let hir::ExprKind::Array(ref args) = boxed.kind;
200 return Some(VecArgs::Vec(&*args));
206 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
207 Some(VecArgs::Vec(&[]))
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!`
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
228 fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
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;
235 return Some(vec![lhs, rhs]);
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)`)
246 if let ExprKind::If(ref clause, _, _) = matchexpr.kind;
247 if let ExprKind::Unary(UnOp::Not, condition) = clause.kind;
249 return Some(vec![condition]);
253 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
255 if let ExprKind::Block(ref matchblock,_) = matchexpr.kind;
256 if let Some(ref matchblock_expr) = matchblock.expr;
258 return ast_matchblock(matchblock_expr);
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);