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::{Arm, Block, BorrowKind, Expr, ExprKind, LoopSource, MatchSource, 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> {
17 pub pat: &'tcx hir::Pat<'tcx>,
18 /// `IntoIterator` argument
19 pub arg: &'tcx hir::Expr<'tcx>,
21 pub body: &'tcx hir::Expr<'tcx>,
22 /// entire `for` loop span
26 impl<'tcx> ForLoop<'tcx> {
28 /// Parses a desugared `for` loop
29 pub fn hir(expr: &Expr<'tcx>) -> Option<Self> {
31 if let hir::ExprKind::Match(iterexpr, arms, hir::MatchSource::ForLoopDesugar) = expr.kind;
32 if let Some(first_arm) = arms.get(0);
33 if let hir::ExprKind::Call(_, iterargs) = iterexpr.kind;
34 if let Some(first_arg) = iterargs.get(0);
35 if iterargs.len() == 1 && arms.len() == 1 && first_arm.guard.is_none();
36 if let hir::ExprKind::Loop(block, ..) = first_arm.body.kind;
37 if block.expr.is_none();
38 if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
39 if let hir::StmtKind::Local(local) = let_stmt.kind;
40 if let hir::StmtKind::Expr(body_expr) = body.kind;
54 /// An `if` expression without `DropTemps`
57 pub cond: &'hir Expr<'hir>,
58 /// `if` then expression
59 pub then: &'hir Expr<'hir>,
61 pub r#else: Option<&'hir Expr<'hir>>,
66 /// Parses an `if` expression
67 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
70 kind: ExprKind::DropTemps(cond),
77 Some(Self { cond, then, r#else })
84 /// An `if let` expression
85 pub struct IfLet<'hir> {
87 pub let_pat: &'hir Pat<'hir>,
88 /// `if let` scrutinee
89 pub let_expr: &'hir Expr<'hir>,
90 /// `if let` then expression
91 pub if_then: &'hir Expr<'hir>,
92 /// `if let` else expression
93 pub if_else: Option<&'hir Expr<'hir>>,
96 impl<'hir> IfLet<'hir> {
97 /// Parses an `if let` expression
98 pub fn hir(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
101 kind: ExprKind::Let(let_pat, let_expr, _),
108 let hir = cx.tcx.hir();
109 let mut iter = hir.parent_iter(expr.hir_id);
110 if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
114 kind: ExprKind::Loop(_, _, LoopSource::While, _),
119 // while loop desugar
134 /// An `if let` or `match` expression. Useful for lints that trigger on one or the other.
135 pub enum IfLetOrMatch<'hir> {
136 /// Any `match` expression
137 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
138 /// scrutinee, pattern, then block, else block
143 Option<&'hir Expr<'hir>>,
147 impl<'hir> IfLetOrMatch<'hir> {
148 /// Parses an `if let` or `match` expression
149 pub fn parse(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
151 ExprKind::Match(expr, arms, source) => Some(Self::Match(expr, arms, source)),
152 _ => IfLet::hir(cx, expr).map(
158 }| { Self::IfLet(let_expr, let_pat, if_then, if_else) },
164 /// An `if` or `if let` expression
165 pub struct IfOrIfLet<'hir> {
166 /// `if` condition that is maybe a `let` expression
167 pub cond: &'hir Expr<'hir>,
168 /// `if` then expression
169 pub then: &'hir Expr<'hir>,
170 /// `else` expression
171 pub r#else: Option<&'hir Expr<'hir>>,
174 impl<'hir> IfOrIfLet<'hir> {
176 /// Parses an `if` or `if let` expression
177 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
178 if let ExprKind::If(cond, then, r#else) = expr.kind {
179 if let ExprKind::DropTemps(new_cond) = cond.kind {
186 if let ExprKind::Let(..) = cond.kind {
187 return Some(Self { cond, then, r#else });
194 /// Represent a range akin to `ast::ExprKind::Range`.
195 #[derive(Debug, Copy, Clone)]
196 pub struct Range<'a> {
197 /// The lower bound of the range, or `None` for ranges such as `..X`.
198 pub start: Option<&'a hir::Expr<'a>>,
199 /// The upper bound of the range, or `None` for ranges such as `X..`.
200 pub end: Option<&'a hir::Expr<'a>>,
201 /// Whether the interval is open or closed.
202 pub limits: ast::RangeLimits,
206 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
207 pub fn hir(expr: &'a hir::Expr<'_>) -> Option<Range<'a>> {
208 /// Finds the field named `name` in the field. Always return `Some` for
210 fn get_field<'c>(name: &str, fields: &'c [hir::ExprField<'_>]) -> Option<&'c hir::Expr<'c>> {
211 let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
216 hir::ExprKind::Call(path, args)
219 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
223 start: Some(&args[0]),
225 limits: ast::RangeLimits::Closed,
228 hir::ExprKind::Struct(path, fields, None) => match &path {
229 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
232 limits: ast::RangeLimits::HalfOpen,
234 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
235 start: Some(get_field("start", fields)?),
237 limits: ast::RangeLimits::HalfOpen,
239 hir::QPath::LangItem(hir::LangItem::Range, _) => Some(Range {
240 start: Some(get_field("start", fields)?),
241 end: Some(get_field("end", fields)?),
242 limits: ast::RangeLimits::HalfOpen,
244 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
246 end: Some(get_field("end", fields)?),
247 limits: ast::RangeLimits::Closed,
249 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
251 end: Some(get_field("end", fields)?),
252 limits: ast::RangeLimits::HalfOpen,
261 /// Represent the pre-expansion arguments of a `vec!` invocation.
262 pub enum VecArgs<'a> {
263 /// `vec![elem; len]`
264 Repeat(&'a hir::Expr<'a>, &'a hir::Expr<'a>),
266 Vec(&'a [hir::Expr<'a>]),
269 impl<'a> VecArgs<'a> {
270 /// Returns the arguments of the `vec!` macro if this expression was expanded
272 pub fn hir(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<VecArgs<'a>> {
274 if let hir::ExprKind::Call(fun, args) = expr.kind;
275 if let hir::ExprKind::Path(ref qpath) = fun.kind;
276 if is_expn_of(fun.span, "vec").is_some();
277 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
279 return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
280 // `vec![elem; size]` case
281 Some(VecArgs::Repeat(&args[0], &args[1]))
283 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
284 // `vec![a, b, c]` case
286 if let hir::ExprKind::Box(boxed) = args[0].kind;
287 if let hir::ExprKind::Array(args) = boxed.kind;
289 return Some(VecArgs::Vec(args));
295 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
296 Some(VecArgs::Vec(&[]))
308 /// A desugared `while` loop
309 pub struct While<'hir> {
310 /// `while` loop condition
311 pub condition: &'hir Expr<'hir>,
312 /// `while` loop body
313 pub body: &'hir Expr<'hir>,
316 impl<'hir> While<'hir> {
318 /// Parses a desugared `while` loop
319 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
320 if let ExprKind::Loop(
327 kind: ExprKind::DropTemps(condition),
342 return Some(Self { condition, body });
348 /// A desugared `while let` loop
349 pub struct WhileLet<'hir> {
350 /// `while let` loop item pattern
351 pub let_pat: &'hir Pat<'hir>,
352 /// `while let` loop scrutinee
353 pub let_expr: &'hir Expr<'hir>,
354 /// `while let` loop body
355 pub if_then: &'hir Expr<'hir>,
358 impl<'hir> WhileLet<'hir> {
360 /// Parses a desugared `while let` loop
361 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
362 if let ExprKind::Loop(
369 kind: ExprKind::Let(let_pat, let_expr, _),
394 /// Converts a hir binary operator to the corresponding `ast` type.
396 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
398 hir::BinOpKind::Eq => ast::BinOpKind::Eq,
399 hir::BinOpKind::Ge => ast::BinOpKind::Ge,
400 hir::BinOpKind::Gt => ast::BinOpKind::Gt,
401 hir::BinOpKind::Le => ast::BinOpKind::Le,
402 hir::BinOpKind::Lt => ast::BinOpKind::Lt,
403 hir::BinOpKind::Ne => ast::BinOpKind::Ne,
404 hir::BinOpKind::Or => ast::BinOpKind::Or,
405 hir::BinOpKind::Add => ast::BinOpKind::Add,
406 hir::BinOpKind::And => ast::BinOpKind::And,
407 hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
408 hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
409 hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
410 hir::BinOpKind::Div => ast::BinOpKind::Div,
411 hir::BinOpKind::Mul => ast::BinOpKind::Mul,
412 hir::BinOpKind::Rem => ast::BinOpKind::Rem,
413 hir::BinOpKind::Shl => ast::BinOpKind::Shl,
414 hir::BinOpKind::Shr => ast::BinOpKind::Shr,
415 hir::BinOpKind::Sub => ast::BinOpKind::Sub,
419 /// Extract args from an assert-like macro.
420 /// Currently working with:
421 /// - `assert!`, `assert_eq!` and `assert_ne!`
422 /// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
424 /// `assert!(expr)` will return `Some([expr])`
425 /// `debug_assert_eq!(a, b)` will return `Some([a, b])`
426 pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
427 /// Try to match the AST for a pattern that contains a match, for example when two args are
429 fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
431 if let ExprKind::Match(headerexpr, _, _) = &matchblock_expr.kind;
432 if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
433 if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
434 if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
436 return Some(vec![lhs, rhs]);
442 if let ExprKind::Block(block, _) = e.kind {
443 if block.stmts.len() == 1 {
444 if let StmtKind::Semi(matchexpr) = block.stmts.get(0)?.kind {
445 // macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
447 if let Some(If { cond, .. }) = If::hir(matchexpr);
448 if let ExprKind::Unary(UnOp::Not, condition) = cond.kind;
450 return Some(vec![condition]);
454 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
456 if let ExprKind::Block(matchblock,_) = matchexpr.kind;
457 if let Some(matchblock_expr) = matchblock.expr;
459 return ast_matchblock(matchblock_expr);
463 } else if let Some(matchblock_expr) = block.expr {
464 // macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
465 return ast_matchblock(matchblock_expr);
471 /// A parsed `format!` expansion
472 pub struct FormatExpn<'tcx> {
473 /// Span of `format!(..)`
475 /// Inner `format_args!` expansion
476 pub format_args: FormatArgsExpn<'tcx>,
479 impl FormatExpn<'tcx> {
480 /// Parses an expanded `format!` invocation
481 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
483 if let ExprKind::Block(block, _) = expr.kind;
484 if let [stmt] = block.stmts;
485 if let StmtKind::Local(local) = stmt.kind;
486 if let Some(init) = local.init;
487 if let ExprKind::Call(_, [format_args]) = init.kind;
488 let expn_data = expr.span.ctxt().outer_expn_data();
489 if let ExpnKind::Macro(_, sym::format) = expn_data.kind;
490 if let Some(format_args) = FormatArgsExpn::parse(format_args);
493 call_site: expn_data.call_site,
503 /// A parsed `format_args!` expansion
504 pub struct FormatArgsExpn<'tcx> {
505 /// Span of the first argument, the format string
506 pub format_string_span: Span,
507 /// Values passed after the format string
508 pub value_args: Vec<&'tcx Expr<'tcx>>,
510 /// String literal expressions which represent the format string split by "{}"
511 pub format_string_parts: &'tcx [Expr<'tcx>],
512 /// Symbols corresponding to [`Self::format_string_parts`]
513 pub format_string_symbols: Vec<Symbol>,
514 /// Expressions like `ArgumentV1::new(arg0, Debug::fmt)`
515 pub args: &'tcx [Expr<'tcx>],
516 /// The final argument passed to `Arguments::new_v1_formatted`, if applicable
517 pub fmt_expr: Option<&'tcx Expr<'tcx>>,
520 impl FormatArgsExpn<'tcx> {
521 /// Parses an expanded `format_args!` or `format_args_nl!` invocation
522 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
524 if let ExpnKind::Macro(_, name) = expr.span.ctxt().outer_expn_data().kind;
525 let name = name.as_str();
526 if name.ends_with("format_args") || name.ends_with("format_args_nl");
528 if let ExprKind::Match(inner_match, [arm], _) = expr.kind;
530 // `match match`, if you will
531 if let ExprKind::Match(args, [inner_arm], _) = inner_match.kind;
532 if let ExprKind::Tup(value_args) = args.kind;
533 if let Some(value_args) = value_args
535 .map(|e| match e.kind {
536 ExprKind::AddrOf(_, _, e) => Some(e),
540 if let ExprKind::Array(args) = inner_arm.body.kind;
542 if let ExprKind::Block(Block { stmts: [], expr: Some(expr), .. }, _) = arm.body.kind;
543 if let ExprKind::Call(_, call_args) = expr.kind;
544 if let Some((strs_ref, fmt_expr)) = match call_args {
546 [strs_ref, _] => Some((strs_ref, None)),
547 // Arguments::new_v1_formatted
548 [strs_ref, _, fmt_expr] => Some((strs_ref, Some(fmt_expr))),
551 if let ExprKind::AddrOf(BorrowKind::Ref, _, strs_arr) = strs_ref.kind;
552 if let ExprKind::Array(format_string_parts) = strs_arr.kind;
553 if let Some(format_string_symbols) = format_string_parts
556 if let ExprKind::Lit(lit) = &e.kind {
557 if let LitKind::Str(symbol, _style) = lit.node {
565 Some(FormatArgsExpn {
566 format_string_span: strs_ref.span,
569 format_string_symbols,
580 /// Checks if a `let` statement is from a `for` loop desugaring.
581 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
582 // This will detect plain for-loops without an actual variable binding:
585 // for x in some_vec {
590 if let Some(expr) = local.init;
591 if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
597 // This detects a variable binding in for loop to avoid `let_unit_value`
598 // lint (see issue #1964).
601 // for _ in vec![()] {
605 if let hir::LocalSource::ForLoopDesugar = local.source {
612 /// A parsed `panic!` expansion
613 pub struct PanicExpn<'tcx> {
614 /// Span of `panic!(..)`
616 /// Inner `format_args!` expansion
617 pub format_args: FormatArgsExpn<'tcx>,
620 impl PanicExpn<'tcx> {
621 /// Parses an expanded `panic!` invocation
622 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
624 if let ExprKind::Block(block, _) = expr.kind;
625 if let Some(init) = block.expr;
626 if let ExprKind::Call(_, [format_args]) = init.kind;
627 let expn_data = expr.span.ctxt().outer_expn_data();
628 if let ExprKind::AddrOf(_, _, format_args) = format_args.kind;
629 if let Some(format_args) = FormatArgsExpn::parse(format_args);
632 call_site: expn_data.call_site,