1 //! This module contains functions for retrieve the original AST from lowered
4 #![deny(clippy::missing_docs_in_private_items)]
6 use crate::utils::{is_expn_of, match_def_path, match_qpath, paths};
7 use if_chain::if_chain;
8 use rustc::lint::LateContext;
12 /// Converts a hir binary operator to the corresponding `ast` type.
14 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
16 hir::BinOpKind::Eq => ast::BinOpKind::Eq,
17 hir::BinOpKind::Ge => ast::BinOpKind::Ge,
18 hir::BinOpKind::Gt => ast::BinOpKind::Gt,
19 hir::BinOpKind::Le => ast::BinOpKind::Le,
20 hir::BinOpKind::Lt => ast::BinOpKind::Lt,
21 hir::BinOpKind::Ne => ast::BinOpKind::Ne,
22 hir::BinOpKind::Or => ast::BinOpKind::Or,
23 hir::BinOpKind::Add => ast::BinOpKind::Add,
24 hir::BinOpKind::And => ast::BinOpKind::And,
25 hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
26 hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
27 hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
28 hir::BinOpKind::Div => ast::BinOpKind::Div,
29 hir::BinOpKind::Mul => ast::BinOpKind::Mul,
30 hir::BinOpKind::Rem => ast::BinOpKind::Rem,
31 hir::BinOpKind::Shl => ast::BinOpKind::Shl,
32 hir::BinOpKind::Shr => ast::BinOpKind::Shr,
33 hir::BinOpKind::Sub => ast::BinOpKind::Sub,
37 /// Represent a range akin to `ast::ExprKind::Range`.
38 #[derive(Debug, Copy, Clone)]
39 pub struct Range<'a> {
40 /// The lower bound of the range, or `None` for ranges such as `..X`.
41 pub start: Option<&'a hir::Expr>,
42 /// The upper bound of the range, or `None` for ranges such as `X..`.
43 pub end: Option<&'a hir::Expr>,
44 /// Whether the interval is open or closed.
45 pub limits: ast::RangeLimits,
48 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
49 pub fn range<'a, 'b, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'b hir::Expr) -> Option<Range<'b>> {
50 /// Finds the field named `name` in the field. Always return `Some` for
52 fn get_field<'c>(name: &str, fields: &'c [hir::Field]) -> Option<&'c hir::Expr> {
53 let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
58 let def_path = match cx.tables.expr_ty(expr).kind {
59 ty::Adt(def, _) => cx.tcx.def_path(def.did),
63 // sanity checks for std::ops::RangeXXXX
64 if def_path.data.len() != 3 {
67 if def_path.data.get(0)?.data.as_symbol() != sym!(ops) {
70 if def_path.data.get(1)?.data.as_symbol() != sym!(range) {
73 let type_name = def_path.data.get(2)?.data.as_symbol();
82 if !range_types.contains(&&*type_name.as_str()) {
86 // The range syntax is expanded to literal paths starting with `core` or `std`
88 // `#[no_std]`. Testing both instead of resolving the paths.
91 hir::ExprKind::Path(ref path) => {
92 if match_qpath(path, &paths::RANGE_FULL_STD) || match_qpath(path, &paths::RANGE_FULL) {
96 limits: ast::RangeLimits::HalfOpen,
102 hir::ExprKind::Call(ref path, ref args) => {
103 if let hir::ExprKind::Path(ref path) = path.kind {
104 if match_qpath(path, &paths::RANGE_INCLUSIVE_STD_NEW) || match_qpath(path, &paths::RANGE_INCLUSIVE_NEW)
107 start: Some(&args[0]),
109 limits: ast::RangeLimits::Closed,
118 hir::ExprKind::Struct(ref path, ref fields, None) => {
119 if match_qpath(path, &paths::RANGE_FROM_STD) || match_qpath(path, &paths::RANGE_FROM) {
121 start: Some(get_field("start", fields)?),
123 limits: ast::RangeLimits::HalfOpen,
125 } else if match_qpath(path, &paths::RANGE_STD) || match_qpath(path, &paths::RANGE) {
127 start: Some(get_field("start", fields)?),
128 end: Some(get_field("end", fields)?),
129 limits: ast::RangeLimits::HalfOpen,
131 } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE)
135 end: Some(get_field("end", fields)?),
136 limits: ast::RangeLimits::Closed,
138 } else if match_qpath(path, &paths::RANGE_TO_STD) || match_qpath(path, &paths::RANGE_TO) {
141 end: Some(get_field("end", fields)?),
142 limits: ast::RangeLimits::HalfOpen,
152 /// Checks if a `let` statement is from a `for` loop desugaring.
153 pub fn is_from_for_desugar(local: &hir::Local) -> bool {
154 // This will detect plain for-loops without an actual variable binding:
157 // for x in some_vec {
162 if let Some(ref expr) = local.init;
163 if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
169 // This detects a variable binding in for loop to avoid `let_unit_value`
170 // lint (see issue #1964).
173 // for _ in vec![()] {
177 if let hir::LocalSource::ForLoopDesugar = local.source {
184 /// Recover the essential nodes of a desugared for loop:
185 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
186 pub fn for_loop(expr: &hir::Expr) -> Option<(&hir::Pat, &hir::Expr, &hir::Expr)> {
188 if let hir::ExprKind::Match(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.kind;
189 if let hir::ExprKind::Call(_, ref iterargs) = iterexpr.kind;
190 if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
191 if let hir::ExprKind::Loop(ref block, _, _) = arms[0].body.kind;
192 if block.expr.is_none();
193 if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
194 if let hir::StmtKind::Local(ref local) = let_stmt.kind;
195 if let hir::StmtKind::Expr(ref expr) = body.kind;
197 return Some((&*local.pat, &iterargs[0], expr));
203 /// Recover the essential nodes of a desugared while loop:
204 /// `while cond { body }` becomes `(cond, body)`.
205 pub fn while_loop(expr: &hir::Expr) -> Option<(&hir::Expr, &hir::Expr)> {
207 if let hir::ExprKind::Loop(block, _, hir::LoopSource::While) = &expr.kind;
208 if let hir::Block { expr: Some(expr), .. } = &**block;
209 if let hir::ExprKind::Match(cond, arms, hir::MatchSource::WhileDesugar) = &expr.kind;
210 if let hir::ExprKind::DropTemps(cond) = &cond.kind;
211 if let [arm, ..] = &arms[..];
212 if let hir::Arm { body, .. } = arm;
214 return Some((cond, body));
220 /// Recover the essential nodes of a desugared if block
221 /// `if cond { then } else { els }` becomes `(cond, then, Some(els))`
222 pub fn if_block(expr: &hir::Expr) -> Option<(&hir::Expr, &hir::Expr, Option<&hir::Expr>)> {
223 if let hir::ExprKind::Match(ref cond, ref arms, hir::MatchSource::IfDesugar { contains_else_clause }) = expr.kind {
224 let cond = if let hir::ExprKind::DropTemps(ref cond) = cond.kind {
227 panic!("If block desugar must contain DropTemps");
229 let then = &arms[0].body;
230 let els = if contains_else_clause {
235 Some((cond, then, els))
241 /// Represent the pre-expansion arguments of a `vec!` invocation.
242 pub enum VecArgs<'a> {
243 /// `vec![elem; len]`
244 Repeat(&'a hir::Expr, &'a hir::Expr),
246 Vec(&'a [hir::Expr]),
249 /// Returns the arguments of the `vec!` macro if this expression was expanded
251 pub fn vec_macro<'e>(cx: &LateContext<'_, '_>, expr: &'e hir::Expr) -> Option<VecArgs<'e>> {
253 if let hir::ExprKind::Call(ref fun, ref args) = expr.kind;
254 if let hir::ExprKind::Path(ref qpath) = fun.kind;
255 if is_expn_of(fun.span, "vec").is_some();
256 if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
258 return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
259 // `vec![elem; size]` case
260 Some(VecArgs::Repeat(&args[0], &args[1]))
262 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
263 // `vec![a, b, c]` case
265 if let hir::ExprKind::Box(ref boxed) = args[0].kind;
266 if let hir::ExprKind::Array(ref args) = boxed.kind;
268 return Some(VecArgs::Vec(&*args));