1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! This module contains functions for retrieve the original AST from lowered
14 #![deny(clippy::missing_docs_in_private_items)]
16 use if_chain::if_chain;
17 use crate::rustc::{hir, ty};
18 use crate::rustc::lint::LateContext;
19 use crate::syntax::ast;
20 use crate::utils::{is_expn_of, match_def_path, match_qpath, opt_def_id, paths, resolve_node};
22 /// Convert a hir binary operator to the corresponding `ast` type.
23 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
25 hir::BinOpKind::Eq => ast::BinOpKind::Eq,
26 hir::BinOpKind::Ge => ast::BinOpKind::Ge,
27 hir::BinOpKind::Gt => ast::BinOpKind::Gt,
28 hir::BinOpKind::Le => ast::BinOpKind::Le,
29 hir::BinOpKind::Lt => ast::BinOpKind::Lt,
30 hir::BinOpKind::Ne => ast::BinOpKind::Ne,
31 hir::BinOpKind::Or => ast::BinOpKind::Or,
32 hir::BinOpKind::Add => ast::BinOpKind::Add,
33 hir::BinOpKind::And => ast::BinOpKind::And,
34 hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
35 hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
36 hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
37 hir::BinOpKind::Div => ast::BinOpKind::Div,
38 hir::BinOpKind::Mul => ast::BinOpKind::Mul,
39 hir::BinOpKind::Rem => ast::BinOpKind::Rem,
40 hir::BinOpKind::Shl => ast::BinOpKind::Shl,
41 hir::BinOpKind::Shr => ast::BinOpKind::Shr,
42 hir::BinOpKind::Sub => ast::BinOpKind::Sub,
46 /// Represent a range akin to `ast::ExprKind::Range`.
47 #[derive(Debug, Copy, Clone)]
48 pub struct Range<'a> {
49 /// The lower bound of the range, or `None` for ranges such as `..X`.
50 pub start: Option<&'a hir::Expr>,
51 /// The upper bound of the range, or `None` for ranges such as `X..`.
52 pub end: Option<&'a hir::Expr>,
53 /// Whether the interval is open or closed.
54 pub limits: ast::RangeLimits,
57 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
58 pub fn range<'a, 'b, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'b hir::Expr) -> Option<Range<'b>> {
59 /// Find the field named `name` in the field. Always return `Some` for
61 fn get_field<'a>(name: &str, fields: &'a [hir::Field]) -> Option<&'a hir::Expr> {
62 let expr = &fields.iter().find(|field| field.ident.name == name)?.expr;
68 let def_path = match cx.tables.expr_ty(expr).sty {
69 ty::Adt(def, _) => cx.tcx.def_path(def.did),
73 // sanity checks for std::ops::RangeXXXX
74 if def_path.data.len() != 3 {
77 if def_path.data.get(0)?.data.as_interned_str() != "ops" {
80 if def_path.data.get(1)?.data.as_interned_str() != "range" {
83 let type_name = def_path.data.get(2)?.data.as_interned_str();
92 if !range_types.contains(&&*type_name.as_str()) {
96 // The range syntax is expanded to literal paths starting with `core` or `std`
98 // `#[no_std]`. Testing both instead of resolving the paths.
101 hir::ExprKind::Path(ref path) => {
102 if match_qpath(path, &paths::RANGE_FULL_STD) || match_qpath(path, &paths::RANGE_FULL) {
106 limits: ast::RangeLimits::HalfOpen,
112 hir::ExprKind::Call(ref path, ref args) => if let hir::ExprKind::Path(ref path) = path.node {
113 if match_qpath(path, &paths::RANGE_INCLUSIVE_STD_NEW) || match_qpath(path, &paths::RANGE_INCLUSIVE_NEW) {
115 start: Some(&args[0]),
117 limits: ast::RangeLimits::Closed,
125 hir::ExprKind::Struct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD)
126 || match_qpath(path, &paths::RANGE_FROM)
129 start: Some(get_field("start", fields)?),
131 limits: ast::RangeLimits::HalfOpen,
133 } else if match_qpath(path, &paths::RANGE_STD) || match_qpath(path, &paths::RANGE) {
135 start: Some(get_field("start", fields)?),
136 end: Some(get_field("end", fields)?),
137 limits: ast::RangeLimits::HalfOpen,
139 } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
142 end: Some(get_field("end", fields)?),
143 limits: ast::RangeLimits::Closed,
145 } else if match_qpath(path, &paths::RANGE_TO_STD) || match_qpath(path, &paths::RANGE_TO) {
148 end: Some(get_field("end", fields)?),
149 limits: ast::RangeLimits::HalfOpen,
158 /// Checks if a `let` decl is from a `for` loop desugaring.
159 pub fn is_from_for_desugar(decl: &hir::Decl) -> bool {
160 // This will detect plain for-loops without an actual variable binding:
163 // for x in some_vec {
168 if let hir::DeclKind::Local(ref loc) = decl.node;
169 if let Some(ref expr) = loc.init;
170 if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.node;
176 // This detects a variable binding in for loop to avoid `let_unit_value`
177 // lint (see issue #1964).
180 // for _ in vec![()] {
185 if let hir::DeclKind::Local(ref loc) = decl.node;
186 if let hir::LocalSource::ForLoopDesugar = loc.source;
195 /// Recover the essential nodes of a desugared for loop:
196 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
197 pub fn for_loop(expr: &hir::Expr) -> Option<(&hir::Pat, &hir::Expr, &hir::Expr)> {
199 if let hir::ExprKind::Match(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.node;
200 if let hir::ExprKind::Call(_, ref iterargs) = iterexpr.node;
201 if iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none();
202 if let hir::ExprKind::Loop(ref block, _, _) = arms[0].body.node;
203 if block.expr.is_none();
204 if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
205 if let hir::StmtKind::Decl(ref decl, _) = let_stmt.node;
206 if let hir::DeclKind::Local(ref decl) = decl.node;
207 if let hir::StmtKind::Expr(ref expr, _) = body.node;
209 return Some((&*decl.pat, &iterargs[0], expr));
215 /// Represent the pre-expansion arguments of a `vec!` invocation.
216 pub enum VecArgs<'a> {
217 /// `vec![elem; len]`
218 Repeat(&'a hir::Expr, &'a hir::Expr),
220 Vec(&'a [hir::Expr]),
223 /// Returns the arguments of the `vec!` macro if this expression was expanded
225 pub fn vec_macro<'e>(cx: &LateContext<'_, '_>, expr: &'e hir::Expr) -> Option<VecArgs<'e>> {
227 if let hir::ExprKind::Call(ref fun, ref args) = expr.node;
228 if let hir::ExprKind::Path(ref path) = fun.node;
229 if is_expn_of(fun.span, "vec").is_some();
230 if let Some(fun_def_id) = opt_def_id(resolve_node(cx, path, fun.hir_id));
232 return if match_def_path(cx.tcx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
233 // `vec![elem; size]` case
234 Some(VecArgs::Repeat(&args[0], &args[1]))
236 else if match_def_path(cx.tcx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
237 // `vec![a, b, c]` case
239 if let hir::ExprKind::Box(ref boxed) = args[0].node;
240 if let hir::ExprKind::Array(ref args) = boxed.node;
242 return Some(VecArgs::Vec(&*args));