]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/higher.rs
Auto merge of #89158 - the8472:rollup-3e4ijth, r=the8472
[rust.git] / clippy_utils / src / higher.rs
1 //! This module contains functions that retrieves specifiec elements.
2
3 #![deny(clippy::missing_docs_in_private_items)]
4
5 use crate::{is_expn_of, match_def_path, paths};
6 use if_chain::if_chain;
7 use rustc_ast::ast::{self, LitKind};
8 use rustc_hir as hir;
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};
12
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     /// `for` loop item
17     pub pat: &'tcx hir::Pat<'tcx>,
18     /// `IntoIterator` argument
19     pub arg: &'tcx hir::Expr<'tcx>,
20     /// `for` loop body
21     pub body: &'tcx hir::Expr<'tcx>,
22     /// entire `for` loop span
23     pub span: Span,
24 }
25
26 impl<'tcx> ForLoop<'tcx> {
27     #[inline]
28     /// Parses a desugared `for` loop
29     pub fn hir(expr: &Expr<'tcx>) -> Option<Self> {
30         if_chain! {
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;
41             then {
42                 return Some(Self {
43                     pat: &*local.pat,
44                     arg: first_arg,
45                     body: body_expr,
46                     span: first_arm.span
47                 });
48             }
49         }
50         None
51     }
52 }
53
54 /// An `if` expression without `DropTemps`
55 pub struct If<'hir> {
56     /// `if` condition
57     pub cond: &'hir Expr<'hir>,
58     /// `if` then expression
59     pub then: &'hir Expr<'hir>,
60     /// `else` expression
61     pub r#else: Option<&'hir Expr<'hir>>,
62 }
63
64 impl<'hir> If<'hir> {
65     #[inline]
66     /// Parses an `if` expression
67     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
68         if let ExprKind::If(
69             Expr {
70                 kind: ExprKind::DropTemps(cond),
71                 ..
72             },
73             then,
74             r#else,
75         ) = expr.kind
76         {
77             Some(Self { cond, then, r#else })
78         } else {
79             None
80         }
81     }
82 }
83
84 /// An `if let` expression
85 pub struct IfLet<'hir> {
86     /// `if let` pattern
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>>,
94 }
95
96 impl<'hir> IfLet<'hir> {
97     /// Parses an `if let` expression
98     pub fn hir(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
99         if let ExprKind::If(
100             Expr {
101                 kind: ExprKind::Let(let_pat, let_expr, _),
102                 ..
103             },
104             if_then,
105             if_else,
106         ) = expr.kind
107         {
108             let mut iter = cx.tcx.hir().parent_iter(expr.hir_id);
109             if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
110                 if let Some((
111                     _,
112                     Node::Expr(Expr {
113                         kind: ExprKind::Loop(_, _, LoopSource::While, _),
114                         ..
115                     }),
116                 )) = iter.next()
117                 {
118                     // while loop desugar
119                     return None;
120                 }
121             }
122             return Some(Self {
123                 let_pat,
124                 let_expr,
125                 if_then,
126                 if_else,
127             });
128         }
129         None
130     }
131 }
132
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
138     IfLet(
139         &'hir Expr<'hir>,
140         &'hir Pat<'hir>,
141         &'hir Expr<'hir>,
142         Option<&'hir Expr<'hir>>,
143     ),
144 }
145
146 impl<'hir> IfLetOrMatch<'hir> {
147     /// Parses an `if let` or `match` expression
148     pub fn parse(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
149         match expr.kind {
150             ExprKind::Match(expr, arms, source) => Some(Self::Match(expr, arms, source)),
151             _ => IfLet::hir(cx, expr).map(
152                 |IfLet {
153                      let_expr,
154                      let_pat,
155                      if_then,
156                      if_else,
157                  }| { Self::IfLet(let_expr, let_pat, if_then, if_else) },
158             ),
159         }
160     }
161 }
162
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>>,
171 }
172
173 impl<'hir> IfOrIfLet<'hir> {
174     #[inline]
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 {
179                 return Some(Self {
180                     cond: new_cond,
181                     r#else,
182                     then,
183                 });
184             }
185             if let ExprKind::Let(..) = cond.kind {
186                 return Some(Self { cond, then, r#else });
187             }
188         }
189         None
190     }
191 }
192
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,
202 }
203
204 impl<'a> Range<'a> {
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
208         /// convenience.
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;
211             Some(expr)
212         }
213
214         match expr.kind {
215             hir::ExprKind::Call(path, args)
216                 if matches!(
217                     path.kind,
218                     hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
219                 ) =>
220             {
221                 Some(Range {
222                     start: Some(&args[0]),
223                     end: Some(&args[1]),
224                     limits: ast::RangeLimits::Closed,
225                 })
226             },
227             hir::ExprKind::Struct(path, fields, None) => match &path {
228                 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
229                     start: None,
230                     end: None,
231                     limits: ast::RangeLimits::HalfOpen,
232                 }),
233                 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
234                     start: Some(get_field("start", fields)?),
235                     end: None,
236                     limits: ast::RangeLimits::HalfOpen,
237                 }),
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,
242                 }),
243                 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
244                     start: None,
245                     end: Some(get_field("end", fields)?),
246                     limits: ast::RangeLimits::Closed,
247                 }),
248                 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
249                     start: None,
250                     end: Some(get_field("end", fields)?),
251                     limits: ast::RangeLimits::HalfOpen,
252                 }),
253                 _ => None,
254             },
255             _ => None,
256         }
257     }
258 }
259
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>),
264     /// `vec![a, b, c]`
265     Vec(&'a [hir::Expr<'a>]),
266 }
267
268 impl<'a> VecArgs<'a> {
269     /// Returns the arguments of the `vec!` macro if this expression was expanded
270     /// from `vec!`.
271     pub fn hir(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<VecArgs<'a>> {
272         if_chain! {
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();
277             then {
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]))
281                 }
282                 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
283                     // `vec![a, b, c]` case
284                     if_chain! {
285                         if let hir::ExprKind::Box(boxed) = args[0].kind;
286                         if let hir::ExprKind::Array(args) = boxed.kind;
287                         then {
288                             return Some(VecArgs::Vec(args));
289                         }
290                     }
291
292                     None
293                 }
294                 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
295                     Some(VecArgs::Vec(&[]))
296                 }
297                 else {
298                     None
299                 };
300             }
301         }
302
303         None
304     }
305 }
306
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>,
313 }
314
315 impl<'hir> While<'hir> {
316     #[inline]
317     /// Parses a desugared `while` loop
318     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
319         if let ExprKind::Loop(
320             Block {
321                 expr:
322                     Some(Expr {
323                         kind:
324                             ExprKind::If(
325                                 Expr {
326                                     kind: ExprKind::DropTemps(condition),
327                                     ..
328                                 },
329                                 body,
330                                 _,
331                             ),
332                         ..
333                     }),
334                 ..
335             },
336             _,
337             LoopSource::While,
338             _,
339         ) = expr.kind
340         {
341             return Some(Self { condition, body });
342         }
343         None
344     }
345 }
346
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>,
355 }
356
357 impl<'hir> WhileLet<'hir> {
358     #[inline]
359     /// Parses a desugared `while let` loop
360     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
361         if let ExprKind::Loop(
362             Block {
363                 expr:
364                     Some(Expr {
365                         kind:
366                             ExprKind::If(
367                                 Expr {
368                                     kind: ExprKind::Let(let_pat, let_expr, _),
369                                     ..
370                                 },
371                                 if_then,
372                                 _,
373                             ),
374                         ..
375                     }),
376                 ..
377             },
378             _,
379             LoopSource::While,
380             _,
381         ) = expr.kind
382         {
383             return Some(Self {
384                 let_pat,
385                 let_expr,
386                 if_then,
387             });
388         }
389         None
390     }
391 }
392
393 /// Converts a hir binary operator to the corresponding `ast` type.
394 #[must_use]
395 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
396     match op {
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,
415     }
416 }
417
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!`
422 /// For example:
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
427     /// compared
428     fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
429         if_chain! {
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;
434             then {
435                 return Some(vec![lhs, rhs]);
436             }
437         }
438         None
439     }
440
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)`)
445                 if_chain! {
446                     if let Some(If { cond, .. }) = If::hir(matchexpr);
447                     if let ExprKind::Unary(UnOp::Not, condition) = cond.kind;
448                     then {
449                         return Some(vec![condition]);
450                     }
451                 }
452
453                 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
454                 if_chain! {
455                     if let ExprKind::Block(matchblock,_) = matchexpr.kind;
456                     if let Some(matchblock_expr) = matchblock.expr;
457                     then {
458                         return ast_matchblock(matchblock_expr);
459                     }
460                 }
461             }
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);
465         }
466     }
467     None
468 }
469
470 /// A parsed `format!` expansion
471 pub struct FormatExpn<'tcx> {
472     /// Span of `format!(..)`
473     pub call_site: Span,
474     /// Inner `format_args!` expansion
475     pub format_args: FormatArgsExpn<'tcx>,
476 }
477
478 impl FormatExpn<'tcx> {
479     /// Parses an expanded `format!` invocation
480     pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
481         if_chain! {
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);
490             then {
491                 Some(FormatExpn {
492                     call_site: expn_data.call_site,
493                     format_args,
494                 })
495             } else {
496                 None
497             }
498         }
499     }
500 }
501
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>>,
508
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>>,
517 }
518
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> {
522         if_chain! {
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
527             if let ExprKind::Match(inner_match, [arm], _) = expr.kind;
528
529             // `match match`, if you will
530             if let ExprKind::Match(args, [inner_arm], _) = inner_match.kind;
531             if let ExprKind::Tup(value_args) = args.kind;
532             if let Some(value_args) = value_args
533                 .iter()
534                 .map(|e| match e.kind {
535                     ExprKind::AddrOf(_, _, e) => Some(e),
536                     _ => None,
537                 })
538                 .collect();
539             if let ExprKind::Array(args) = inner_arm.body.kind;
540
541             if let ExprKind::Block(Block { stmts: [], expr: Some(expr), .. }, _) = arm.body.kind;
542             if let ExprKind::Call(_, call_args) = expr.kind;
543             if let Some((strs_ref, fmt_expr)) = match call_args {
544                 // Arguments::new_v1
545                 [strs_ref, _] => Some((strs_ref, None)),
546                 // Arguments::new_v1_formatted
547                 [strs_ref, _, fmt_expr] => Some((strs_ref, Some(fmt_expr))),
548                 _ => None,
549             };
550             if let ExprKind::AddrOf(BorrowKind::Ref, _, strs_arr) = strs_ref.kind;
551             if let ExprKind::Array(format_string_parts) = strs_arr.kind;
552             if let Some(format_string_symbols) = format_string_parts
553                 .iter()
554                 .map(|e| {
555                     if let ExprKind::Lit(lit) = &e.kind {
556                         if let LitKind::Str(symbol, _style) = lit.node {
557                             return Some(symbol);
558                         }
559                     }
560                     None
561                 })
562                 .collect();
563             then {
564                 Some(FormatArgsExpn {
565                     format_string_span: strs_ref.span,
566                     value_args,
567                     format_string_parts,
568                     format_string_symbols,
569                     args,
570                     fmt_expr,
571                 })
572             } else {
573                 None
574             }
575         }
576     }
577 }
578
579 /// Checks if a `let` statement is from a `for` loop desugaring.
580 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
581     // This will detect plain for-loops without an actual variable binding:
582     //
583     // ```
584     // for x in some_vec {
585     //     // do stuff
586     // }
587     // ```
588     if_chain! {
589         if let Some(expr) = local.init;
590         if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
591         then {
592             return true;
593         }
594     }
595
596     // This detects a variable binding in for loop to avoid `let_unit_value`
597     // lint (see issue #1964).
598     //
599     // ```
600     // for _ in vec![()] {
601     //     // anything
602     // }
603     // ```
604     if let hir::LocalSource::ForLoopDesugar = local.source {
605         return true;
606     }
607
608     false
609 }