1 //! This module contains functions that retrieves specifiec elements.
3 #![deny(clippy::missing_docs_in_private_items)]
5 use crate::ty::is_type_diagnostic_item;
6 use crate::{is_expn_of, match_def_path, paths};
7 use if_chain::if_chain;
8 use rustc_ast::ast::{self, LitKind};
11 Arm, Block, BorrowKind, Expr, ExprKind, HirId, LoopSource, MatchSource, Node, Pat, QPath, StmtKind, UnOp,
13 use rustc_lint::LateContext;
14 use rustc_span::{sym, symbol, ExpnKind, Span, Symbol};
16 /// The essential nodes of a desugared for loop as well as the entire span:
17 /// `for pat in arg { body }` becomes `(pat, arg, body)`. Return `(pat, arg, body, span)`.
18 pub struct ForLoop<'tcx> {
20 pub pat: &'tcx hir::Pat<'tcx>,
21 /// `IntoIterator` argument
22 pub arg: &'tcx hir::Expr<'tcx>,
24 pub body: &'tcx hir::Expr<'tcx>,
25 /// entire `for` loop span
29 impl<'tcx> ForLoop<'tcx> {
31 /// Parses a desugared `for` loop
32 pub fn hir(expr: &Expr<'tcx>) -> Option<Self> {
34 if let hir::ExprKind::Match(iterexpr, arms, hir::MatchSource::ForLoopDesugar) = expr.kind;
35 if let Some(first_arm) = arms.get(0);
36 if let hir::ExprKind::Call(_, iterargs) = iterexpr.kind;
37 if let Some(first_arg) = iterargs.get(0);
38 if iterargs.len() == 1 && arms.len() == 1 && first_arm.guard.is_none();
39 if let hir::ExprKind::Loop(block, ..) = first_arm.body.kind;
40 if block.expr.is_none();
41 if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
42 if let hir::StmtKind::Local(local) = let_stmt.kind;
43 if let hir::StmtKind::Expr(body_expr) = body.kind;
57 /// An `if` expression without `DropTemps`
60 pub cond: &'hir Expr<'hir>,
61 /// `if` then expression
62 pub then: &'hir Expr<'hir>,
64 pub r#else: Option<&'hir Expr<'hir>>,
69 /// Parses an `if` expression
70 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
73 kind: ExprKind::DropTemps(cond),
80 Some(Self { cond, then, r#else })
87 /// An `if let` expression
88 pub struct IfLet<'hir> {
90 pub let_pat: &'hir Pat<'hir>,
91 /// `if let` scrutinee
92 pub let_expr: &'hir Expr<'hir>,
93 /// `if let` then expression
94 pub if_then: &'hir Expr<'hir>,
95 /// `if let` else expression
96 pub if_else: Option<&'hir Expr<'hir>>,
99 impl<'hir> IfLet<'hir> {
100 /// Parses an `if let` expression
101 pub fn hir(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
104 kind: ExprKind::Let(let_pat, let_expr, _),
111 let mut iter = cx.tcx.hir().parent_iter(expr.hir_id);
112 if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
116 kind: ExprKind::Loop(_, _, LoopSource::While, _),
121 // while loop desugar
136 /// An `if let` or `match` expression. Useful for lints that trigger on one or the other.
137 pub enum IfLetOrMatch<'hir> {
138 /// Any `match` expression
139 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
140 /// scrutinee, pattern, then block, else block
145 Option<&'hir Expr<'hir>>,
149 impl<'hir> IfLetOrMatch<'hir> {
150 /// Parses an `if let` or `match` expression
151 pub fn parse(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
153 ExprKind::Match(expr, arms, source) => Some(Self::Match(expr, arms, source)),
154 _ => IfLet::hir(cx, expr).map(
160 }| { Self::IfLet(let_expr, let_pat, if_then, if_else) },
166 /// An `if` or `if let` expression
167 pub struct IfOrIfLet<'hir> {
168 /// `if` condition that is maybe a `let` expression
169 pub cond: &'hir Expr<'hir>,
170 /// `if` then expression
171 pub then: &'hir Expr<'hir>,
172 /// `else` expression
173 pub r#else: Option<&'hir Expr<'hir>>,
176 impl<'hir> IfOrIfLet<'hir> {
178 /// Parses an `if` or `if let` expression
179 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
180 if let ExprKind::If(cond, then, r#else) = expr.kind {
181 if let ExprKind::DropTemps(new_cond) = cond.kind {
188 if let ExprKind::Let(..) = cond.kind {
189 return Some(Self { cond, then, r#else });
196 /// Represent a range akin to `ast::ExprKind::Range`.
197 #[derive(Debug, Copy, Clone)]
198 pub struct Range<'a> {
199 /// The lower bound of the range, or `None` for ranges such as `..X`.
200 pub start: Option<&'a hir::Expr<'a>>,
201 /// The upper bound of the range, or `None` for ranges such as `X..`.
202 pub end: Option<&'a hir::Expr<'a>>,
203 /// Whether the interval is open or closed.
204 pub limits: ast::RangeLimits,
208 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
209 pub fn hir(expr: &'a hir::Expr<'_>) -> Option<Range<'a>> {
210 /// Finds the field named `name` in the field. Always return `Some` for
212 fn get_field<'c>(name: &str, fields: &'c [hir::ExprField<'_>]) -> Option<&'c hir::Expr<'c>> {
213 let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
218 hir::ExprKind::Call(path, args)
221 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
225 start: Some(&args[0]),
227 limits: ast::RangeLimits::Closed,
230 hir::ExprKind::Struct(path, fields, None) => match &path {
231 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
234 limits: ast::RangeLimits::HalfOpen,
236 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
237 start: Some(get_field("start", fields)?),
239 limits: ast::RangeLimits::HalfOpen,
241 hir::QPath::LangItem(hir::LangItem::Range, _) => Some(Range {
242 start: Some(get_field("start", fields)?),
243 end: Some(get_field("end", fields)?),
244 limits: ast::RangeLimits::HalfOpen,
246 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
248 end: Some(get_field("end", fields)?),
249 limits: ast::RangeLimits::Closed,
251 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
253 end: Some(get_field("end", fields)?),
254 limits: ast::RangeLimits::HalfOpen,
263 /// Represent the pre-expansion arguments of a `vec!` invocation.
264 pub enum VecArgs<'a> {
265 /// `vec![elem; len]`
266 Repeat(&'a hir::Expr<'a>, &'a hir::Expr<'a>),
268 Vec(&'a [hir::Expr<'a>]),
271 impl<'a> VecArgs<'a> {
272 /// Returns the arguments of the `vec!` macro if this expression was expanded
274 pub fn hir(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<VecArgs<'a>> {
276 if let hir::ExprKind::Call(fun, args) = expr.kind;
277 if let hir::ExprKind::Path(ref qpath) = fun.kind;
278 if is_expn_of(fun.span, "vec").is_some();
279 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
281 return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
282 // `vec![elem; size]` case
283 Some(VecArgs::Repeat(&args[0], &args[1]))
285 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
286 // `vec![a, b, c]` case
288 if let hir::ExprKind::Box(boxed) = args[0].kind;
289 if let hir::ExprKind::Array(args) = boxed.kind;
291 return Some(VecArgs::Vec(args));
297 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
298 Some(VecArgs::Vec(&[]))
310 /// A desugared `while` loop
311 pub struct While<'hir> {
312 /// `while` loop condition
313 pub condition: &'hir Expr<'hir>,
314 /// `while` loop body
315 pub body: &'hir Expr<'hir>,
318 impl<'hir> While<'hir> {
320 /// Parses a desugared `while` loop
321 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
322 if let ExprKind::Loop(
329 kind: ExprKind::DropTemps(condition),
344 return Some(Self { condition, body });
350 /// A desugared `while let` loop
351 pub struct WhileLet<'hir> {
352 /// `while let` loop item pattern
353 pub let_pat: &'hir Pat<'hir>,
354 /// `while let` loop scrutinee
355 pub let_expr: &'hir Expr<'hir>,
356 /// `while let` loop body
357 pub if_then: &'hir Expr<'hir>,
360 impl<'hir> WhileLet<'hir> {
362 /// Parses a desugared `while let` loop
363 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
364 if let ExprKind::Loop(
371 kind: ExprKind::Let(let_pat, let_expr, _),
396 /// Converts a hir binary operator to the corresponding `ast` type.
398 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
400 hir::BinOpKind::Eq => ast::BinOpKind::Eq,
401 hir::BinOpKind::Ge => ast::BinOpKind::Ge,
402 hir::BinOpKind::Gt => ast::BinOpKind::Gt,
403 hir::BinOpKind::Le => ast::BinOpKind::Le,
404 hir::BinOpKind::Lt => ast::BinOpKind::Lt,
405 hir::BinOpKind::Ne => ast::BinOpKind::Ne,
406 hir::BinOpKind::Or => ast::BinOpKind::Or,
407 hir::BinOpKind::Add => ast::BinOpKind::Add,
408 hir::BinOpKind::And => ast::BinOpKind::And,
409 hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
410 hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
411 hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
412 hir::BinOpKind::Div => ast::BinOpKind::Div,
413 hir::BinOpKind::Mul => ast::BinOpKind::Mul,
414 hir::BinOpKind::Rem => ast::BinOpKind::Rem,
415 hir::BinOpKind::Shl => ast::BinOpKind::Shl,
416 hir::BinOpKind::Shr => ast::BinOpKind::Shr,
417 hir::BinOpKind::Sub => ast::BinOpKind::Sub,
421 /// Extract args from an assert-like macro.
422 /// Currently working with:
423 /// - `assert!`, `assert_eq!` and `assert_ne!`
424 /// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
426 /// `assert!(expr)` will return `Some([expr])`
427 /// `debug_assert_eq!(a, b)` will return `Some([a, b])`
428 pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
429 /// Try to match the AST for a pattern that contains a match, for example when two args are
431 fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
433 if let ExprKind::Match(headerexpr, _, _) = &matchblock_expr.kind;
434 if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
435 if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
436 if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
438 return Some(vec![lhs, rhs]);
444 if let ExprKind::Block(block, _) = e.kind {
445 if block.stmts.len() == 1 {
446 if let StmtKind::Semi(matchexpr) = block.stmts.get(0)?.kind {
447 // macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
449 if let Some(If { cond, .. }) = If::hir(matchexpr);
450 if let ExprKind::Unary(UnOp::Not, condition) = cond.kind;
452 return Some(vec![condition]);
456 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
458 if let ExprKind::Block(matchblock,_) = matchexpr.kind;
459 if let Some(matchblock_expr) = matchblock.expr;
461 return ast_matchblock(matchblock_expr);
465 } else if let Some(matchblock_expr) = block.expr {
466 // macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
467 return ast_matchblock(matchblock_expr);
473 /// A parsed `format!` expansion
474 pub struct FormatExpn<'tcx> {
475 /// Span of `format!(..)`
477 /// Inner `format_args!` expansion
478 pub format_args: FormatArgsExpn<'tcx>,
481 impl FormatExpn<'tcx> {
482 /// Parses an expanded `format!` invocation
483 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
485 if let ExprKind::Block(block, _) = expr.kind;
486 if let [stmt] = block.stmts;
487 if let StmtKind::Local(local) = stmt.kind;
488 if let Some(init) = local.init;
489 if let ExprKind::Call(_, [format_args]) = init.kind;
490 let expn_data = expr.span.ctxt().outer_expn_data();
491 if let ExpnKind::Macro(_, sym::format) = expn_data.kind;
492 if let Some(format_args) = FormatArgsExpn::parse(format_args);
495 call_site: expn_data.call_site,
505 /// A parsed `format_args!` expansion
506 pub struct FormatArgsExpn<'tcx> {
507 /// Span of the first argument, the format string
508 pub format_string_span: Span,
509 /// Values passed after the format string
510 pub value_args: Vec<&'tcx Expr<'tcx>>,
512 /// String literal expressions which represent the format string split by "{}"
513 pub format_string_parts: &'tcx [Expr<'tcx>],
514 /// Symbols corresponding to [`Self::format_string_parts`]
515 pub format_string_symbols: Vec<Symbol>,
516 /// Expressions like `ArgumentV1::new(arg0, Debug::fmt)`
517 pub args: &'tcx [Expr<'tcx>],
518 /// The final argument passed to `Arguments::new_v1_formatted`, if applicable
519 pub fmt_expr: Option<&'tcx Expr<'tcx>>,
522 impl FormatArgsExpn<'tcx> {
523 /// Parses an expanded `format_args!` or `format_args_nl!` invocation
524 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
526 if let ExpnKind::Macro(_, name) = expr.span.ctxt().outer_expn_data().kind;
527 let name = name.as_str();
528 if name.ends_with("format_args") || name.ends_with("format_args_nl");
529 if let ExprKind::Call(_, args) = expr.kind;
530 if let Some((strs_ref, args, fmt_expr)) = match args {
532 [strs_ref, args] => Some((strs_ref, args, None)),
533 // Arguments::new_v1_formatted
534 [strs_ref, args, fmt_expr, _unsafe_arg] => Some((strs_ref, args, Some(fmt_expr))),
537 if let ExprKind::AddrOf(BorrowKind::Ref, _, strs_arr) = strs_ref.kind;
538 if let ExprKind::Array(format_string_parts) = strs_arr.kind;
539 if let Some(format_string_symbols) = format_string_parts
542 if let ExprKind::Lit(lit) = &e.kind {
543 if let LitKind::Str(symbol, _style) = lit.node {
550 if let ExprKind::AddrOf(BorrowKind::Ref, _, args) = args.kind;
551 if let ExprKind::Match(args, [arm], _) = args.kind;
552 if let ExprKind::Tup(value_args) = args.kind;
553 if let Some(value_args) = value_args
555 .map(|e| match e.kind {
556 ExprKind::AddrOf(_, _, e) => Some(e),
560 if let ExprKind::Array(args) = arm.body.kind;
562 Some(FormatArgsExpn {
563 format_string_span: strs_ref.span,
566 format_string_symbols,
577 /// Checks if a `let` statement is from a `for` loop desugaring.
578 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
579 // This will detect plain for-loops without an actual variable binding:
582 // for x in some_vec {
587 if let Some(expr) = local.init;
588 if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
594 // This detects a variable binding in for loop to avoid `let_unit_value`
595 // lint (see issue #1964).
598 // for _ in vec![()] {
602 if let hir::LocalSource::ForLoopDesugar = local.source {
609 /// A parsed `panic!` expansion
610 pub struct PanicExpn<'tcx> {
611 /// Span of `panic!(..)`
613 /// Inner `format_args!` expansion
614 pub format_args: FormatArgsExpn<'tcx>,
617 impl PanicExpn<'tcx> {
618 /// Parses an expanded `panic!` invocation
619 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
621 if let ExprKind::Block(block, _) = expr.kind;
622 if let Some(init) = block.expr;
623 if let ExprKind::Call(_, [format_args]) = init.kind;
624 let expn_data = expr.span.ctxt().outer_expn_data();
625 if let ExprKind::AddrOf(_, _, format_args) = format_args.kind;
626 if let Some(format_args) = FormatArgsExpn::parse(format_args);
629 call_site: expn_data.call_site,
639 /// A parsed `Vec` initialization expression
640 #[derive(Clone, Copy)]
641 pub enum VecInitKind {
644 /// `Vec::default()` or `Default::default()`
646 /// `Vec::with_capacity(123)`
647 WithLiteralCapacity(u64),
648 /// `Vec::with_capacity(slice.len())`
649 WithExprCapacity(HirId),
652 /// Checks if given expression is an initialization of `Vec` and returns its kind.
653 pub fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<VecInitKind> {
654 if let ExprKind::Call(func, args) = expr.kind {
656 ExprKind::Path(QPath::TypeRelative(ty, name))
657 if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::Vec) =>
659 if name.ident.name == sym::new {
660 return Some(VecInitKind::New);
661 } else if name.ident.name == symbol::kw::Default {
662 return Some(VecInitKind::Default);
663 } else if name.ident.name.as_str() == "with_capacity" {
664 let arg = args.get(0)?;
666 if let ExprKind::Lit(lit) = &arg.kind;
667 if let LitKind::Int(num, _) = lit.node;
669 return Some(VecInitKind::WithLiteralCapacity(num.try_into().ok()?))
672 return Some(VecInitKind::WithExprCapacity(arg.hir_id));
675 ExprKind::Path(QPath::Resolved(_, path))
676 if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD)
677 && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Vec) =>
679 return Some(VecInitKind::Default);