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