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 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(expr: &hir::Expr) -> Option<Range> {
48 /// Find the field named `name` in the field. Always return `Some` for
50 fn get_field<'a>(name: &str, fields: &'a [hir::Field]) -> Option<&'a hir::Expr> {
51 let expr = &fields.iter().find(|field| field.name.node == name)?.expr;
56 // The range syntax is expanded to literal paths starting with `core` or `std`
58 // `#[no_std]`. Testing both instead of resolving the paths.
61 hir::ExprPath(ref path) => {
62 if match_qpath(path, &paths::RANGE_FULL_STD) || match_qpath(path, &paths::RANGE_FULL) {
66 limits: ast::RangeLimits::HalfOpen,
72 hir::ExprCall(ref path, ref args) => if let hir::ExprPath(ref path) = path.node {
73 if match_qpath(path, &paths::RANGE_INCLUSIVE_STD_NEW) || match_qpath(path, &paths::RANGE_INCLUSIVE_NEW) {
75 start: Some(&args[0]),
77 limits: ast::RangeLimits::Closed,
85 hir::ExprStruct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD)
86 || match_qpath(path, &paths::RANGE_FROM)
89 start: Some(get_field("start", fields)?),
91 limits: ast::RangeLimits::HalfOpen,
93 } else if match_qpath(path, &paths::RANGE_STD) || match_qpath(path, &paths::RANGE) {
95 start: Some(get_field("start", fields)?),
96 end: Some(get_field("end", fields)?),
97 limits: ast::RangeLimits::HalfOpen,
99 } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
102 end: Some(get_field("end", fields)?),
103 limits: ast::RangeLimits::Closed,
105 } else if match_qpath(path, &paths::RANGE_TO_STD) || match_qpath(path, &paths::RANGE_TO) {
108 end: Some(get_field("end", fields)?),
109 limits: ast::RangeLimits::HalfOpen,
118 /// Checks if a `let` decl is from a `for` loop desugaring.
119 pub fn is_from_for_desugar(decl: &hir::Decl) -> bool {
120 // This will detect plain for-loops without an actual variable binding:
123 // for x in some_vec {
128 if let hir::DeclLocal(ref loc) = decl.node;
129 if let Some(ref expr) = loc.init;
130 if let hir::ExprMatch(_, _, hir::MatchSource::ForLoopDesugar) = expr.node;
136 // This detects a variable binding in for loop to avoid `let_unit_value`
137 // lint (see issue #1964).
140 // for _ in vec![()] {
145 if let hir::DeclLocal(ref loc) = decl.node;
146 if let hir::LocalSource::ForLoopDesugar = loc.source;
155 /// Recover the essential nodes of a desugared for loop:
156 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
157 pub fn for_loop(expr: &hir::Expr) -> Option<(&hir::Pat, &hir::Expr, &hir::Expr)> {
159 if let hir::ExprMatch(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.node;
160 if let hir::ExprCall(_, ref iterargs) = iterexpr.node;
161 if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
162 if let hir::ExprLoop(ref block, _, _) = arms[0].body.node;
163 if block.expr.is_none();
164 if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
165 if let hir::StmtDecl(ref decl, _) = let_stmt.node;
166 if let hir::DeclLocal(ref decl) = decl.node;
167 if let hir::StmtExpr(ref expr, _) = body.node;
169 return Some((&*decl.pat, &iterargs[0], expr));
175 /// Represent the pre-expansion arguments of a `vec!` invocation.
176 pub enum VecArgs<'a> {
177 /// `vec![elem; len]`
178 Repeat(&'a hir::Expr, &'a hir::Expr),
180 Vec(&'a [hir::Expr]),
183 /// Returns the arguments of the `vec!` macro if this expression was expanded
185 pub fn vec_macro<'e>(cx: &LateContext, expr: &'e hir::Expr) -> Option<VecArgs<'e>> {
187 if let hir::ExprCall(ref fun, ref args) = expr.node;
188 if let hir::ExprPath(ref path) = fun.node;
189 if is_expn_of(fun.span, "vec").is_some();
190 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, path, fun.hir_id));
192 return if match_def_path(cx.tcx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
193 // `vec![elem; size]` case
194 Some(VecArgs::Repeat(&args[0], &args[1]))
196 else if match_def_path(cx.tcx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
197 // `vec![a, b, c]` case
199 if let hir::ExprBox(ref boxed) = args[0].node;
200 if let hir::ExprArray(ref args) = boxed.node;
202 return Some(VecArgs::Vec(&*args));