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 mut iter = cx.tcx.hir().parent_iter(expr.hir_id);
109 if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
113 kind: ExprKind::Loop(_, _, LoopSource::While, _),
118 // while loop desugar
133 /// An `if let` or `match` expression. Useful for lints that trigger on one or the other.
134 pub enum IfLetOrMatch<'hir> {
135 /// Any `match` expression
136 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
137 /// scrutinee, pattern, then block, else block
142 Option<&'hir Expr<'hir>>,
146 impl<'hir> IfLetOrMatch<'hir> {
147 /// Parses an `if let` or `match` expression
148 pub fn parse(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
150 ExprKind::Match(expr, arms, source) => Some(Self::Match(expr, arms, source)),
151 _ => IfLet::hir(cx, expr).map(
157 }| { Self::IfLet(let_expr, let_pat, if_then, if_else) },
163 /// An `if` or `if let` expression
164 pub struct IfOrIfLet<'hir> {
165 /// `if` condition that is maybe a `let` expression
166 pub cond: &'hir Expr<'hir>,
167 /// `if` then expression
168 pub then: &'hir Expr<'hir>,
169 /// `else` expression
170 pub r#else: Option<&'hir Expr<'hir>>,
173 impl<'hir> IfOrIfLet<'hir> {
175 /// Parses an `if` or `if let` expression
176 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
177 if let ExprKind::If(cond, then, r#else) = expr.kind {
178 if let ExprKind::DropTemps(new_cond) = cond.kind {
185 if let ExprKind::Let(..) = cond.kind {
186 return Some(Self { cond, then, r#else });
193 /// Represent a range akin to `ast::ExprKind::Range`.
194 #[derive(Debug, Copy, Clone)]
195 pub struct Range<'a> {
196 /// The lower bound of the range, or `None` for ranges such as `..X`.
197 pub start: Option<&'a hir::Expr<'a>>,
198 /// The upper bound of the range, or `None` for ranges such as `X..`.
199 pub end: Option<&'a hir::Expr<'a>>,
200 /// Whether the interval is open or closed.
201 pub limits: ast::RangeLimits,
205 /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
206 pub fn hir(expr: &'a hir::Expr<'_>) -> Option<Range<'a>> {
207 /// Finds the field named `name` in the field. Always return `Some` for
209 fn get_field<'c>(name: &str, fields: &'c [hir::ExprField<'_>]) -> Option<&'c hir::Expr<'c>> {
210 let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
215 hir::ExprKind::Call(path, args)
218 hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
222 start: Some(&args[0]),
224 limits: ast::RangeLimits::Closed,
227 hir::ExprKind::Struct(path, fields, None) => match &path {
228 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
231 limits: ast::RangeLimits::HalfOpen,
233 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
234 start: Some(get_field("start", fields)?),
236 limits: ast::RangeLimits::HalfOpen,
238 hir::QPath::LangItem(hir::LangItem::Range, _) => Some(Range {
239 start: Some(get_field("start", fields)?),
240 end: Some(get_field("end", fields)?),
241 limits: ast::RangeLimits::HalfOpen,
243 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
245 end: Some(get_field("end", fields)?),
246 limits: ast::RangeLimits::Closed,
248 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
250 end: Some(get_field("end", fields)?),
251 limits: ast::RangeLimits::HalfOpen,
260 /// Represent the pre-expansion arguments of a `vec!` invocation.
261 pub enum VecArgs<'a> {
262 /// `vec![elem; len]`
263 Repeat(&'a hir::Expr<'a>, &'a hir::Expr<'a>),
265 Vec(&'a [hir::Expr<'a>]),
268 impl<'a> VecArgs<'a> {
269 /// Returns the arguments of the `vec!` macro if this expression was expanded
271 pub fn hir(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<VecArgs<'a>> {
273 if let hir::ExprKind::Call(fun, args) = expr.kind;
274 if let hir::ExprKind::Path(ref qpath) = fun.kind;
275 if is_expn_of(fun.span, "vec").is_some();
276 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
278 return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
279 // `vec![elem; size]` case
280 Some(VecArgs::Repeat(&args[0], &args[1]))
282 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
283 // `vec![a, b, c]` case
285 if let hir::ExprKind::Box(boxed) = args[0].kind;
286 if let hir::ExprKind::Array(args) = boxed.kind;
288 return Some(VecArgs::Vec(args));
294 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
295 Some(VecArgs::Vec(&[]))
307 /// A desugared `while` loop
308 pub struct While<'hir> {
309 /// `while` loop condition
310 pub condition: &'hir Expr<'hir>,
311 /// `while` loop body
312 pub body: &'hir Expr<'hir>,
315 impl<'hir> While<'hir> {
317 /// Parses a desugared `while` loop
318 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
319 if let ExprKind::Loop(
326 kind: ExprKind::DropTemps(condition),
341 return Some(Self { condition, body });
347 /// A desugared `while let` loop
348 pub struct WhileLet<'hir> {
349 /// `while let` loop item pattern
350 pub let_pat: &'hir Pat<'hir>,
351 /// `while let` loop scrutinee
352 pub let_expr: &'hir Expr<'hir>,
353 /// `while let` loop body
354 pub if_then: &'hir Expr<'hir>,
357 impl<'hir> WhileLet<'hir> {
359 /// Parses a desugared `while let` loop
360 pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
361 if let ExprKind::Loop(
368 kind: ExprKind::Let(let_pat, let_expr, _),
393 /// Converts a hir binary operator to the corresponding `ast` type.
395 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
397 hir::BinOpKind::Eq => ast::BinOpKind::Eq,
398 hir::BinOpKind::Ge => ast::BinOpKind::Ge,
399 hir::BinOpKind::Gt => ast::BinOpKind::Gt,
400 hir::BinOpKind::Le => ast::BinOpKind::Le,
401 hir::BinOpKind::Lt => ast::BinOpKind::Lt,
402 hir::BinOpKind::Ne => ast::BinOpKind::Ne,
403 hir::BinOpKind::Or => ast::BinOpKind::Or,
404 hir::BinOpKind::Add => ast::BinOpKind::Add,
405 hir::BinOpKind::And => ast::BinOpKind::And,
406 hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
407 hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
408 hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
409 hir::BinOpKind::Div => ast::BinOpKind::Div,
410 hir::BinOpKind::Mul => ast::BinOpKind::Mul,
411 hir::BinOpKind::Rem => ast::BinOpKind::Rem,
412 hir::BinOpKind::Shl => ast::BinOpKind::Shl,
413 hir::BinOpKind::Shr => ast::BinOpKind::Shr,
414 hir::BinOpKind::Sub => ast::BinOpKind::Sub,
418 /// Extract args from an assert-like macro.
419 /// Currently working with:
420 /// - `assert!`, `assert_eq!` and `assert_ne!`
421 /// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
423 /// `assert!(expr)` will return `Some([expr])`
424 /// `debug_assert_eq!(a, b)` will return `Some([a, b])`
425 pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
426 /// Try to match the AST for a pattern that contains a match, for example when two args are
428 fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
430 if let ExprKind::Match(headerexpr, _, _) = &matchblock_expr.kind;
431 if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
432 if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
433 if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
435 return Some(vec![lhs, rhs]);
441 if let ExprKind::Block(block, _) = e.kind {
442 if block.stmts.len() == 1 {
443 if let StmtKind::Semi(matchexpr) = block.stmts.get(0)?.kind {
444 // macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
446 if let Some(If { cond, .. }) = If::hir(matchexpr);
447 if let ExprKind::Unary(UnOp::Not, condition) = cond.kind;
449 return Some(vec![condition]);
453 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
455 if let ExprKind::Block(matchblock,_) = matchexpr.kind;
456 if let Some(matchblock_expr) = matchblock.expr;
458 return ast_matchblock(matchblock_expr);
462 } else if let Some(matchblock_expr) = block.expr {
463 // macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
464 return ast_matchblock(matchblock_expr);
470 /// A parsed `format!` expansion
471 pub struct FormatExpn<'tcx> {
472 /// Span of `format!(..)`
474 /// Inner `format_args!` expansion
475 pub format_args: FormatArgsExpn<'tcx>,
478 impl FormatExpn<'tcx> {
479 /// Parses an expanded `format!` invocation
480 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
482 if let ExprKind::Block(block, _) = expr.kind;
483 if let [stmt] = block.stmts;
484 if let StmtKind::Local(local) = stmt.kind;
485 if let Some(init) = local.init;
486 if let ExprKind::Call(_, [format_args]) = init.kind;
487 let expn_data = expr.span.ctxt().outer_expn_data();
488 if let ExpnKind::Macro(_, sym::format) = expn_data.kind;
489 if let Some(format_args) = FormatArgsExpn::parse(format_args);
492 call_site: expn_data.call_site,
502 /// A parsed `format_args!` expansion
503 pub struct FormatArgsExpn<'tcx> {
504 /// Span of the first argument, the format string
505 pub format_string_span: Span,
506 /// Values passed after the format string
507 pub value_args: Vec<&'tcx Expr<'tcx>>,
509 /// String literal expressions which represent the format string split by "{}"
510 pub format_string_parts: &'tcx [Expr<'tcx>],
511 /// Symbols corresponding to [`Self::format_string_parts`]
512 pub format_string_symbols: Vec<Symbol>,
513 /// Expressions like `ArgumentV1::new(arg0, Debug::fmt)`
514 pub args: &'tcx [Expr<'tcx>],
515 /// The final argument passed to `Arguments::new_v1_formatted`, if applicable
516 pub fmt_expr: Option<&'tcx Expr<'tcx>>,
519 impl FormatArgsExpn<'tcx> {
520 /// Parses an expanded `format_args!` or `format_args_nl!` invocation
521 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
523 if let ExpnKind::Macro(_, name) = expr.span.ctxt().outer_expn_data().kind;
524 let name = name.as_str();
525 if name.ends_with("format_args") || name.ends_with("format_args_nl");
526 if let ExprKind::Call(_, args) = expr.kind;
527 if let Some((strs_ref, args, fmt_expr)) = match args {
529 [strs_ref, args] => Some((strs_ref, args, None)),
530 // Arguments::new_v1_formatted
531 [strs_ref, args, fmt_expr, _unsafe_arg] => Some((strs_ref, args, Some(fmt_expr))),
534 if let ExprKind::AddrOf(BorrowKind::Ref, _, strs_arr) = strs_ref.kind;
535 if let ExprKind::Array(format_string_parts) = strs_arr.kind;
536 if let Some(format_string_symbols) = format_string_parts
539 if let ExprKind::Lit(lit) = &e.kind {
540 if let LitKind::Str(symbol, _style) = lit.node {
547 if let ExprKind::AddrOf(BorrowKind::Ref, _, args) = args.kind;
548 if let ExprKind::Match(args, [arm], _) = args.kind;
549 if let ExprKind::Tup(value_args) = args.kind;
550 if let Some(value_args) = value_args
552 .map(|e| match e.kind {
553 ExprKind::AddrOf(_, _, e) => Some(e),
557 if let ExprKind::Array(args) = arm.body.kind;
559 Some(FormatArgsExpn {
560 format_string_span: strs_ref.span,
563 format_string_symbols,
574 /// Checks if a `let` statement is from a `for` loop desugaring.
575 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
576 // This will detect plain for-loops without an actual variable binding:
579 // for x in some_vec {
584 if let Some(expr) = local.init;
585 if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
591 // This detects a variable binding in for loop to avoid `let_unit_value`
592 // lint (see issue #1964).
595 // for _ in vec![()] {
599 if let hir::LocalSource::ForLoopDesugar = local.source {
606 /// A parsed `panic!` expansion
607 pub struct PanicExpn<'tcx> {
608 /// Span of `panic!(..)`
610 /// Inner `format_args!` expansion
611 pub format_args: FormatArgsExpn<'tcx>,
614 impl PanicExpn<'tcx> {
615 /// Parses an expanded `panic!` invocation
616 pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
618 if let ExprKind::Block(block, _) = expr.kind;
619 if let Some(init) = block.expr;
620 if let ExprKind::Call(_, [format_args]) = init.kind;
621 let expn_data = expr.span.ctxt().outer_expn_data();
622 if let Some(format_args) = FormatArgsExpn::parse(format_args);
625 call_site: expn_data.call_site,