]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/higher.rs
Auto merge of #90700 - fee1-dead:select-returns-vec, r=davidtwco
[rust.git] / clippy_utils / src / higher.rs
1 //! This module contains functions that retrieve specific elements.
2
3 #![deny(clippy::missing_docs_in_private_items)]
4
5 use crate::ty::is_type_diagnostic_item;
6 use crate::{is_expn_of, last_path_segment, match_def_path, paths};
7 use if_chain::if_chain;
8 use rustc_ast::ast::{self, LitKind};
9 use rustc_hir as hir;
10 use rustc_hir::{
11     Arm, Block, BorrowKind, Expr, ExprKind, HirId, LoopSource, MatchSource, Node, Pat, QPath, StmtKind, UnOp,
12 };
13 use rustc_lint::LateContext;
14 use rustc_span::{sym, symbol, ExpnKind, Span, Symbol};
15
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> {
19     /// `for` loop item
20     pub pat: &'tcx hir::Pat<'tcx>,
21     /// `IntoIterator` argument
22     pub arg: &'tcx hir::Expr<'tcx>,
23     /// `for` loop body
24     pub body: &'tcx hir::Expr<'tcx>,
25     /// entire `for` loop span
26     pub span: Span,
27 }
28
29 impl<'tcx> ForLoop<'tcx> {
30     #[inline]
31     /// Parses a desugared `for` loop
32     pub fn hir(expr: &Expr<'tcx>) -> Option<Self> {
33         if_chain! {
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;
44             then {
45                 return Some(Self {
46                     pat: &*local.pat,
47                     arg: first_arg,
48                     body: body_expr,
49                     span: first_arm.span
50                 });
51             }
52         }
53         None
54     }
55 }
56
57 /// An `if` expression without `DropTemps`
58 pub struct If<'hir> {
59     /// `if` condition
60     pub cond: &'hir Expr<'hir>,
61     /// `if` then expression
62     pub then: &'hir Expr<'hir>,
63     /// `else` expression
64     pub r#else: Option<&'hir Expr<'hir>>,
65 }
66
67 impl<'hir> If<'hir> {
68     #[inline]
69     /// Parses an `if` expression
70     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
71         if let ExprKind::If(
72             Expr {
73                 kind: ExprKind::DropTemps(cond),
74                 ..
75             },
76             then,
77             r#else,
78         ) = expr.kind
79         {
80             Some(Self { cond, then, r#else })
81         } else {
82             None
83         }
84     }
85 }
86
87 /// An `if let` expression
88 pub struct IfLet<'hir> {
89     /// `if let` pattern
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>>,
97 }
98
99 impl<'hir> IfLet<'hir> {
100     /// Parses an `if let` expression
101     pub fn hir(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
102         if let ExprKind::If(
103             Expr {
104                 kind: ExprKind::Let(let_pat, let_expr, _),
105                 ..
106             },
107             if_then,
108             if_else,
109         ) = expr.kind
110         {
111             let mut iter = cx.tcx.hir().parent_iter(expr.hir_id);
112             if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
113                 if let Some((
114                     _,
115                     Node::Expr(Expr {
116                         kind: ExprKind::Loop(_, _, LoopSource::While, _),
117                         ..
118                     }),
119                 )) = iter.next()
120                 {
121                     // while loop desugar
122                     return None;
123                 }
124             }
125             return Some(Self {
126                 let_pat,
127                 let_expr,
128                 if_then,
129                 if_else,
130             });
131         }
132         None
133     }
134 }
135
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
141     IfLet(
142         &'hir Expr<'hir>,
143         &'hir Pat<'hir>,
144         &'hir Expr<'hir>,
145         Option<&'hir Expr<'hir>>,
146     ),
147 }
148
149 impl<'hir> IfLetOrMatch<'hir> {
150     /// Parses an `if let` or `match` expression
151     pub fn parse(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
152         match expr.kind {
153             ExprKind::Match(expr, arms, source) => Some(Self::Match(expr, arms, source)),
154             _ => IfLet::hir(cx, expr).map(
155                 |IfLet {
156                      let_expr,
157                      let_pat,
158                      if_then,
159                      if_else,
160                  }| { Self::IfLet(let_expr, let_pat, if_then, if_else) },
161             ),
162         }
163     }
164 }
165
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>>,
174 }
175
176 impl<'hir> IfOrIfLet<'hir> {
177     #[inline]
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 {
182                 return Some(Self {
183                     cond: new_cond,
184                     r#else,
185                     then,
186                 });
187             }
188             if let ExprKind::Let(..) = cond.kind {
189                 return Some(Self { cond, then, r#else });
190             }
191         }
192         None
193     }
194 }
195
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,
205 }
206
207 impl<'a> Range<'a> {
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
211         /// convenience.
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;
214             Some(expr)
215         }
216
217         match expr.kind {
218             hir::ExprKind::Call(path, args)
219                 if matches!(
220                     path.kind,
221                     hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
222                 ) =>
223             {
224                 Some(Range {
225                     start: Some(&args[0]),
226                     end: Some(&args[1]),
227                     limits: ast::RangeLimits::Closed,
228                 })
229             },
230             hir::ExprKind::Struct(path, fields, None) => match &path {
231                 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
232                     start: None,
233                     end: None,
234                     limits: ast::RangeLimits::HalfOpen,
235                 }),
236                 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
237                     start: Some(get_field("start", fields)?),
238                     end: None,
239                     limits: ast::RangeLimits::HalfOpen,
240                 }),
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,
245                 }),
246                 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
247                     start: None,
248                     end: Some(get_field("end", fields)?),
249                     limits: ast::RangeLimits::Closed,
250                 }),
251                 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
252                     start: None,
253                     end: Some(get_field("end", fields)?),
254                     limits: ast::RangeLimits::HalfOpen,
255                 }),
256                 _ => None,
257             },
258             _ => None,
259         }
260     }
261 }
262
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>),
267     /// `vec![a, b, c]`
268     Vec(&'a [hir::Expr<'a>]),
269 }
270
271 impl<'a> VecArgs<'a> {
272     /// Returns the arguments of the `vec!` macro if this expression was expanded
273     /// from `vec!`.
274     pub fn hir(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<VecArgs<'a>> {
275         if_chain! {
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();
280             then {
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]))
284                 }
285                 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
286                     // `vec![a, b, c]` case
287                     if_chain! {
288                         if let hir::ExprKind::Box(boxed) = args[0].kind;
289                         if let hir::ExprKind::Array(args) = boxed.kind;
290                         then {
291                             return Some(VecArgs::Vec(args));
292                         }
293                     }
294
295                     None
296                 }
297                 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
298                     Some(VecArgs::Vec(&[]))
299                 }
300                 else {
301                     None
302                 };
303             }
304         }
305
306         None
307     }
308 }
309
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>,
316 }
317
318 impl<'hir> While<'hir> {
319     #[inline]
320     /// Parses a desugared `while` loop
321     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
322         if let ExprKind::Loop(
323             Block {
324                 expr:
325                     Some(Expr {
326                         kind:
327                             ExprKind::If(
328                                 Expr {
329                                     kind: ExprKind::DropTemps(condition),
330                                     ..
331                                 },
332                                 body,
333                                 _,
334                             ),
335                         ..
336                     }),
337                 ..
338             },
339             _,
340             LoopSource::While,
341             _,
342         ) = expr.kind
343         {
344             return Some(Self { condition, body });
345         }
346         None
347     }
348 }
349
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>,
358 }
359
360 impl<'hir> WhileLet<'hir> {
361     #[inline]
362     /// Parses a desugared `while let` loop
363     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
364         if let ExprKind::Loop(
365             Block {
366                 expr:
367                     Some(Expr {
368                         kind:
369                             ExprKind::If(
370                                 Expr {
371                                     kind: ExprKind::Let(let_pat, let_expr, _),
372                                     ..
373                                 },
374                                 if_then,
375                                 _,
376                             ),
377                         ..
378                     }),
379                 ..
380             },
381             _,
382             LoopSource::While,
383             _,
384         ) = expr.kind
385         {
386             return Some(Self {
387                 let_pat,
388                 let_expr,
389                 if_then,
390             });
391         }
392         None
393     }
394 }
395
396 /// Converts a hir binary operator to the corresponding `ast` type.
397 #[must_use]
398 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
399     match op {
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,
418     }
419 }
420
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!`
425 /// For example:
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
430     /// compared
431     fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
432         if_chain! {
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;
437             then {
438                 return Some(vec![lhs, rhs]);
439             }
440         }
441         None
442     }
443
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)`)
448                 if_chain! {
449                     if let Some(If { cond, .. }) = If::hir(matchexpr);
450                     if let ExprKind::Unary(UnOp::Not, condition) = cond.kind;
451                     then {
452                         return Some(vec![condition]);
453                     }
454                 }
455
456                 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
457                 if_chain! {
458                     if let ExprKind::Block(matchblock,_) = matchexpr.kind;
459                     if let Some(matchblock_expr) = matchblock.expr;
460                     then {
461                         return ast_matchblock(matchblock_expr);
462                     }
463                 }
464             }
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);
468         }
469     }
470     None
471 }
472
473 /// A parsed `format!` expansion
474 pub struct FormatExpn<'tcx> {
475     /// Span of `format!(..)`
476     pub call_site: Span,
477     /// Inner `format_args!` expansion
478     pub format_args: FormatArgsExpn<'tcx>,
479 }
480
481 impl FormatExpn<'tcx> {
482     /// Parses an expanded `format!` invocation
483     pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
484         if_chain! {
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);
493             then {
494                 Some(FormatExpn {
495                     call_site: expn_data.call_site,
496                     format_args,
497                 })
498             } else {
499                 None
500             }
501         }
502     }
503 }
504
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>>,
511
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>>,
520 }
521
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> {
525         if_chain! {
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 {
531                 // Arguments::new_v1
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))),
535                 _ => None,
536             };
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
540                 .iter()
541                 .map(|e| {
542                     if let ExprKind::Lit(lit) = &e.kind {
543                         if let LitKind::Str(symbol, _style) = lit.node {
544                             return Some(symbol);
545                         }
546                     }
547                     None
548                 })
549                 .collect();
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
554                 .iter()
555                 .map(|e| match e.kind {
556                     ExprKind::AddrOf(_, _, e) => Some(e),
557                     _ => None,
558                 })
559                 .collect();
560             if let ExprKind::Array(args) = arm.body.kind;
561             then {
562                 Some(FormatArgsExpn {
563                     format_string_span: strs_ref.span,
564                     value_args,
565                     format_string_parts,
566                     format_string_symbols,
567                     args,
568                     fmt_expr,
569                 })
570             } else {
571                 None
572             }
573         }
574     }
575
576     /// Returns a vector of `FormatArgsArg`.
577     pub fn args(&self) -> Option<Vec<FormatArgsArg<'tcx>>> {
578         if let Some(expr) = self.fmt_expr {
579             if_chain! {
580                 if let ExprKind::AddrOf(BorrowKind::Ref, _, expr) = expr.kind;
581                 if let ExprKind::Array(exprs) = expr.kind;
582                 then {
583                     exprs.iter().map(|fmt| {
584                         if_chain! {
585                             // struct `core::fmt::rt::v1::Argument`
586                             if let ExprKind::Struct(_, fields, _) = fmt.kind;
587                             if let Some(position_field) = fields.iter().find(|f| f.ident.name == sym::position);
588                             if let ExprKind::Lit(lit) = &position_field.expr.kind;
589                             if let LitKind::Int(position, _) = lit.node;
590                             if let Ok(i) = usize::try_from(position);
591                             let arg = &self.args[i];
592                             if let ExprKind::Call(_, [arg_name, _]) = arg.kind;
593                             if let ExprKind::Field(_, j) = arg_name.kind;
594                             if let Ok(j) = j.name.as_str().parse::<usize>();
595                             then {
596                                 Some(FormatArgsArg { value: self.value_args[j], arg, fmt: Some(fmt) })
597                             } else {
598                                 None
599                             }
600                         }
601                     }).collect()
602                 } else {
603                     None
604                 }
605             }
606         } else {
607             Some(
608                 self.value_args
609                     .iter()
610                     .zip(self.args.iter())
611                     .map(|(value, arg)| FormatArgsArg { value, arg, fmt: None })
612                     .collect(),
613             )
614         }
615     }
616 }
617
618 /// Type representing a `FormatArgsExpn`'s format arguments
619 pub struct FormatArgsArg<'tcx> {
620     /// An element of `value_args` according to `position`
621     pub value: &'tcx Expr<'tcx>,
622     /// An element of `args` according to `position`
623     pub arg: &'tcx Expr<'tcx>,
624     /// An element of `fmt_expn`
625     pub fmt: Option<&'tcx Expr<'tcx>>,
626 }
627
628 impl<'tcx> FormatArgsArg<'tcx> {
629     /// Returns true if any formatting parameters are used that would have an effect on strings,
630     /// like `{:+2}` instead of just `{}`.
631     pub fn has_string_formatting(&self) -> bool {
632         self.fmt.map_or(false, |fmt| {
633             // `!` because these conditions check that `self` is unformatted.
634             !if_chain! {
635                 // struct `core::fmt::rt::v1::Argument`
636                 if let ExprKind::Struct(_, fields, _) = fmt.kind;
637                 if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym::format);
638                 // struct `core::fmt::rt::v1::FormatSpec`
639                 if let ExprKind::Struct(_, subfields, _) = format_field.expr.kind;
640                 let mut precision_found = false;
641                 let mut width_found = false;
642                 if subfields.iter().all(|field| {
643                     match field.ident.name {
644                         sym::precision => {
645                             precision_found = true;
646                             if let ExprKind::Path(ref precision_path) = field.expr.kind {
647                                 last_path_segment(precision_path).ident.name == sym::Implied
648                             } else {
649                                 false
650                             }
651                         }
652                         sym::width => {
653                             width_found = true;
654                             if let ExprKind::Path(ref width_qpath) = field.expr.kind {
655                                 last_path_segment(width_qpath).ident.name == sym::Implied
656                             } else {
657                                 false
658                             }
659                         }
660                         _ => true,
661                     }
662                 });
663                 if precision_found && width_found;
664                 then { true } else { false }
665             }
666         })
667     }
668
669     /// Returns true if the argument is formatted using `Display::fmt`.
670     pub fn is_display(&self) -> bool {
671         if_chain! {
672             if let ExprKind::Call(_, [_, format_field]) = self.arg.kind;
673             if let ExprKind::Path(QPath::Resolved(_, path)) = format_field.kind;
674             if let [.., t, _] = path.segments;
675             if t.ident.name == sym::Display;
676             then { true } else { false }
677         }
678     }
679 }
680
681 /// Checks if a `let` statement is from a `for` loop desugaring.
682 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
683     // This will detect plain for-loops without an actual variable binding:
684     //
685     // ```
686     // for x in some_vec {
687     //     // do stuff
688     // }
689     // ```
690     if_chain! {
691         if let Some(expr) = local.init;
692         if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
693         then {
694             return true;
695         }
696     }
697
698     // This detects a variable binding in for loop to avoid `let_unit_value`
699     // lint (see issue #1964).
700     //
701     // ```
702     // for _ in vec![()] {
703     //     // anything
704     // }
705     // ```
706     if let hir::LocalSource::ForLoopDesugar = local.source {
707         return true;
708     }
709
710     false
711 }
712
713 /// A parsed `panic!` expansion
714 pub struct PanicExpn<'tcx> {
715     /// Span of `panic!(..)`
716     pub call_site: Span,
717     /// Inner `format_args!` expansion
718     pub format_args: FormatArgsExpn<'tcx>,
719 }
720
721 impl PanicExpn<'tcx> {
722     /// Parses an expanded `panic!` invocation
723     pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
724         if_chain! {
725             if let ExprKind::Call(_, [format_args]) = expr.kind;
726             let expn_data = expr.span.ctxt().outer_expn_data();
727             if let Some(format_args) = FormatArgsExpn::parse(format_args);
728             then {
729                 Some(PanicExpn {
730                     call_site: expn_data.call_site,
731                     format_args,
732                 })
733             } else {
734                 None
735             }
736         }
737     }
738 }
739
740 /// A parsed `Vec` initialization expression
741 #[derive(Clone, Copy)]
742 pub enum VecInitKind {
743     /// `Vec::new()`
744     New,
745     /// `Vec::default()` or `Default::default()`
746     Default,
747     /// `Vec::with_capacity(123)`
748     WithLiteralCapacity(u64),
749     /// `Vec::with_capacity(slice.len())`
750     WithExprCapacity(HirId),
751 }
752
753 /// Checks if given expression is an initialization of `Vec` and returns its kind.
754 pub fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<VecInitKind> {
755     if let ExprKind::Call(func, args) = expr.kind {
756         match func.kind {
757             ExprKind::Path(QPath::TypeRelative(ty, name))
758                 if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::Vec) =>
759             {
760                 if name.ident.name == sym::new {
761                     return Some(VecInitKind::New);
762                 } else if name.ident.name == symbol::kw::Default {
763                     return Some(VecInitKind::Default);
764                 } else if name.ident.name.as_str() == "with_capacity" {
765                     let arg = args.get(0)?;
766                     if_chain! {
767                         if let ExprKind::Lit(lit) = &arg.kind;
768                         if let LitKind::Int(num, _) = lit.node;
769                         then {
770                             return Some(VecInitKind::WithLiteralCapacity(num.try_into().ok()?))
771                         }
772                     }
773                     return Some(VecInitKind::WithExprCapacity(arg.hir_id));
774                 }
775             },
776             ExprKind::Path(QPath::Resolved(_, path))
777                 if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD)
778                     && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Vec) =>
779             {
780                 return Some(VecInitKind::Default);
781             },
782             _ => (),
783         }
784     }
785     None
786 }