1 //! This module contains functions that retrieves specifiec elements.
3 #![deny(clippy::missing_docs_in_private_items)]
5 use crate::{is_expn_of, match_def_path, paths};
6 use if_chain::if_chain;
7 use rustc_ast::ast::{self, LitKind};
9 use rustc_hir::{Block, BorrowKind, Expr, ExprKind, LoopSource, Node, Pat, StmtKind, UnOp};
10 use rustc_lint::LateContext;
11 use rustc_span::{sym, ExpnKind, Span, Symbol};
13 /// The essential nodes of a desugared for loop as well as the entire span:
14 /// `for pat in arg { body }` becomes `(pat, arg, body)`. Return `(pat, arg, body, span)`.
15 pub struct ForLoop<'tcx> {
16 pub pat: &'tcx hir::Pat<'tcx>,
17 pub arg: &'tcx hir::Expr<'tcx>,
18 pub body: &'tcx hir::Expr<'tcx>,
22 impl<'tcx> ForLoop<'tcx> {
24 pub fn hir(expr: &Expr<'tcx>) -> Option<Self> {
26 if let hir::ExprKind::Match(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.kind;
27 if let Some(first_arm) = arms.get(0);
28 if let hir::ExprKind::Call(_, ref iterargs) = iterexpr.kind;
29 if let Some(first_arg) = iterargs.get(0);
30 if iterargs.len() == 1 && arms.len() == 1 && first_arm.guard.is_none();
31 if let hir::ExprKind::Loop(ref block, ..) = first_arm.body.kind;
32 if block.expr.is_none();
33 if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
34 if let hir::StmtKind::Local(ref local) = let_stmt.kind;
35 if let hir::StmtKind::Expr(ref body_expr) = body.kind;
50 pub cond: &'hir Expr<'hir>,
51 pub r#else: Option<&'hir Expr<'hir>>,
52 pub then: &'hir Expr<'hir>,
57 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
60 kind: ExprKind::DropTemps(cond),
67 Some(Self { cond, r#else, then })
74 pub struct IfLet<'hir> {
75 pub let_pat: &'hir Pat<'hir>,
76 pub let_expr: &'hir Expr<'hir>,
77 pub if_then: &'hir Expr<'hir>,
78 pub if_else: Option<&'hir Expr<'hir>>,
81 impl<'hir> IfLet<'hir> {
82 pub fn hir(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
85 kind: ExprKind::Let(let_pat, let_expr, _),
92 let hir = cx.tcx.hir();
93 let mut iter = hir.parent_iter(expr.hir_id);
94 if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
98 kind: ExprKind::Loop(_, _, LoopSource::While, _),
103 // while loop desugar
118 pub struct IfOrIfLet<'hir> {
119 pub cond: &'hir Expr<'hir>,
120 pub r#else: Option<&'hir Expr<'hir>>,
121 pub then: &'hir Expr<'hir>,
124 impl<'hir> IfOrIfLet<'hir> {
126 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
127 if let ExprKind::If(cond, then, r#else) = expr.kind {
128 if let ExprKind::DropTemps(new_cond) = cond.kind {
135 if let ExprKind::Let(..) = cond.kind {
136 return Some(Self { cond, r#else, then });
143 /// Represent a range akin to `ast::ExprKind::Range`.
144 #[derive(Debug, Copy, Clone)]
145 pub struct Range<'a> {
146 /// The lower bound of the range, or `None` for ranges such as `..X`.
147 pub start: Option<&'a hir::Expr<'a>>,
148 /// The upper bound of the range, or `None` for ranges such as `X..`.
149 pub end: Option<&'a hir::Expr<'a>>,
150 /// Whether the interval is open or closed.
151 pub limits: ast::RangeLimits,
155 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
156 pub fn hir(expr: &'a hir::Expr<'_>) -> Option<Range<'a>> {
157 /// Finds the field named `name` in the field. Always return `Some` for
159 fn get_field<'c>(name: &str, fields: &'c [hir::ExprField<'_>]) -> Option<&'c hir::Expr<'c>> {
160 let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
165 hir::ExprKind::Call(ref path, ref args)
168 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
172 start: Some(&args[0]),
174 limits: ast::RangeLimits::Closed,
177 hir::ExprKind::Struct(ref path, ref fields, None) => match path {
178 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
181 limits: ast::RangeLimits::HalfOpen,
183 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
184 start: Some(get_field("start", fields)?),
186 limits: ast::RangeLimits::HalfOpen,
188 hir::QPath::LangItem(hir::LangItem::Range, _) => Some(Range {
189 start: Some(get_field("start", fields)?),
190 end: Some(get_field("end", fields)?),
191 limits: ast::RangeLimits::HalfOpen,
193 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
195 end: Some(get_field("end", fields)?),
196 limits: ast::RangeLimits::Closed,
198 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
200 end: Some(get_field("end", fields)?),
201 limits: ast::RangeLimits::HalfOpen,
210 /// Represent the pre-expansion arguments of a `vec!` invocation.
211 pub enum VecArgs<'a> {
212 /// `vec![elem; len]`
213 Repeat(&'a hir::Expr<'a>, &'a hir::Expr<'a>),
215 Vec(&'a [hir::Expr<'a>]),
218 impl<'a> VecArgs<'a> {
219 /// Returns the arguments of the `vec!` macro if this expression was expanded
221 pub fn hir(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<VecArgs<'a>> {
223 if let hir::ExprKind::Call(ref fun, ref args) = expr.kind;
224 if let hir::ExprKind::Path(ref qpath) = fun.kind;
225 if is_expn_of(fun.span, "vec").is_some();
226 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
228 return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
229 // `vec![elem; size]` case
230 Some(VecArgs::Repeat(&args[0], &args[1]))
232 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
233 // `vec![a, b, c]` case
235 if let hir::ExprKind::Box(ref boxed) = args[0].kind;
236 if let hir::ExprKind::Array(ref args) = boxed.kind;
238 return Some(VecArgs::Vec(&*args));
244 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
245 Some(VecArgs::Vec(&[]))
257 pub struct While<'hir> {
258 pub if_cond: &'hir Expr<'hir>,
259 pub if_then: &'hir Expr<'hir>,
260 pub if_else: Option<&'hir Expr<'hir>>,
263 impl<'hir> While<'hir> {
265 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
266 if let ExprKind::Loop(
273 kind: ExprKind::DropTemps(if_cond),
288 let if_else = *if_else_ref;
299 pub struct WhileLet<'hir> {
300 pub if_expr: &'hir Expr<'hir>,
301 pub let_pat: &'hir Pat<'hir>,
302 pub let_expr: &'hir Expr<'hir>,
303 pub if_then: &'hir Expr<'hir>,
304 pub if_else: Option<&'hir Expr<'hir>>,
307 impl<'hir> WhileLet<'hir> {
309 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
310 if let ExprKind::Loop(
312 expr: Some(if_expr), ..
323 kind: ExprKind::Let(let_pat, let_expr, _),
332 let if_else = *if_else_ref;
346 /// Converts a hir binary operator to the corresponding `ast` type.
348 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
350 hir::BinOpKind::Eq => ast::BinOpKind::Eq,
351 hir::BinOpKind::Ge => ast::BinOpKind::Ge,
352 hir::BinOpKind::Gt => ast::BinOpKind::Gt,
353 hir::BinOpKind::Le => ast::BinOpKind::Le,
354 hir::BinOpKind::Lt => ast::BinOpKind::Lt,
355 hir::BinOpKind::Ne => ast::BinOpKind::Ne,
356 hir::BinOpKind::Or => ast::BinOpKind::Or,
357 hir::BinOpKind::Add => ast::BinOpKind::Add,
358 hir::BinOpKind::And => ast::BinOpKind::And,
359 hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
360 hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
361 hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
362 hir::BinOpKind::Div => ast::BinOpKind::Div,
363 hir::BinOpKind::Mul => ast::BinOpKind::Mul,
364 hir::BinOpKind::Rem => ast::BinOpKind::Rem,
365 hir::BinOpKind::Shl => ast::BinOpKind::Shl,
366 hir::BinOpKind::Shr => ast::BinOpKind::Shr,
367 hir::BinOpKind::Sub => ast::BinOpKind::Sub,
371 /// Extract args from an assert-like macro.
372 /// Currently working with:
373 /// - `assert!`, `assert_eq!` and `assert_ne!`
374 /// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
376 /// `assert!(expr)` will return `Some([expr])`
377 /// `debug_assert_eq!(a, b)` will return `Some([a, b])`
378 pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
379 /// Try to match the AST for a pattern that contains a match, for example when two args are
381 fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
383 if let ExprKind::Match(headerexpr, _, _) = &matchblock_expr.kind;
384 if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
385 if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
386 if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
388 return Some(vec![lhs, rhs]);
394 if let ExprKind::Block(block, _) = e.kind {
395 if block.stmts.len() == 1 {
396 if let StmtKind::Semi(matchexpr) = block.stmts.get(0)?.kind {
397 // macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
399 if let Some(If { cond, .. }) = If::hir(matchexpr);
400 if let ExprKind::Unary(UnOp::Not, condition) = cond.kind;
402 return Some(vec![condition]);
406 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
408 if let ExprKind::Block(matchblock,_) = matchexpr.kind;
409 if let Some(matchblock_expr) = matchblock.expr;
411 return ast_matchblock(matchblock_expr);
415 } else if let Some(matchblock_expr) = block.expr {
416 // macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
417 return ast_matchblock(matchblock_expr);
423 /// A parsed `format!` expansion
424 pub struct FormatExpn<'tcx> {
425 /// Span of `format!(..)`
427 /// Inner `format_args!` expansion
428 pub format_args: FormatArgsExpn<'tcx>,
431 impl FormatExpn<'tcx> {
432 /// Parses an expanded `format!` invocation
433 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
435 if let ExprKind::Block(block, _) = expr.kind;
436 if let [stmt] = block.stmts;
437 if let StmtKind::Local(local) = stmt.kind;
438 if let Some(init) = local.init;
439 if let ExprKind::Call(_, [format_args]) = init.kind;
440 let expn_data = expr.span.ctxt().outer_expn_data();
441 if let ExpnKind::Macro(_, sym::format) = expn_data.kind;
442 if let Some(format_args) = FormatArgsExpn::parse(format_args);
445 call_site: expn_data.call_site,
455 /// A parsed `format_args!` expansion
456 pub struct FormatArgsExpn<'tcx> {
457 /// Span of the first argument, the format string
458 pub format_string_span: Span,
459 /// Values passed after the format string
460 pub value_args: Vec<&'tcx Expr<'tcx>>,
462 /// String literal expressions which represent the format string split by "{}"
463 pub format_string_parts: &'tcx [Expr<'tcx>],
464 /// Symbols corresponding to [`Self::format_string_parts`]
465 pub format_string_symbols: Vec<Symbol>,
466 /// Expressions like `ArgumentV1::new(arg0, Debug::fmt)`
467 pub args: &'tcx [Expr<'tcx>],
468 /// The final argument passed to `Arguments::new_v1_formatted`, if applicable
469 pub fmt_expr: Option<&'tcx Expr<'tcx>>,
472 impl FormatArgsExpn<'tcx> {
473 /// Parses an expanded `format_args!` or `format_args_nl!` invocation
474 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
476 if let ExpnKind::Macro(_, name) = expr.span.ctxt().outer_expn_data().kind;
477 let name = name.as_str();
478 if name.ends_with("format_args") || name.ends_with("format_args_nl");
480 if let ExprKind::Match(inner_match, [arm], _) = expr.kind;
482 // `match match`, if you will
483 if let ExprKind::Match(args, [inner_arm], _) = inner_match.kind;
484 if let ExprKind::Tup(value_args) = args.kind;
485 if let Some(value_args) = value_args
487 .map(|e| match e.kind {
488 ExprKind::AddrOf(_, _, e) => Some(e),
492 if let ExprKind::Array(args) = inner_arm.body.kind;
494 if let ExprKind::Block(Block { stmts: [], expr: Some(expr), .. }, _) = arm.body.kind;
495 if let ExprKind::Call(_, call_args) = expr.kind;
496 if let Some((strs_ref, fmt_expr)) = match call_args {
498 [strs_ref, _] => Some((strs_ref, None)),
499 // Arguments::new_v1_formatted
500 [strs_ref, _, fmt_expr] => Some((strs_ref, Some(fmt_expr))),
503 if let ExprKind::AddrOf(BorrowKind::Ref, _, strs_arr) = strs_ref.kind;
504 if let ExprKind::Array(format_string_parts) = strs_arr.kind;
505 if let Some(format_string_symbols) = format_string_parts
508 if let ExprKind::Lit(lit) = &e.kind {
509 if let LitKind::Str(symbol, _style) = lit.node {
517 Some(FormatArgsExpn {
518 format_string_span: strs_ref.span,
521 format_string_symbols,
532 /// Checks if a `let` statement is from a `for` loop desugaring.
533 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
534 // This will detect plain for-loops without an actual variable binding:
537 // for x in some_vec {
542 if let Some(ref expr) = local.init;
543 if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
549 // This detects a variable binding in for loop to avoid `let_unit_value`
550 // lint (see issue #1964).
553 // for _ in vec![()] {
557 if let hir::LocalSource::ForLoopDesugar = local.source {