]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/higher.rs
Merge remote-tracking branch 'upstream/master' into rustup2
[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::{Block, BorrowKind, Expr, ExprKind, LoopSource, 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     pub pat: &'tcx hir::Pat<'tcx>,
17     pub arg: &'tcx hir::Expr<'tcx>,
18     pub body: &'tcx hir::Expr<'tcx>,
19     pub span: Span,
20 }
21
22 impl<'tcx> ForLoop<'tcx> {
23     #[inline]
24     pub fn hir(expr: &Expr<'tcx>) -> Option<Self> {
25         if_chain! {
26             if let hir::ExprKind::Match(ref iterexpr, ref arms, hir::MatchSource::ForLoopDesugar) = expr.kind;
27             if let Some(first_arm) = arms.get(0);
28             if let hir::ExprKind::Call(_, ref iterargs) = iterexpr.kind;
29             if let Some(first_arg) = iterargs.get(0);
30             if iterargs.len() == 1 && arms.len() == 1 && first_arm.guard.is_none();
31             if let hir::ExprKind::Loop(ref block, ..) = first_arm.body.kind;
32             if block.expr.is_none();
33             if let [ _, _, ref let_stmt, ref body ] = *block.stmts;
34             if let hir::StmtKind::Local(ref local) = let_stmt.kind;
35             if let hir::StmtKind::Expr(ref body_expr) = body.kind;
36             then {
37                 return Some(Self {
38                     pat: &*local.pat,
39                     arg: first_arg,
40                     body: body_expr,
41                     span: first_arm.span
42                 });
43             }
44         }
45         None
46     }
47 }
48
49 pub struct If<'hir> {
50     pub cond: &'hir Expr<'hir>,
51     pub r#else: Option<&'hir Expr<'hir>>,
52     pub then: &'hir Expr<'hir>,
53 }
54
55 impl<'hir> If<'hir> {
56     #[inline]
57     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
58         if let ExprKind::If(
59             Expr {
60                 kind: ExprKind::DropTemps(cond),
61                 ..
62             },
63             then,
64             r#else,
65         ) = expr.kind
66         {
67             Some(Self { cond, r#else, then })
68         } else {
69             None
70         }
71     }
72 }
73
74 pub struct IfLet<'hir> {
75     pub let_pat: &'hir Pat<'hir>,
76     pub let_expr: &'hir Expr<'hir>,
77     pub if_then: &'hir Expr<'hir>,
78     pub if_else: Option<&'hir Expr<'hir>>,
79 }
80
81 impl<'hir> IfLet<'hir> {
82     pub fn hir(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> {
83         if let ExprKind::If(
84             Expr {
85                 kind: ExprKind::Let(let_pat, let_expr, _),
86                 ..
87             },
88             if_then,
89             if_else,
90         ) = expr.kind
91         {
92             let hir = cx.tcx.hir();
93             let mut iter = hir.parent_iter(expr.hir_id);
94             if let Some((_, Node::Block(Block { stmts: [], .. }))) = iter.next() {
95                 if let Some((
96                     _,
97                     Node::Expr(Expr {
98                         kind: ExprKind::Loop(_, _, LoopSource::While, _),
99                         ..
100                     }),
101                 )) = iter.next()
102                 {
103                     // while loop desugar
104                     return None;
105                 }
106             }
107             return Some(Self {
108                 let_pat,
109                 let_expr,
110                 if_then,
111                 if_else,
112             });
113         }
114         None
115     }
116 }
117
118 pub struct IfOrIfLet<'hir> {
119     pub cond: &'hir Expr<'hir>,
120     pub r#else: Option<&'hir Expr<'hir>>,
121     pub then: &'hir Expr<'hir>,
122 }
123
124 impl<'hir> IfOrIfLet<'hir> {
125     #[inline]
126     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
127         if let ExprKind::If(cond, then, r#else) = expr.kind {
128             if let ExprKind::DropTemps(new_cond) = cond.kind {
129                 return Some(Self {
130                     cond: new_cond,
131                     r#else,
132                     then,
133                 });
134             }
135             if let ExprKind::Let(..) = cond.kind {
136                 return Some(Self { cond, r#else, then });
137             }
138         }
139         None
140     }
141 }
142
143 /// Represent a range akin to `ast::ExprKind::Range`.
144 #[derive(Debug, Copy, Clone)]
145 pub struct Range<'a> {
146     /// The lower bound of the range, or `None` for ranges such as `..X`.
147     pub start: Option<&'a hir::Expr<'a>>,
148     /// The upper bound of the range, or `None` for ranges such as `X..`.
149     pub end: Option<&'a hir::Expr<'a>>,
150     /// Whether the interval is open or closed.
151     pub limits: ast::RangeLimits,
152 }
153
154 impl<'a> Range<'a> {
155     /// Higher a `hir` range to something similar to `ast::ExprKind::Range`.
156     pub fn hir(expr: &'a hir::Expr<'_>) -> Option<Range<'a>> {
157         /// Finds the field named `name` in the field. Always return `Some` for
158         /// convenience.
159         fn get_field<'c>(name: &str, fields: &'c [hir::ExprField<'_>]) -> Option<&'c hir::Expr<'c>> {
160             let expr = &fields.iter().find(|field| field.ident.name.as_str() == name)?.expr;
161             Some(expr)
162         }
163
164         match expr.kind {
165             hir::ExprKind::Call(ref path, ref args)
166                 if matches!(
167                     path.kind,
168                     hir::ExprKind::Path(hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, _))
169                 ) =>
170             {
171                 Some(Range {
172                     start: Some(&args[0]),
173                     end: Some(&args[1]),
174                     limits: ast::RangeLimits::Closed,
175                 })
176             },
177             hir::ExprKind::Struct(ref path, ref fields, None) => match path {
178                 hir::QPath::LangItem(hir::LangItem::RangeFull, _) => Some(Range {
179                     start: None,
180                     end: None,
181                     limits: ast::RangeLimits::HalfOpen,
182                 }),
183                 hir::QPath::LangItem(hir::LangItem::RangeFrom, _) => Some(Range {
184                     start: Some(get_field("start", fields)?),
185                     end: None,
186                     limits: ast::RangeLimits::HalfOpen,
187                 }),
188                 hir::QPath::LangItem(hir::LangItem::Range, _) => Some(Range {
189                     start: Some(get_field("start", fields)?),
190                     end: Some(get_field("end", fields)?),
191                     limits: ast::RangeLimits::HalfOpen,
192                 }),
193                 hir::QPath::LangItem(hir::LangItem::RangeToInclusive, _) => Some(Range {
194                     start: None,
195                     end: Some(get_field("end", fields)?),
196                     limits: ast::RangeLimits::Closed,
197                 }),
198                 hir::QPath::LangItem(hir::LangItem::RangeTo, _) => Some(Range {
199                     start: None,
200                     end: Some(get_field("end", fields)?),
201                     limits: ast::RangeLimits::HalfOpen,
202                 }),
203                 _ => None,
204             },
205             _ => None,
206         }
207     }
208 }
209
210 /// Represent the pre-expansion arguments of a `vec!` invocation.
211 pub enum VecArgs<'a> {
212     /// `vec![elem; len]`
213     Repeat(&'a hir::Expr<'a>, &'a hir::Expr<'a>),
214     /// `vec![a, b, c]`
215     Vec(&'a [hir::Expr<'a>]),
216 }
217
218 impl<'a> VecArgs<'a> {
219     /// Returns the arguments of the `vec!` macro if this expression was expanded
220     /// from `vec!`.
221     pub fn hir(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<VecArgs<'a>> {
222         if_chain! {
223             if let hir::ExprKind::Call(ref fun, ref args) = expr.kind;
224             if let hir::ExprKind::Path(ref qpath) = fun.kind;
225             if is_expn_of(fun.span, "vec").is_some();
226             if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
227             then {
228                 return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 {
229                     // `vec![elem; size]` case
230                     Some(VecArgs::Repeat(&args[0], &args[1]))
231                 }
232                 else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
233                     // `vec![a, b, c]` case
234                     if_chain! {
235                         if let hir::ExprKind::Box(ref boxed) = args[0].kind;
236                         if let hir::ExprKind::Array(ref args) = boxed.kind;
237                         then {
238                             return Some(VecArgs::Vec(&*args));
239                         }
240                     }
241
242                     None
243                 }
244                 else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
245                     Some(VecArgs::Vec(&[]))
246                 }
247                 else {
248                     None
249                 };
250             }
251         }
252
253         None
254     }
255 }
256
257 pub struct While<'hir> {
258     pub if_cond: &'hir Expr<'hir>,
259     pub if_then: &'hir Expr<'hir>,
260     pub if_else: Option<&'hir Expr<'hir>>,
261 }
262
263 impl<'hir> While<'hir> {
264     #[inline]
265     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
266         if let ExprKind::Loop(
267             Block {
268                 expr:
269                     Some(Expr {
270                         kind:
271                             ExprKind::If(
272                                 Expr {
273                                     kind: ExprKind::DropTemps(if_cond),
274                                     ..
275                                 },
276                                 if_then,
277                                 if_else_ref,
278                             ),
279                         ..
280                     }),
281                 ..
282             },
283             _,
284             LoopSource::While,
285             _,
286         ) = expr.kind
287         {
288             let if_else = *if_else_ref;
289             return Some(Self {
290                 if_cond,
291                 if_then,
292                 if_else,
293             });
294         }
295         None
296     }
297 }
298
299 pub struct WhileLet<'hir> {
300     pub if_expr: &'hir Expr<'hir>,
301     pub let_pat: &'hir Pat<'hir>,
302     pub let_expr: &'hir Expr<'hir>,
303     pub if_then: &'hir Expr<'hir>,
304     pub if_else: Option<&'hir Expr<'hir>>,
305 }
306
307 impl<'hir> WhileLet<'hir> {
308     #[inline]
309     pub const fn hir(expr: &Expr<'hir>) -> Option<Self> {
310         if let ExprKind::Loop(
311             Block {
312                 expr: Some(if_expr), ..
313             },
314             _,
315             LoopSource::While,
316             _,
317         ) = expr.kind
318         {
319             if let Expr {
320                 kind:
321                     ExprKind::If(
322                         Expr {
323                             kind: ExprKind::Let(let_pat, let_expr, _),
324                             ..
325                         },
326                         if_then,
327                         if_else_ref,
328                     ),
329                 ..
330             } = if_expr
331             {
332                 let if_else = *if_else_ref;
333                 return Some(Self {
334                     if_expr,
335                     let_pat,
336                     let_expr,
337                     if_then,
338                     if_else,
339                 });
340             }
341         }
342         None
343     }
344 }
345
346 /// Converts a hir binary operator to the corresponding `ast` type.
347 #[must_use]
348 pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind {
349     match op {
350         hir::BinOpKind::Eq => ast::BinOpKind::Eq,
351         hir::BinOpKind::Ge => ast::BinOpKind::Ge,
352         hir::BinOpKind::Gt => ast::BinOpKind::Gt,
353         hir::BinOpKind::Le => ast::BinOpKind::Le,
354         hir::BinOpKind::Lt => ast::BinOpKind::Lt,
355         hir::BinOpKind::Ne => ast::BinOpKind::Ne,
356         hir::BinOpKind::Or => ast::BinOpKind::Or,
357         hir::BinOpKind::Add => ast::BinOpKind::Add,
358         hir::BinOpKind::And => ast::BinOpKind::And,
359         hir::BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
360         hir::BinOpKind::BitOr => ast::BinOpKind::BitOr,
361         hir::BinOpKind::BitXor => ast::BinOpKind::BitXor,
362         hir::BinOpKind::Div => ast::BinOpKind::Div,
363         hir::BinOpKind::Mul => ast::BinOpKind::Mul,
364         hir::BinOpKind::Rem => ast::BinOpKind::Rem,
365         hir::BinOpKind::Shl => ast::BinOpKind::Shl,
366         hir::BinOpKind::Shr => ast::BinOpKind::Shr,
367         hir::BinOpKind::Sub => ast::BinOpKind::Sub,
368     }
369 }
370
371 /// Extract args from an assert-like macro.
372 /// Currently working with:
373 /// - `assert!`, `assert_eq!` and `assert_ne!`
374 /// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!`
375 /// For example:
376 /// `assert!(expr)` will return `Some([expr])`
377 /// `debug_assert_eq!(a, b)` will return `Some([a, b])`
378 pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> {
379     /// Try to match the AST for a pattern that contains a match, for example when two args are
380     /// compared
381     fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> {
382         if_chain! {
383             if let ExprKind::Match(headerexpr, _, _) = &matchblock_expr.kind;
384             if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind;
385             if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind;
386             if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind;
387             then {
388                 return Some(vec![lhs, rhs]);
389             }
390         }
391         None
392     }
393
394     if let ExprKind::Block(block, _) = e.kind {
395         if block.stmts.len() == 1 {
396             if let StmtKind::Semi(matchexpr) = block.stmts.get(0)?.kind {
397                 // macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`)
398                 if_chain! {
399                     if let Some(If { cond, .. }) = If::hir(matchexpr);
400                     if let ExprKind::Unary(UnOp::Not, condition) = cond.kind;
401                     then {
402                         return Some(vec![condition]);
403                     }
404                 }
405
406                 // debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
407                 if_chain! {
408                     if let ExprKind::Block(matchblock,_) = matchexpr.kind;
409                     if let Some(matchblock_expr) = matchblock.expr;
410                     then {
411                         return ast_matchblock(matchblock_expr);
412                     }
413                 }
414             }
415         } else if let Some(matchblock_expr) = block.expr {
416             // macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`)
417             return ast_matchblock(matchblock_expr);
418         }
419     }
420     None
421 }
422
423 /// A parsed `format!` expansion
424 pub struct FormatExpn<'tcx> {
425     /// Span of `format!(..)`
426     pub call_site: Span,
427     /// Inner `format_args!` expansion
428     pub format_args: FormatArgsExpn<'tcx>,
429 }
430
431 impl FormatExpn<'tcx> {
432     /// Parses an expanded `format!` invocation
433     pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
434         if_chain! {
435             if let ExprKind::Block(block, _) = expr.kind;
436             if let [stmt] = block.stmts;
437             if let StmtKind::Local(local) = stmt.kind;
438             if let Some(init) = local.init;
439             if let ExprKind::Call(_, [format_args]) = init.kind;
440             let expn_data = expr.span.ctxt().outer_expn_data();
441             if let ExpnKind::Macro(_, sym::format) = expn_data.kind;
442             if let Some(format_args) = FormatArgsExpn::parse(format_args);
443             then {
444                 Some(FormatExpn {
445                     call_site: expn_data.call_site,
446                     format_args,
447                 })
448             } else {
449                 None
450             }
451         }
452     }
453 }
454
455 /// A parsed `format_args!` expansion
456 pub struct FormatArgsExpn<'tcx> {
457     /// Span of the first argument, the format string
458     pub format_string_span: Span,
459     /// Values passed after the format string
460     pub value_args: Vec<&'tcx Expr<'tcx>>,
461
462     /// String literal expressions which represent the format string split by "{}"
463     pub format_string_parts: &'tcx [Expr<'tcx>],
464     /// Symbols corresponding to [`Self::format_string_parts`]
465     pub format_string_symbols: Vec<Symbol>,
466     /// Expressions like `ArgumentV1::new(arg0, Debug::fmt)`
467     pub args: &'tcx [Expr<'tcx>],
468     /// The final argument passed to `Arguments::new_v1_formatted`, if applicable
469     pub fmt_expr: Option<&'tcx Expr<'tcx>>,
470 }
471
472 impl FormatArgsExpn<'tcx> {
473     /// Parses an expanded `format_args!` or `format_args_nl!` invocation
474     pub fn parse(expr: &'tcx Expr<'tcx>) -> Option<Self> {
475         if_chain! {
476             if let ExpnKind::Macro(_, name) = expr.span.ctxt().outer_expn_data().kind;
477             let name = name.as_str();
478             if name.ends_with("format_args") || name.ends_with("format_args_nl");
479
480             if let ExprKind::Match(inner_match, [arm], _) = expr.kind;
481
482             // `match match`, if you will
483             if let ExprKind::Match(args, [inner_arm], _) = inner_match.kind;
484             if let ExprKind::Tup(value_args) = args.kind;
485             if let Some(value_args) = value_args
486                 .iter()
487                 .map(|e| match e.kind {
488                     ExprKind::AddrOf(_, _, e) => Some(e),
489                     _ => None,
490                 })
491                 .collect();
492             if let ExprKind::Array(args) = inner_arm.body.kind;
493
494             if let ExprKind::Block(Block { stmts: [], expr: Some(expr), .. }, _) = arm.body.kind;
495             if let ExprKind::Call(_, call_args) = expr.kind;
496             if let Some((strs_ref, fmt_expr)) = match call_args {
497                 // Arguments::new_v1
498                 [strs_ref, _] => Some((strs_ref, None)),
499                 // Arguments::new_v1_formatted
500                 [strs_ref, _, fmt_expr] => Some((strs_ref, Some(fmt_expr))),
501                 _ => None,
502             };
503             if let ExprKind::AddrOf(BorrowKind::Ref, _, strs_arr) = strs_ref.kind;
504             if let ExprKind::Array(format_string_parts) = strs_arr.kind;
505             if let Some(format_string_symbols) = format_string_parts
506                 .iter()
507                 .map(|e| {
508                     if let ExprKind::Lit(lit) = &e.kind {
509                         if let LitKind::Str(symbol, _style) = lit.node {
510                             return Some(symbol);
511                         }
512                     }
513                     None
514                 })
515                 .collect();
516             then {
517                 Some(FormatArgsExpn {
518                     format_string_span: strs_ref.span,
519                     value_args,
520                     format_string_parts,
521                     format_string_symbols,
522                     args,
523                     fmt_expr,
524                 })
525             } else {
526                 None
527             }
528         }
529     }
530 }
531
532 /// Checks if a `let` statement is from a `for` loop desugaring.
533 pub fn is_from_for_desugar(local: &hir::Local<'_>) -> bool {
534     // This will detect plain for-loops without an actual variable binding:
535     //
536     // ```
537     // for x in some_vec {
538     //     // do stuff
539     // }
540     // ```
541     if_chain! {
542         if let Some(ref expr) = local.init;
543         if let hir::ExprKind::Match(_, _, hir::MatchSource::ForLoopDesugar) = expr.kind;
544         then {
545             return true;
546         }
547     }
548
549     // This detects a variable binding in for loop to avoid `let_unit_value`
550     // lint (see issue #1964).
551     //
552     // ```
553     // for _ in vec![()] {
554     //     // anything
555     // }
556     // ```
557     if let hir::LocalSource::ForLoopDesugar = local.source {
558         return true;
559     }
560
561     false
562 }