1 //! This module contains functions for retrieve the original AST from lowered
4 #![deny(missing_docs_in_private_items)]
7 use rustc::lint::LateContext;
9 use crate::utils::{is_expn_of, match_def_path, match_qpath, opt_def_id, paths, resolve_node};
11 /// Convert a hir binary operator to the corresponding `ast` type.
12 pub fn binop(op: hir::BinOp_) -> ast::BinOpKind {
14 hir::BiEq => ast::BinOpKind::Eq,
15 hir::BiGe => ast::BinOpKind::Ge,
16 hir::BiGt => ast::BinOpKind::Gt,
17 hir::BiLe => ast::BinOpKind::Le,
18 hir::BiLt => ast::BinOpKind::Lt,
19 hir::BiNe => ast::BinOpKind::Ne,
20 hir::BiOr => ast::BinOpKind::Or,
21 hir::BiAdd => ast::BinOpKind::Add,
22 hir::BiAnd => ast::BinOpKind::And,
23 hir::BiBitAnd => ast::BinOpKind::BitAnd,
24 hir::BiBitOr => ast::BinOpKind::BitOr,
25 hir::BiBitXor => ast::BinOpKind::BitXor,
26 hir::BiDiv => ast::BinOpKind::Div,
27 hir::BiMul => ast::BinOpKind::Mul,
28 hir::BiRem => ast::BinOpKind::Rem,
29 hir::BiShl => ast::BinOpKind::Shl,
30 hir::BiShr => ast::BinOpKind::Shr,
31 hir::BiSub => ast::BinOpKind::Sub,
35 /// Represent a range akin to `ast::ExprKind::Range`.
36 #[derive(Debug, Copy, Clone)]
37 pub struct Range<'a> {
38 /// The lower bound of the range, or `None` for ranges such as `..X`.
39 pub start: Option<&'a hir::Expr>,
40 /// The upper bound of the range, or `None` for ranges such as `X..`.
41 pub end: Option<&'a hir::Expr>,
42 /// Whether the interval is open or closed.
43 pub limits: ast::RangeLimits,
46 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
47 pub fn range<'a, 'b, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'b hir::Expr) -> Option<Range<'b>> {
49 let def_path = match cx.tables.expr_ty(expr).sty {
50 ty::TyAdt(def, _) => cx.tcx.def_path(def.did),
54 // sanity checks for std::ops::RangeXXXX
55 if def_path.data.len() != 3 {
58 if def_path.data.get(0)?.data.as_interned_str() != "ops" {
61 if def_path.data.get(1)?.data.as_interned_str() != "range" {
64 let type_name = def_path.data.get(2)?.data.as_interned_str();
73 if !range_types.contains(&&*type_name.as_str()) {
77 /// Find the field named `name` in the field. Always return `Some` for
79 fn get_field<'a>(name: &str, fields: &'a [hir::Field]) -> Option<&'a hir::Expr> {
80 let expr = &fields.iter().find(|field| field.ident.name == name)?.expr;
85 // The range syntax is expanded to literal paths starting with `core` or `std`
87 // `#[no_std]`. Testing both instead of resolving the paths.
90 hir::ExprPath(ref path) => {
91 if match_qpath(path, &paths::RANGE_FULL_STD) || match_qpath(path, &paths::RANGE_FULL) {
95 limits: ast::RangeLimits::HalfOpen,
101 hir::ExprCall(ref path, ref args) => if let hir::ExprPath(ref path) = path.node {
102 if match_qpath(path, &paths::RANGE_INCLUSIVE_STD_NEW) || match_qpath(path, &paths::RANGE_INCLUSIVE_NEW) {
104 start: Some(&args[0]),
106 limits: ast::RangeLimits::Closed,
114 hir::ExprStruct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD)
115 || match_qpath(path, &paths::RANGE_FROM)
118 start: Some(get_field("start", fields)?),
120 limits: ast::RangeLimits::HalfOpen,
122 } else if match_qpath(path, &paths::RANGE_STD) || match_qpath(path, &paths::RANGE) {
124 start: Some(get_field("start", fields)?),
125 end: Some(get_field("end", fields)?),
126 limits: ast::RangeLimits::HalfOpen,
128 } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
131 end: Some(get_field("end", fields)?),
132 limits: ast::RangeLimits::Closed,
134 } else if match_qpath(path, &paths::RANGE_TO_STD) || match_qpath(path, &paths::RANGE_TO) {
137 end: Some(get_field("end", fields)?),
138 limits: ast::RangeLimits::HalfOpen,
147 /// Checks if a `let` decl is from a `for` loop desugaring.
148 pub fn is_from_for_desugar(decl: &hir::Decl) -> bool {
149 // This will detect plain for-loops without an actual variable binding:
152 // for x in some_vec {
157 if let hir::DeclLocal(ref loc) = decl.node;
158 if let Some(ref expr) = loc.init;
159 if let hir::ExprMatch(_, _, hir::MatchSource::ForLoopDesugar) = expr.node;
165 // This detects a variable binding in for loop to avoid `let_unit_value`
166 // lint (see issue #1964).
169 // for _ in vec![()] {
174 if let hir::DeclLocal(ref loc) = decl.node;
175 if let hir::LocalSource::ForLoopDesugar = loc.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::ExprMatch(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.node;
189 if let hir::ExprCall(_, ref iterargs) = iterexpr.node;
190 if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
191 if let hir::ExprLoop(ref block, _, _) = arms[0].body.node;
192 if block.expr.is_none();
193 if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
194 if let hir::StmtDecl(ref decl, _) = let_stmt.node;
195 if let hir::DeclLocal(ref decl) = decl.node;
196 if let hir::StmtExpr(ref expr, _) = body.node;
198 return Some((&*decl.pat, &iterargs[0], expr));
204 /// Represent the pre-expansion arguments of a `vec!` invocation.
205 pub enum VecArgs<'a> {
206 /// `vec![elem; len]`
207 Repeat(&'a hir::Expr, &'a hir::Expr),
209 Vec(&'a [hir::Expr]),
212 /// Returns the arguments of the `vec!` macro if this expression was expanded
214 pub fn vec_macro<'e>(cx: &LateContext, expr: &'e hir::Expr) -> Option<VecArgs<'e>> {
216 if let hir::ExprCall(ref fun, ref args) = expr.node;
217 if let hir::ExprPath(ref path) = fun.node;
218 if is_expn_of(fun.span, "vec").is_some();
219 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, path, fun.hir_id));
221 return if match_def_path(cx.tcx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
222 // `vec![elem; size]` case
223 Some(VecArgs::Repeat(&args[0], &args[1]))
225 else if match_def_path(cx.tcx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
226 // `vec![a, b, c]` case
228 if let hir::ExprBox(ref boxed) = args[0].node;
229 if let hir::ExprArray(ref args) = boxed.node;
231 return Some(VecArgs::Vec(&*args));