]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/lib.rs
5d6c1337be6a2d33df4f3b544e67359e2842ac5e
[rust.git] / clippy_utils / src / lib.rs
1 #![feature(box_patterns)]
2 #![feature(in_band_lifetimes)]
3 #![feature(iter_zip)]
4 #![feature(rustc_private)]
5 #![recursion_limit = "512"]
6 #![allow(clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate)]
7
8 // FIXME: switch to something more ergonomic here, once available.
9 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
10 extern crate rustc_ast;
11 extern crate rustc_ast_pretty;
12 extern crate rustc_attr;
13 extern crate rustc_data_structures;
14 extern crate rustc_errors;
15 extern crate rustc_hir;
16 extern crate rustc_hir_pretty;
17 extern crate rustc_infer;
18 extern crate rustc_lexer;
19 extern crate rustc_lint;
20 extern crate rustc_middle;
21 extern crate rustc_mir;
22 extern crate rustc_session;
23 extern crate rustc_span;
24 extern crate rustc_target;
25 extern crate rustc_trait_selection;
26 extern crate rustc_typeck;
27
28 #[macro_use]
29 pub mod sym_helper;
30
31 #[allow(clippy::module_name_repetitions)]
32 pub mod ast_utils;
33 pub mod attrs;
34 pub mod camel_case;
35 pub mod comparisons;
36 pub mod consts;
37 pub mod diagnostics;
38 pub mod eager_or_lazy;
39 pub mod higher;
40 mod hir_utils;
41 pub mod numeric_literal;
42 pub mod paths;
43 pub mod ptr;
44 pub mod qualify_min_const_fn;
45 pub mod source;
46 pub mod sugg;
47 pub mod ty;
48 pub mod usage;
49 pub mod visitors;
50
51 pub use self::attrs::*;
52 pub use self::hir_utils::{both, count_eq, eq_expr_value, over, SpanlessEq, SpanlessHash};
53
54 use std::collections::hash_map::Entry;
55 use std::hash::BuildHasherDefault;
56
57 use if_chain::if_chain;
58 use rustc_ast::ast::{self, Attribute, BorrowKind, LitKind};
59 use rustc_data_structures::fx::FxHashMap;
60 use rustc_hir as hir;
61 use rustc_hir::def::{DefKind, Res};
62 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
63 use rustc_hir::intravisit::{self, walk_expr, ErasedMap, NestedVisitorMap, Visitor};
64 use rustc_hir::LangItem::{ResultErr, ResultOk};
65 use rustc_hir::{
66     def, Arm, BindingAnnotation, Block, Body, Constness, Destination, Expr, ExprKind, FnDecl, GenericArgs, HirId, Impl,
67     ImplItem, ImplItemKind, Item, ItemKind, LangItem, MatchSource, Node, Param, Pat, PatKind, Path, PathSegment, QPath,
68     Stmt, StmtKind, TraitItem, TraitItemKind, TraitRef, TyKind,
69 };
70 use rustc_lint::{LateContext, Level, Lint, LintContext};
71 use rustc_middle::hir::exports::Export;
72 use rustc_middle::hir::map::Map;
73 use rustc_middle::ty as rustc_ty;
74 use rustc_middle::ty::{layout::IntegerExt, DefIdTree, Ty, TyCtxt, TypeFoldable};
75 use rustc_semver::RustcVersion;
76 use rustc_session::Session;
77 use rustc_span::hygiene::{ExpnKind, MacroKind};
78 use rustc_span::source_map::original_sp;
79 use rustc_span::sym;
80 use rustc_span::symbol::{kw, Symbol};
81 use rustc_span::{Span, DUMMY_SP};
82 use rustc_target::abi::Integer;
83
84 use crate::consts::{constant, Constant};
85 use crate::ty::{can_partially_move_ty, is_recursively_primitive_type};
86
87 pub fn parse_msrv(msrv: &str, sess: Option<&Session>, span: Option<Span>) -> Option<RustcVersion> {
88     if let Ok(version) = RustcVersion::parse(msrv) {
89         return Some(version);
90     } else if let Some(sess) = sess {
91         if let Some(span) = span {
92             sess.span_err(span, &format!("`{}` is not a valid Rust version", msrv));
93         }
94     }
95     None
96 }
97
98 pub fn meets_msrv(msrv: Option<&RustcVersion>, lint_msrv: &RustcVersion) -> bool {
99     msrv.map_or(true, |msrv| msrv.meets(*lint_msrv))
100 }
101
102 #[macro_export]
103 macro_rules! extract_msrv_attr {
104     (LateContext) => {
105         extract_msrv_attr!(@LateContext, ());
106     };
107     (EarlyContext) => {
108         extract_msrv_attr!(@EarlyContext);
109     };
110     (@$context:ident$(, $call:tt)?) => {
111         fn enter_lint_attrs(&mut self, cx: &rustc_lint::$context<'tcx>, attrs: &'tcx [rustc_ast::ast::Attribute]) {
112             use $crate::get_unique_inner_attr;
113             match get_unique_inner_attr(cx.sess$($call)?, attrs, "msrv") {
114                 Some(msrv_attr) => {
115                     if let Some(msrv) = msrv_attr.value_str() {
116                         self.msrv = $crate::parse_msrv(
117                             &msrv.to_string(),
118                             Some(cx.sess$($call)?),
119                             Some(msrv_attr.span),
120                         );
121                     } else {
122                         cx.sess$($call)?.span_err(msrv_attr.span, "bad clippy attribute");
123                     }
124                 },
125                 _ => (),
126             }
127         }
128     };
129 }
130
131 /// Returns `true` if the two spans come from differing expansions (i.e., one is
132 /// from a macro and one isn't).
133 #[must_use]
134 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
135     rhs.ctxt() != lhs.ctxt()
136 }
137
138 /// If the given expression is a local binding, find the initializer expression.
139 /// If that initializer expression is another local binding, find its initializer again.
140 /// This process repeats as long as possible (but usually no more than once). Initializer
141 /// expressions with adjustments are ignored. If this is not desired, use [`find_binding_init`]
142 /// instead.
143 ///
144 /// Examples:
145 /// ```ignore
146 /// let abc = 1;
147 /// //        ^ output
148 /// let def = abc;
149 /// dbg!(def)
150 /// //   ^^^ input
151 ///
152 /// // or...
153 /// let abc = 1;
154 /// let def = abc + 2;
155 /// //        ^^^^^^^ output
156 /// dbg!(def)
157 /// //   ^^^ input
158 /// ```
159 pub fn expr_or_init<'a, 'b, 'tcx: 'b>(cx: &LateContext<'tcx>, mut expr: &'a Expr<'b>) -> &'a Expr<'b> {
160     while let Some(init) = path_to_local(expr)
161         .and_then(|id| find_binding_init(cx, id))
162         .filter(|init| cx.typeck_results().expr_adjustments(init).is_empty())
163     {
164         expr = init;
165     }
166     expr
167 }
168
169 /// Finds the initializer expression for a local binding. Returns `None` if the binding is mutable.
170 /// By only considering immutable bindings, we guarantee that the returned expression represents the
171 /// value of the binding wherever it is referenced.
172 ///
173 /// Example: For `let x = 1`, if the `HirId` of `x` is provided, the `Expr` `1` is returned.
174 /// Note: If you have an expression that references a binding `x`, use `path_to_local` to get the
175 /// canonical binding `HirId`.
176 pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
177     let hir = cx.tcx.hir();
178     if_chain! {
179         if let Some(Node::Binding(pat)) = hir.find(hir_id);
180         if matches!(pat.kind, PatKind::Binding(BindingAnnotation::Unannotated, ..));
181         let parent = hir.get_parent_node(hir_id);
182         if let Some(Node::Local(local)) = hir.find(parent);
183         then {
184             return local.init;
185         }
186     }
187     None
188 }
189
190 /// Returns `true` if the given `NodeId` is inside a constant context
191 ///
192 /// # Example
193 ///
194 /// ```rust,ignore
195 /// if in_constant(cx, expr.hir_id) {
196 ///     // Do something
197 /// }
198 /// ```
199 pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
200     let parent_id = cx.tcx.hir().get_parent_item(id);
201     match cx.tcx.hir().get(parent_id) {
202         Node::Item(&Item {
203             kind: ItemKind::Const(..) | ItemKind::Static(..),
204             ..
205         })
206         | Node::TraitItem(&TraitItem {
207             kind: TraitItemKind::Const(..),
208             ..
209         })
210         | Node::ImplItem(&ImplItem {
211             kind: ImplItemKind::Const(..),
212             ..
213         })
214         | Node::AnonConst(_) => true,
215         Node::Item(&Item {
216             kind: ItemKind::Fn(ref sig, ..),
217             ..
218         })
219         | Node::ImplItem(&ImplItem {
220             kind: ImplItemKind::Fn(ref sig, _),
221             ..
222         }) => sig.header.constness == Constness::Const,
223         _ => false,
224     }
225 }
226
227 /// Checks if a `QPath` resolves to a constructor of a `LangItem`.
228 /// For example, use this to check whether a function call or a pattern is `Some(..)`.
229 pub fn is_lang_ctor(cx: &LateContext<'_>, qpath: &QPath<'_>, lang_item: LangItem) -> bool {
230     if let QPath::Resolved(_, path) = qpath {
231         if let Res::Def(DefKind::Ctor(..), ctor_id) = path.res {
232             if let Ok(item_id) = cx.tcx.lang_items().require(lang_item) {
233                 return cx.tcx.parent(ctor_id) == Some(item_id);
234             }
235         }
236     }
237     false
238 }
239
240 /// Returns `true` if this `span` was expanded by any macro.
241 #[must_use]
242 pub fn in_macro(span: Span) -> bool {
243     if span.from_expansion() {
244         !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
245     } else {
246         false
247     }
248 }
249
250 /// Checks if given pattern is a wildcard (`_`)
251 pub fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
252     matches!(pat.kind, PatKind::Wild)
253 }
254
255 /// Checks if the first type parameter is a lang item.
256 pub fn is_ty_param_lang_item(cx: &LateContext<'_>, qpath: &QPath<'tcx>, item: LangItem) -> Option<&'tcx hir::Ty<'tcx>> {
257     let ty = get_qpath_generic_tys(qpath).next()?;
258
259     if let TyKind::Path(qpath) = &ty.kind {
260         cx.qpath_res(qpath, ty.hir_id)
261             .opt_def_id()
262             .map_or(false, |id| {
263                 cx.tcx.lang_items().require(item).map_or(false, |lang_id| id == lang_id)
264             })
265             .then(|| ty)
266     } else {
267         None
268     }
269 }
270
271 /// Checks if the first type parameter is a diagnostic item.
272 pub fn is_ty_param_diagnostic_item(
273     cx: &LateContext<'_>,
274     qpath: &QPath<'tcx>,
275     item: Symbol,
276 ) -> Option<&'tcx hir::Ty<'tcx>> {
277     let ty = get_qpath_generic_tys(qpath).next()?;
278
279     if let TyKind::Path(qpath) = &ty.kind {
280         cx.qpath_res(qpath, ty.hir_id)
281             .opt_def_id()
282             .map_or(false, |id| cx.tcx.is_diagnostic_item(item, id))
283             .then(|| ty)
284     } else {
285         None
286     }
287 }
288
289 /// Checks if the method call given in `expr` belongs to the given trait.
290 /// This is a deprecated function, consider using [`is_trait_method`].
291 pub fn match_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, path: &[&str]) -> bool {
292     let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
293     let trt_id = cx.tcx.trait_of_item(def_id);
294     trt_id.map_or(false, |trt_id| match_def_path(cx, trt_id, path))
295 }
296
297 /// Checks if a method is defined in an impl of a diagnostic item
298 pub fn is_diag_item_method(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbol) -> bool {
299     if let Some(impl_did) = cx.tcx.impl_of_method(def_id) {
300         if let Some(adt) = cx.tcx.type_of(impl_did).ty_adt_def() {
301             return cx.tcx.is_diagnostic_item(diag_item, adt.did);
302         }
303     }
304     false
305 }
306
307 /// Checks if a method is in a diagnostic item trait
308 pub fn is_diag_trait_item(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbol) -> bool {
309     if let Some(trait_did) = cx.tcx.trait_of_item(def_id) {
310         return cx.tcx.is_diagnostic_item(diag_item, trait_did);
311     }
312     false
313 }
314
315 /// Checks if the method call given in `expr` belongs to the given trait.
316 pub fn is_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, diag_item: Symbol) -> bool {
317     cx.typeck_results()
318         .type_dependent_def_id(expr.hir_id)
319         .map_or(false, |did| is_diag_trait_item(cx, did, diag_item))
320 }
321
322 /// Checks if an expression references a variable of the given name.
323 pub fn match_var(expr: &Expr<'_>, var: Symbol) -> bool {
324     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
325         if let [p] = path.segments {
326             return p.ident.name == var;
327         }
328     }
329     false
330 }
331
332 pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
333     match *path {
334         QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
335         QPath::TypeRelative(_, ref seg) => seg,
336         QPath::LangItem(..) => panic!("last_path_segment: lang item has no path segments"),
337     }
338 }
339
340 pub fn get_qpath_generics(path: &QPath<'tcx>) -> Option<&'tcx GenericArgs<'tcx>> {
341     match path {
342         QPath::Resolved(_, p) => p.segments.last().and_then(|s| s.args),
343         QPath::TypeRelative(_, s) => s.args,
344         QPath::LangItem(..) => None,
345     }
346 }
347
348 pub fn get_qpath_generic_tys(path: &QPath<'tcx>) -> impl Iterator<Item = &'tcx hir::Ty<'tcx>> {
349     get_qpath_generics(path)
350         .map_or([].as_ref(), |a| a.args)
351         .iter()
352         .filter_map(|a| {
353             if let hir::GenericArg::Type(ty) = a {
354                 Some(ty)
355             } else {
356                 None
357             }
358         })
359 }
360
361 pub fn single_segment_path<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
362     match *path {
363         QPath::Resolved(_, ref path) => path.segments.get(0),
364         QPath::TypeRelative(_, ref seg) => Some(seg),
365         QPath::LangItem(..) => None,
366     }
367 }
368
369 /// THIS METHOD IS DEPRECATED and will eventually be removed since it does not match against the
370 /// entire path or resolved `DefId`. Prefer using `match_def_path`. Consider getting a `DefId` from
371 /// `QPath::Resolved.1.res.opt_def_id()`.
372 ///
373 /// Matches a `QPath` against a slice of segment string literals.
374 ///
375 /// There is also `match_path` if you are dealing with a `rustc_hir::Path` instead of a
376 /// `rustc_hir::QPath`.
377 ///
378 /// # Examples
379 /// ```rust,ignore
380 /// match_qpath(path, &["std", "rt", "begin_unwind"])
381 /// ```
382 pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool {
383     match *path {
384         QPath::Resolved(_, ref path) => match_path(path, segments),
385         QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
386             TyKind::Path(ref inner_path) => {
387                 if let [prefix @ .., end] = segments {
388                     if match_qpath(inner_path, prefix) {
389                         return segment.ident.name.as_str() == *end;
390                     }
391                 }
392                 false
393             },
394             _ => false,
395         },
396         QPath::LangItem(..) => false,
397     }
398 }
399
400 /// THIS METHOD IS DEPRECATED and will eventually be removed since it does not match against the
401 /// entire path or resolved `DefId`. Prefer using `match_def_path`. Consider getting a `DefId` from
402 /// `QPath::Resolved.1.res.opt_def_id()`.
403 ///
404 /// Matches a `Path` against a slice of segment string literals.
405 ///
406 /// There is also `match_qpath` if you are dealing with a `rustc_hir::QPath` instead of a
407 /// `rustc_hir::Path`.
408 ///
409 /// # Examples
410 ///
411 /// ```rust,ignore
412 /// if match_path(&trait_ref.path, &paths::HASH) {
413 ///     // This is the `std::hash::Hash` trait.
414 /// }
415 ///
416 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
417 ///     // This is a `rustc_middle::lint::Lint`.
418 /// }
419 /// ```
420 pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool {
421     path.segments
422         .iter()
423         .rev()
424         .zip(segments.iter().rev())
425         .all(|(a, b)| a.ident.name.as_str() == *b)
426 }
427
428 /// Matches a `Path` against a slice of segment string literals, e.g.
429 ///
430 /// # Examples
431 /// ```rust,ignore
432 /// match_path_ast(path, &["std", "rt", "begin_unwind"])
433 /// ```
434 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
435     path.segments
436         .iter()
437         .rev()
438         .zip(segments.iter().rev())
439         .all(|(a, b)| a.ident.name.as_str() == *b)
440 }
441
442 /// If the expression is a path to a local, returns the canonical `HirId` of the local.
443 pub fn path_to_local(expr: &Expr<'_>) -> Option<HirId> {
444     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
445         if let Res::Local(id) = path.res {
446             return Some(id);
447         }
448     }
449     None
450 }
451
452 /// Returns true if the expression is a path to a local with the specified `HirId`.
453 /// Use this function to see if an expression matches a function argument or a match binding.
454 pub fn path_to_local_id(expr: &Expr<'_>, id: HirId) -> bool {
455     path_to_local(expr) == Some(id)
456 }
457
458 /// Gets the definition associated to a path.
459 #[allow(clippy::shadow_unrelated)] // false positive #6563
460 pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Res {
461     macro_rules! try_res {
462         ($e:expr) => {
463             match $e {
464                 Some(e) => e,
465                 None => return Res::Err,
466             }
467         };
468     }
469     fn item_child_by_name<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, name: &str) -> Option<&'tcx Export<HirId>> {
470         tcx.item_children(def_id)
471             .iter()
472             .find(|item| item.ident.name.as_str() == name)
473     }
474
475     let (krate, first, path) = match *path {
476         [krate, first, ref path @ ..] => (krate, first, path),
477         _ => return Res::Err,
478     };
479     let tcx = cx.tcx;
480     let crates = tcx.crates();
481     let krate = try_res!(crates.iter().find(|&&num| tcx.crate_name(num).as_str() == krate));
482     let first = try_res!(item_child_by_name(tcx, krate.as_def_id(), first));
483     let last = path
484         .iter()
485         .copied()
486         // `get_def_path` seems to generate these empty segments for extern blocks.
487         // We can just ignore them.
488         .filter(|segment| !segment.is_empty())
489         // for each segment, find the child item
490         .try_fold(first, |item, segment| {
491             let def_id = item.res.def_id();
492             if let Some(item) = item_child_by_name(tcx, def_id, segment) {
493                 Some(item)
494             } else if matches!(item.res, Res::Def(DefKind::Enum | DefKind::Struct, _)) {
495                 // it is not a child item so check inherent impl items
496                 tcx.inherent_impls(def_id)
497                     .iter()
498                     .find_map(|&impl_def_id| item_child_by_name(tcx, impl_def_id, segment))
499             } else {
500                 None
501             }
502         });
503     try_res!(last).res
504 }
505
506 /// Convenience function to get the `DefId` of a trait by path.
507 /// It could be a trait or trait alias.
508 pub fn get_trait_def_id(cx: &LateContext<'_>, path: &[&str]) -> Option<DefId> {
509     match path_to_res(cx, path) {
510         Res::Def(DefKind::Trait | DefKind::TraitAlias, trait_id) => Some(trait_id),
511         _ => None,
512     }
513 }
514
515 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
516 ///
517 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
518 ///
519 /// ```rust
520 /// struct Point(isize, isize);
521 ///
522 /// impl std::ops::Add for Point {
523 ///     type Output = Self;
524 ///
525 ///     fn add(self, other: Self) -> Self {
526 ///         Point(0, 0)
527 ///     }
528 /// }
529 /// ```
530 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> {
531     // Get the implemented trait for the current function
532     let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
533     if_chain! {
534         if parent_impl != hir::CRATE_HIR_ID;
535         if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
536         if let hir::ItemKind::Impl(impl_) = &item.kind;
537         then { return impl_.of_trait.as_ref(); }
538     }
539     None
540 }
541
542 /// Checks if the top level expression can be moved into a closure as is.
543 pub fn can_move_expr_to_closure_no_visit(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, jump_targets: &[HirId]) -> bool {
544     match expr.kind {
545         ExprKind::Break(Destination { target_id: Ok(id), .. }, _)
546         | ExprKind::Continue(Destination { target_id: Ok(id), .. })
547             if jump_targets.contains(&id) =>
548         {
549             true
550         },
551         ExprKind::Break(..)
552         | ExprKind::Continue(_)
553         | ExprKind::Ret(_)
554         | ExprKind::Yield(..)
555         | ExprKind::InlineAsm(_)
556         | ExprKind::LlvmInlineAsm(_) => false,
557         // Accessing a field of a local value can only be done if the type isn't
558         // partially moved.
559         ExprKind::Field(base_expr, _)
560             if matches!(
561                 base_expr.kind,
562                 ExprKind::Path(QPath::Resolved(_, Path { res: Res::Local(_), .. }))
563             ) && can_partially_move_ty(cx, cx.typeck_results().expr_ty(base_expr)) =>
564         {
565             // TODO: check if the local has been partially moved. Assume it has for now.
566             false
567         }
568         _ => true,
569     }
570 }
571
572 /// Checks if the expression can be moved into a closure as is.
573 pub fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
574     struct V<'cx, 'tcx> {
575         cx: &'cx LateContext<'tcx>,
576         loops: Vec<HirId>,
577         allow_closure: bool,
578     }
579     impl Visitor<'tcx> for V<'_, 'tcx> {
580         type Map = ErasedMap<'tcx>;
581         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
582             NestedVisitorMap::None
583         }
584
585         fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
586             if !self.allow_closure {
587                 return;
588             }
589             if let ExprKind::Loop(b, ..) = e.kind {
590                 self.loops.push(e.hir_id);
591                 self.visit_block(b);
592                 self.loops.pop();
593             } else {
594                 self.allow_closure &= can_move_expr_to_closure_no_visit(self.cx, e, &self.loops);
595                 walk_expr(self, e);
596             }
597         }
598     }
599
600     let mut v = V {
601         cx,
602         allow_closure: true,
603         loops: Vec::new(),
604     };
605     v.visit_expr(expr);
606     v.allow_closure
607 }
608
609 /// Returns the method names and argument list of nested method call expressions that make up
610 /// `expr`. method/span lists are sorted with the most recent call first.
611 pub fn method_calls<'tcx>(
612     expr: &'tcx Expr<'tcx>,
613     max_depth: usize,
614 ) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
615     let mut method_names = Vec::with_capacity(max_depth);
616     let mut arg_lists = Vec::with_capacity(max_depth);
617     let mut spans = Vec::with_capacity(max_depth);
618
619     let mut current = expr;
620     for _ in 0..max_depth {
621         if let ExprKind::MethodCall(path, span, args, _) = &current.kind {
622             if args.iter().any(|e| e.span.from_expansion()) {
623                 break;
624             }
625             method_names.push(path.ident.name);
626             arg_lists.push(&**args);
627             spans.push(*span);
628             current = &args[0];
629         } else {
630             break;
631         }
632     }
633
634     (method_names, arg_lists, spans)
635 }
636
637 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
638 ///
639 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
640 /// `method_chain_args(expr, &["bar", "baz"])` will return a `Vec`
641 /// containing the `Expr`s for
642 /// `.bar()` and `.baz()`
643 pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
644     let mut current = expr;
645     let mut matched = Vec::with_capacity(methods.len());
646     for method_name in methods.iter().rev() {
647         // method chains are stored last -> first
648         if let ExprKind::MethodCall(ref path, _, ref args, _) = current.kind {
649             if path.ident.name.as_str() == *method_name {
650                 if args.iter().any(|e| e.span.from_expansion()) {
651                     return None;
652                 }
653                 matched.push(&**args); // build up `matched` backwards
654                 current = &args[0] // go to parent expression
655             } else {
656                 return None;
657             }
658         } else {
659             return None;
660         }
661     }
662     // Reverse `matched` so that it is in the same order as `methods`.
663     matched.reverse();
664     Some(matched)
665 }
666
667 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
668 pub fn is_entrypoint_fn(cx: &LateContext<'_>, def_id: DefId) -> bool {
669     cx.tcx
670         .entry_fn(LOCAL_CRATE)
671         .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id.to_def_id())
672 }
673
674 /// Returns `true` if the expression is in the program's `#[panic_handler]`.
675 pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
676     let parent = cx.tcx.hir().get_parent_item(e.hir_id);
677     let def_id = cx.tcx.hir().local_def_id(parent).to_def_id();
678     Some(def_id) == cx.tcx.lang_items().panic_impl()
679 }
680
681 /// Gets the name of the item the expression is in, if available.
682 pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Symbol> {
683     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
684     match cx.tcx.hir().find(parent_id) {
685         Some(
686             Node::Item(Item { ident, .. })
687             | Node::TraitItem(TraitItem { ident, .. })
688             | Node::ImplItem(ImplItem { ident, .. }),
689         ) => Some(ident.name),
690         _ => None,
691     }
692 }
693
694 /// Gets the name of a `Pat`, if any.
695 pub fn get_pat_name(pat: &Pat<'_>) -> Option<Symbol> {
696     match pat.kind {
697         PatKind::Binding(.., ref spname, _) => Some(spname.name),
698         PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
699         PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
700         _ => None,
701     }
702 }
703
704 pub struct ContainsName {
705     pub name: Symbol,
706     pub result: bool,
707 }
708
709 impl<'tcx> Visitor<'tcx> for ContainsName {
710     type Map = Map<'tcx>;
711
712     fn visit_name(&mut self, _: Span, name: Symbol) {
713         if self.name == name {
714             self.result = true;
715         }
716     }
717     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
718         NestedVisitorMap::None
719     }
720 }
721
722 /// Checks if an `Expr` contains a certain name.
723 pub fn contains_name(name: Symbol, expr: &Expr<'_>) -> bool {
724     let mut cn = ContainsName { name, result: false };
725     cn.visit_expr(expr);
726     cn.result
727 }
728
729 /// Returns `true` if `expr` contains a return expression
730 pub fn contains_return(expr: &hir::Expr<'_>) -> bool {
731     struct RetCallFinder {
732         found: bool,
733     }
734
735     impl<'tcx> hir::intravisit::Visitor<'tcx> for RetCallFinder {
736         type Map = Map<'tcx>;
737
738         fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
739             if self.found {
740                 return;
741             }
742             if let hir::ExprKind::Ret(..) = &expr.kind {
743                 self.found = true;
744             } else {
745                 hir::intravisit::walk_expr(self, expr);
746             }
747         }
748
749         fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
750             hir::intravisit::NestedVisitorMap::None
751         }
752     }
753
754     let mut visitor = RetCallFinder { found: false };
755     visitor.visit_expr(expr);
756     visitor.found
757 }
758
759 struct FindMacroCalls<'a, 'b> {
760     names: &'a [&'b str],
761     result: Vec<Span>,
762 }
763
764 impl<'a, 'b, 'tcx> Visitor<'tcx> for FindMacroCalls<'a, 'b> {
765     type Map = Map<'tcx>;
766
767     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
768         if self.names.iter().any(|fun| is_expn_of(expr.span, fun).is_some()) {
769             self.result.push(expr.span);
770         }
771         // and check sub-expressions
772         intravisit::walk_expr(self, expr);
773     }
774
775     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
776         NestedVisitorMap::None
777     }
778 }
779
780 /// Finds calls of the specified macros in a function body.
781 pub fn find_macro_calls(names: &[&str], body: &Body<'_>) -> Vec<Span> {
782     let mut fmc = FindMacroCalls {
783         names,
784         result: Vec::new(),
785     };
786     fmc.visit_expr(&body.value);
787     fmc.result
788 }
789
790 /// Extends the span to the beginning of the spans line, incl. whitespaces.
791 ///
792 /// ```rust,ignore
793 ///        let x = ();
794 /// //             ^^
795 /// // will be converted to
796 ///        let x = ();
797 /// // ^^^^^^^^^^^^^^
798 /// ```
799 fn line_span<T: LintContext>(cx: &T, span: Span) -> Span {
800     let span = original_sp(span, DUMMY_SP);
801     let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
802     let line_no = source_map_and_line.line;
803     let line_start = source_map_and_line.sf.lines[line_no];
804     Span::new(line_start, span.hi(), span.ctxt())
805 }
806
807 /// Gets the parent node, if any.
808 pub fn get_parent_node(tcx: TyCtxt<'_>, id: HirId) -> Option<Node<'_>> {
809     tcx.hir().parent_iter(id).next().map(|(_, node)| node)
810 }
811
812 /// Gets the parent expression, if any â€“- this is useful to constrain a lint.
813 pub fn get_parent_expr<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
814     match get_parent_node(cx.tcx, e.hir_id) {
815         Some(Node::Expr(parent)) => Some(parent),
816         _ => None,
817     }
818 }
819
820 pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
821     let map = &cx.tcx.hir();
822     let enclosing_node = map
823         .get_enclosing_scope(hir_id)
824         .and_then(|enclosing_id| map.find(enclosing_id));
825     enclosing_node.and_then(|node| match node {
826         Node::Block(block) => Some(block),
827         Node::Item(&Item {
828             kind: ItemKind::Fn(_, _, eid),
829             ..
830         })
831         | Node::ImplItem(&ImplItem {
832             kind: ImplItemKind::Fn(_, eid),
833             ..
834         }) => match cx.tcx.hir().body(eid).value.kind {
835             ExprKind::Block(ref block, _) => Some(block),
836             _ => None,
837         },
838         _ => None,
839     })
840 }
841
842 /// Gets the parent node if it's an impl block.
843 pub fn get_parent_as_impl(tcx: TyCtxt<'_>, id: HirId) -> Option<&Impl<'_>> {
844     let map = tcx.hir();
845     match map.parent_iter(id).next() {
846         Some((
847             _,
848             Node::Item(Item {
849                 kind: ItemKind::Impl(imp),
850                 ..
851             }),
852         )) => Some(imp),
853         _ => None,
854     }
855 }
856
857 /// Checks if the given expression is the else clause of either an `if` or `if let` expression.
858 pub fn is_else_clause(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
859     let map = tcx.hir();
860     let mut iter = map.parent_iter(expr.hir_id);
861     match iter.next() {
862         Some((arm_id, Node::Arm(..))) => matches!(
863             iter.next(),
864             Some((
865                 _,
866                 Node::Expr(Expr {
867                     kind: ExprKind::Match(_, [_, else_arm], MatchSource::IfLetDesugar { .. }),
868                     ..
869                 })
870             ))
871             if else_arm.hir_id == arm_id
872         ),
873         Some((
874             _,
875             Node::Expr(Expr {
876                 kind: ExprKind::If(_, _, Some(else_expr)),
877                 ..
878             }),
879         )) => else_expr.hir_id == expr.hir_id,
880         _ => false,
881     }
882 }
883
884 /// Checks whether the given expression is a constant integer of the given value.
885 /// unlike `is_integer_literal`, this version does const folding
886 pub fn is_integer_const(cx: &LateContext<'_>, e: &Expr<'_>, value: u128) -> bool {
887     if is_integer_literal(e, value) {
888         return true;
889     }
890     let map = cx.tcx.hir();
891     let parent_item = map.get_parent_item(e.hir_id);
892     if let Some((Constant::Int(v), _)) = map
893         .maybe_body_owned_by(parent_item)
894         .and_then(|body_id| constant(cx, cx.tcx.typeck_body(body_id), e))
895     {
896         value == v
897     } else {
898         false
899     }
900 }
901
902 /// Checks whether the given expression is a constant literal of the given value.
903 pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
904     // FIXME: use constant folding
905     if let ExprKind::Lit(ref spanned) = expr.kind {
906         if let LitKind::Int(v, _) = spanned.node {
907             return v == value;
908         }
909     }
910     false
911 }
912
913 /// Returns `true` if the given `Expr` has been coerced before.
914 ///
915 /// Examples of coercions can be found in the Nomicon at
916 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
917 ///
918 /// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
919 /// information on adjustments and coercions.
920 pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
921     cx.typeck_results().adjustments().get(e.hir_id).is_some()
922 }
923
924 /// Returns the pre-expansion span if is this comes from an expansion of the
925 /// macro `name`.
926 /// See also `is_direct_expn_of`.
927 #[must_use]
928 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
929     loop {
930         if span.from_expansion() {
931             let data = span.ctxt().outer_expn_data();
932             let new_span = data.call_site;
933
934             if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
935                 if mac_name.as_str() == name {
936                     return Some(new_span);
937                 }
938             }
939
940             span = new_span;
941         } else {
942             return None;
943         }
944     }
945 }
946
947 /// Returns the pre-expansion span if the span directly comes from an expansion
948 /// of the macro `name`.
949 /// The difference with `is_expn_of` is that in
950 /// ```rust,ignore
951 /// foo!(bar!(42));
952 /// ```
953 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
954 /// `bar!` by
955 /// `is_direct_expn_of`.
956 #[must_use]
957 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
958     if span.from_expansion() {
959         let data = span.ctxt().outer_expn_data();
960         let new_span = data.call_site;
961
962         if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
963             if mac_name.as_str() == name {
964                 return Some(new_span);
965             }
966         }
967     }
968
969     None
970 }
971
972 /// Convenience function to get the return type of a function.
973 pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
974     let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
975     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
976     cx.tcx.erase_late_bound_regions(ret_ty)
977 }
978
979 /// Checks if an expression is constructing a tuple-like enum variant or struct
980 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
981     if let ExprKind::Call(ref fun, _) = expr.kind {
982         if let ExprKind::Path(ref qp) = fun.kind {
983             let res = cx.qpath_res(qp, fun.hir_id);
984             return match res {
985                 def::Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
986                 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
987                 _ => false,
988             };
989         }
990     }
991     false
992 }
993
994 /// Returns `true` if a pattern is refutable.
995 // TODO: should be implemented using rustc/mir_build/thir machinery
996 pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
997     fn is_enum_variant(cx: &LateContext<'_>, qpath: &QPath<'_>, id: HirId) -> bool {
998         matches!(
999             cx.qpath_res(qpath, id),
1000             def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
1001         )
1002     }
1003
1004     fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_>, mut i: I) -> bool {
1005         i.any(|pat| is_refutable(cx, pat))
1006     }
1007
1008     match pat.kind {
1009         PatKind::Wild => false,
1010         PatKind::Binding(_, _, _, pat) => pat.map_or(false, |pat| is_refutable(cx, pat)),
1011         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
1012         PatKind::Lit(..) | PatKind::Range(..) => true,
1013         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
1014         PatKind::Or(ref pats) => {
1015             // TODO: should be the honest check, that pats is exhaustive set
1016             are_refutable(cx, pats.iter().map(|pat| &**pat))
1017         },
1018         PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
1019         PatKind::Struct(ref qpath, ref fields, _) => {
1020             is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| &*field.pat))
1021         },
1022         PatKind::TupleStruct(ref qpath, ref pats, _) => {
1023             is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, pats.iter().map(|pat| &**pat))
1024         },
1025         PatKind::Slice(ref head, ref middle, ref tail) => {
1026             match &cx.typeck_results().node_type(pat.hir_id).kind() {
1027                 rustc_ty::Slice(..) => {
1028                     // [..] is the only irrefutable slice pattern.
1029                     !head.is_empty() || middle.is_none() || !tail.is_empty()
1030                 },
1031                 rustc_ty::Array(..) => {
1032                     are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
1033                 },
1034                 _ => {
1035                     // unreachable!()
1036                     true
1037                 },
1038             }
1039         },
1040     }
1041 }
1042
1043 /// If the pattern is an `or` pattern, call the function once for each sub pattern. Otherwise, call
1044 /// the function once on the given pattern.
1045 pub fn recurse_or_patterns<'tcx, F: FnMut(&'tcx Pat<'tcx>)>(pat: &'tcx Pat<'tcx>, mut f: F) {
1046     if let PatKind::Or(pats) = pat.kind {
1047         pats.iter().cloned().for_each(f)
1048     } else {
1049         f(pat)
1050     }
1051 }
1052
1053 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
1054 /// implementations have.
1055 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
1056     attrs.iter().any(|attr| attr.has_name(sym::automatically_derived))
1057 }
1058
1059 /// Remove blocks around an expression.
1060 ///
1061 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
1062 /// themselves.
1063 pub fn remove_blocks<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
1064     while let ExprKind::Block(ref block, ..) = expr.kind {
1065         match (block.stmts.is_empty(), block.expr.as_ref()) {
1066             (true, Some(e)) => expr = e,
1067             _ => break,
1068         }
1069     }
1070     expr
1071 }
1072
1073 pub fn is_self(slf: &Param<'_>) -> bool {
1074     if let PatKind::Binding(.., name, _) = slf.pat.kind {
1075         name.name == kw::SelfLower
1076     } else {
1077         false
1078     }
1079 }
1080
1081 pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
1082     if_chain! {
1083         if let TyKind::Path(QPath::Resolved(None, ref path)) = slf.kind;
1084         if let Res::SelfTy(..) = path.res;
1085         then {
1086             return true
1087         }
1088     }
1089     false
1090 }
1091
1092 pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
1093     (0..decl.inputs.len()).map(move |i| &body.params[i])
1094 }
1095
1096 /// Checks if a given expression is a match expression expanded from the `?`
1097 /// operator or the `try` macro.
1098 pub fn is_try<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1099     fn is_ok(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1100         if_chain! {
1101             if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
1102             if is_lang_ctor(cx, path, ResultOk);
1103             if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
1104             if path_to_local_id(arm.body, hir_id);
1105             then {
1106                 return true;
1107             }
1108         }
1109         false
1110     }
1111
1112     fn is_err(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1113         if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
1114             is_lang_ctor(cx, path, ResultErr)
1115         } else {
1116             false
1117         }
1118     }
1119
1120     if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
1121         // desugared from a `?` operator
1122         if let MatchSource::TryDesugar = *source {
1123             return Some(expr);
1124         }
1125
1126         if_chain! {
1127             if arms.len() == 2;
1128             if arms[0].guard.is_none();
1129             if arms[1].guard.is_none();
1130             if (is_ok(cx, &arms[0]) && is_err(cx, &arms[1])) ||
1131                 (is_ok(cx, &arms[1]) && is_err(cx, &arms[0]));
1132             then {
1133                 return Some(expr);
1134             }
1135         }
1136     }
1137
1138     None
1139 }
1140
1141 /// Returns `true` if the lint is allowed in the current context
1142 ///
1143 /// Useful for skipping long running code when it's unnecessary
1144 pub fn is_allowed(cx: &LateContext<'_>, lint: &'static Lint, id: HirId) -> bool {
1145     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1146 }
1147
1148 pub fn strip_pat_refs<'hir>(mut pat: &'hir Pat<'hir>) -> &'hir Pat<'hir> {
1149     while let PatKind::Ref(subpat, _) = pat.kind {
1150         pat = subpat;
1151     }
1152     pat
1153 }
1154
1155 pub fn int_bits(tcx: TyCtxt<'_>, ity: rustc_ty::IntTy) -> u64 {
1156     Integer::from_int_ty(&tcx, ity).size().bits()
1157 }
1158
1159 #[allow(clippy::cast_possible_wrap)]
1160 /// Turn a constant int byte representation into an i128
1161 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: rustc_ty::IntTy) -> i128 {
1162     let amt = 128 - int_bits(tcx, ity);
1163     ((u as i128) << amt) >> amt
1164 }
1165
1166 #[allow(clippy::cast_sign_loss)]
1167 /// clip unused bytes
1168 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: rustc_ty::IntTy) -> u128 {
1169     let amt = 128 - int_bits(tcx, ity);
1170     ((u as u128) << amt) >> amt
1171 }
1172
1173 /// clip unused bytes
1174 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: rustc_ty::UintTy) -> u128 {
1175     let bits = Integer::from_uint_ty(&tcx, ity).size().bits();
1176     let amt = 128 - bits;
1177     (u << amt) >> amt
1178 }
1179
1180 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1181     let map = &tcx.hir();
1182     let mut prev_enclosing_node = None;
1183     let mut enclosing_node = node;
1184     while Some(enclosing_node) != prev_enclosing_node {
1185         if is_automatically_derived(map.attrs(enclosing_node)) {
1186             return true;
1187         }
1188         prev_enclosing_node = Some(enclosing_node);
1189         enclosing_node = map.get_parent_item(enclosing_node);
1190     }
1191     false
1192 }
1193
1194 /// Matches a function call with the given path and returns the arguments.
1195 ///
1196 /// Usage:
1197 ///
1198 /// ```rust,ignore
1199 /// if let Some(args) = match_function_call(cx, cmp_max_call, &paths::CMP_MAX);
1200 /// ```
1201 pub fn match_function_call<'tcx>(
1202     cx: &LateContext<'tcx>,
1203     expr: &'tcx Expr<'_>,
1204     path: &[&str],
1205 ) -> Option<&'tcx [Expr<'tcx>]> {
1206     if_chain! {
1207         if let ExprKind::Call(ref fun, ref args) = expr.kind;
1208         if let ExprKind::Path(ref qpath) = fun.kind;
1209         if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
1210         if match_def_path(cx, fun_def_id, path);
1211         then {
1212             return Some(&args)
1213         }
1214     };
1215     None
1216 }
1217
1218 pub fn match_def_path<'tcx>(cx: &LateContext<'tcx>, did: DefId, syms: &[&str]) -> bool {
1219     // We have to convert `syms` to `&[Symbol]` here because rustc's `match_def_path`
1220     // accepts only that. We should probably move to Symbols in Clippy as well.
1221     let syms = syms.iter().map(|p| Symbol::intern(p)).collect::<Vec<Symbol>>();
1222     cx.match_def_path(did, &syms)
1223 }
1224
1225 pub fn match_panic_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx [Expr<'tcx>]> {
1226     match_function_call(cx, expr, &paths::BEGIN_PANIC)
1227         .or_else(|| match_function_call(cx, expr, &paths::BEGIN_PANIC_FMT))
1228         .or_else(|| match_function_call(cx, expr, &paths::PANIC_ANY))
1229         .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC))
1230         .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC_FMT))
1231         .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC_STR))
1232 }
1233
1234 pub fn match_panic_def_id(cx: &LateContext<'_>, did: DefId) -> bool {
1235     match_def_path(cx, did, &paths::BEGIN_PANIC)
1236         || match_def_path(cx, did, &paths::BEGIN_PANIC_FMT)
1237         || match_def_path(cx, did, &paths::PANIC_ANY)
1238         || match_def_path(cx, did, &paths::PANICKING_PANIC)
1239         || match_def_path(cx, did, &paths::PANICKING_PANIC_FMT)
1240         || match_def_path(cx, did, &paths::PANICKING_PANIC_STR)
1241 }
1242
1243 /// Returns the list of condition expressions and the list of blocks in a
1244 /// sequence of `if/else`.
1245 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1246 /// `if a { c } else if b { d } else { e }`.
1247 pub fn if_sequence<'tcx>(mut expr: &'tcx Expr<'tcx>) -> (Vec<&'tcx Expr<'tcx>>, Vec<&'tcx Block<'tcx>>) {
1248     let mut conds = Vec::new();
1249     let mut blocks: Vec<&Block<'_>> = Vec::new();
1250
1251     while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.kind {
1252         conds.push(&**cond);
1253         if let ExprKind::Block(ref block, _) = then_expr.kind {
1254             blocks.push(block);
1255         } else {
1256             panic!("ExprKind::If node is not an ExprKind::Block");
1257         }
1258
1259         if let Some(ref else_expr) = *else_expr {
1260             expr = else_expr;
1261         } else {
1262             break;
1263         }
1264     }
1265
1266     // final `else {..}`
1267     if !blocks.is_empty() {
1268         if let ExprKind::Block(ref block, _) = expr.kind {
1269             blocks.push(&**block);
1270         }
1271     }
1272
1273     (conds, blocks)
1274 }
1275
1276 /// This function returns true if the given expression is the `else` or `if else` part of an if
1277 /// statement
1278 pub fn parent_node_is_if_expr(expr: &Expr<'_>, cx: &LateContext<'_>) -> bool {
1279     let map = cx.tcx.hir();
1280     let parent_id = map.get_parent_node(expr.hir_id);
1281     let parent_node = map.get(parent_id);
1282     matches!(
1283         parent_node,
1284         Node::Expr(Expr {
1285             kind: ExprKind::If(_, _, _),
1286             ..
1287         })
1288     )
1289 }
1290
1291 // Finds the `#[must_use]` attribute, if any
1292 pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
1293     attrs.iter().find(|a| a.has_name(sym::must_use))
1294 }
1295
1296 // check if expr is calling method or function with #[must_use] attribute
1297 pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1298     let did = match expr.kind {
1299         ExprKind::Call(ref path, _) => if_chain! {
1300             if let ExprKind::Path(ref qpath) = path.kind;
1301             if let def::Res::Def(_, did) = cx.qpath_res(qpath, path.hir_id);
1302             then {
1303                 Some(did)
1304             } else {
1305                 None
1306             }
1307         },
1308         ExprKind::MethodCall(_, _, _, _) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1309         _ => None,
1310     };
1311
1312     did.map_or(false, |did| must_use_attr(&cx.tcx.get_attrs(did)).is_some())
1313 }
1314
1315 pub fn get_expr_use_node(tcx: TyCtxt<'tcx>, expr: &Expr<'_>) -> Option<Node<'tcx>> {
1316     let map = tcx.hir();
1317     let mut child_id = expr.hir_id;
1318     let mut iter = map.parent_iter(child_id);
1319     loop {
1320         match iter.next() {
1321             None => break None,
1322             Some((id, Node::Block(_))) => child_id = id,
1323             Some((id, Node::Arm(arm))) if arm.body.hir_id == child_id => child_id = id,
1324             Some((_, Node::Expr(expr))) => match expr.kind {
1325                 ExprKind::Break(
1326                     Destination {
1327                         target_id: Ok(dest), ..
1328                     },
1329                     _,
1330                 ) => {
1331                     iter = map.parent_iter(dest);
1332                     child_id = dest;
1333                 },
1334                 ExprKind::DropTemps(_) | ExprKind::Block(..) => child_id = expr.hir_id,
1335                 ExprKind::If(control_expr, ..) | ExprKind::Match(control_expr, ..)
1336                     if control_expr.hir_id != child_id =>
1337                 {
1338                     child_id = expr.hir_id
1339                 },
1340                 _ => break Some(Node::Expr(expr)),
1341             },
1342             Some((_, node)) => break Some(node),
1343         }
1344     }
1345 }
1346
1347 pub fn is_expr_used(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1348     !matches!(
1349         get_expr_use_node(tcx, expr),
1350         Some(Node::Stmt(Stmt {
1351             kind: StmtKind::Expr(_) | StmtKind::Semi(_),
1352             ..
1353         }))
1354     )
1355 }
1356
1357 pub fn get_expr_use_or_unification_node(tcx: TyCtxt<'tcx>, expr: &Expr<'_>) -> Option<Node<'tcx>> {
1358     let map = tcx.hir();
1359     let mut child_id = expr.hir_id;
1360     let mut iter = map.parent_iter(child_id);
1361     loop {
1362         match iter.next() {
1363             None => break None,
1364             Some((id, Node::Block(_))) => child_id = id,
1365             Some((id, Node::Arm(arm))) if arm.body.hir_id == child_id => child_id = id,
1366             Some((_, Node::Expr(expr))) => match expr.kind {
1367                 ExprKind::Match(_, [arm], _) if arm.hir_id == child_id => child_id = expr.hir_id,
1368                 ExprKind::Block(..) | ExprKind::DropTemps(_) => child_id = expr.hir_id,
1369                 ExprKind::If(_, then_expr, None) if then_expr.hir_id == child_id => break None,
1370                 _ => break Some(Node::Expr(expr)),
1371             },
1372             Some((_, node)) => break Some(node),
1373         }
1374     }
1375 }
1376
1377 pub fn is_expr_used_or_unified(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1378     !matches!(
1379         get_expr_use_or_unification_node(tcx, expr),
1380         None | Some(Node::Stmt(Stmt {
1381             kind: StmtKind::Expr(_) | StmtKind::Semi(_),
1382             ..
1383         }))
1384     )
1385 }
1386
1387 pub fn is_expr_final_block_expr(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
1388     matches!(get_parent_node(tcx, expr.hir_id), Some(Node::Block(..)))
1389 }
1390
1391 pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool {
1392     cx.tcx.hir().attrs(hir::CRATE_HIR_ID).iter().any(|attr| {
1393         if let ast::AttrKind::Normal(ref attr, _) = attr.kind {
1394             attr.path == sym::no_std
1395         } else {
1396             false
1397         }
1398     })
1399 }
1400
1401 /// Check if parent of a hir node is a trait implementation block.
1402 /// For example, `f` in
1403 /// ```rust,ignore
1404 /// impl Trait for S {
1405 ///     fn f() {}
1406 /// }
1407 /// ```
1408 pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool {
1409     if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
1410         matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }))
1411     } else {
1412         false
1413     }
1414 }
1415
1416 /// Check if it's even possible to satisfy the `where` clause for the item.
1417 ///
1418 /// `trivial_bounds` feature allows functions with unsatisfiable bounds, for example:
1419 ///
1420 /// ```ignore
1421 /// fn foo() where i32: Iterator {
1422 ///     for _ in 2i32 {}
1423 /// }
1424 /// ```
1425 pub fn fn_has_unsatisfiable_preds(cx: &LateContext<'_>, did: DefId) -> bool {
1426     use rustc_trait_selection::traits;
1427     let predicates = cx
1428         .tcx
1429         .predicates_of(did)
1430         .predicates
1431         .iter()
1432         .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
1433     traits::impossible_predicates(
1434         cx.tcx,
1435         traits::elaborate_predicates(cx.tcx, predicates)
1436             .map(|o| o.predicate)
1437             .collect::<Vec<_>>(),
1438     )
1439 }
1440
1441 /// Returns the `DefId` of the callee if the given expression is a function or method call.
1442 pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
1443     match &expr.kind {
1444         ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1445         ExprKind::Call(
1446             Expr {
1447                 kind: ExprKind::Path(qpath),
1448                 hir_id: path_hir_id,
1449                 ..
1450             },
1451             ..,
1452         ) => cx.typeck_results().qpath_res(qpath, *path_hir_id).opt_def_id(),
1453         _ => None,
1454     }
1455 }
1456
1457 /// This function checks if any of the lints in the slice is enabled for the provided `HirId`.
1458 /// A lint counts as enabled with any of the levels: `Level::Forbid` | `Level::Deny` | `Level::Warn`
1459 ///
1460 /// ```ignore
1461 /// #[deny(clippy::YOUR_AWESOME_LINT)]
1462 /// println!("Hello, World!"); // <- Clippy code: run_lints(cx, &[YOUR_AWESOME_LINT], id) == true
1463 ///
1464 /// #[allow(clippy::YOUR_AWESOME_LINT)]
1465 /// println!("See you soon!"); // <- Clippy code: run_lints(cx, &[YOUR_AWESOME_LINT], id) == false
1466 /// ```
1467 pub fn run_lints(cx: &LateContext<'_>, lints: &[&'static Lint], id: HirId) -> bool {
1468     lints.iter().any(|lint| {
1469         matches!(
1470             cx.tcx.lint_level_at_node(lint, id),
1471             (Level::Forbid | Level::Deny | Level::Warn, _)
1472         )
1473     })
1474 }
1475
1476 /// Returns Option<String> where String is a textual representation of the type encapsulated in the
1477 /// slice iff the given expression is a slice of primitives (as defined in the
1478 /// `is_recursively_primitive_type` function) and None otherwise.
1479 pub fn is_slice_of_primitives(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
1480     let expr_type = cx.typeck_results().expr_ty_adjusted(expr);
1481     let expr_kind = expr_type.kind();
1482     let is_primitive = match expr_kind {
1483         rustc_ty::Slice(element_type) => is_recursively_primitive_type(element_type),
1484         rustc_ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), &rustc_ty::Slice(_)) => {
1485             if let rustc_ty::Slice(element_type) = inner_ty.kind() {
1486                 is_recursively_primitive_type(element_type)
1487             } else {
1488                 unreachable!()
1489             }
1490         },
1491         _ => false,
1492     };
1493
1494     if is_primitive {
1495         // if we have wrappers like Array, Slice or Tuple, print these
1496         // and get the type enclosed in the slice ref
1497         match expr_type.peel_refs().walk().nth(1).unwrap().expect_ty().kind() {
1498             rustc_ty::Slice(..) => return Some("slice".into()),
1499             rustc_ty::Array(..) => return Some("array".into()),
1500             rustc_ty::Tuple(..) => return Some("tuple".into()),
1501             _ => {
1502                 // is_recursively_primitive_type() should have taken care
1503                 // of the rest and we can rely on the type that is found
1504                 let refs_peeled = expr_type.peel_refs();
1505                 return Some(refs_peeled.walk().last().unwrap().to_string());
1506             },
1507         }
1508     }
1509     None
1510 }
1511
1512 /// returns list of all pairs (a, b) from `exprs` such that `eq(a, b)`
1513 /// `hash` must be comformed with `eq`
1514 pub fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
1515 where
1516     Hash: Fn(&T) -> u64,
1517     Eq: Fn(&T, &T) -> bool,
1518 {
1519     if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
1520         return vec![(&exprs[0], &exprs[1])];
1521     }
1522
1523     let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
1524
1525     let mut map: FxHashMap<_, Vec<&_>> =
1526         FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
1527
1528     for expr in exprs {
1529         match map.entry(hash(expr)) {
1530             Entry::Occupied(mut o) => {
1531                 for o in o.get() {
1532                     if eq(o, expr) {
1533                         match_expr_list.push((o, expr));
1534                     }
1535                 }
1536                 o.get_mut().push(expr);
1537             },
1538             Entry::Vacant(v) => {
1539                 v.insert(vec![expr]);
1540             },
1541         }
1542     }
1543
1544     match_expr_list
1545 }
1546
1547 /// Peels off all references on the pattern. Returns the underlying pattern and the number of
1548 /// references removed.
1549 pub fn peel_hir_pat_refs(pat: &'a Pat<'a>) -> (&'a Pat<'a>, usize) {
1550     fn peel(pat: &'a Pat<'a>, count: usize) -> (&'a Pat<'a>, usize) {
1551         if let PatKind::Ref(pat, _) = pat.kind {
1552             peel(pat, count + 1)
1553         } else {
1554             (pat, count)
1555         }
1556     }
1557     peel(pat, 0)
1558 }
1559
1560 /// Peels of expressions while the given closure returns `Some`.
1561 pub fn peel_hir_expr_while<'tcx>(
1562     mut expr: &'tcx Expr<'tcx>,
1563     mut f: impl FnMut(&'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>>,
1564 ) -> &'tcx Expr<'tcx> {
1565     while let Some(e) = f(expr) {
1566         expr = e;
1567     }
1568     expr
1569 }
1570
1571 /// Peels off up to the given number of references on the expression. Returns the underlying
1572 /// expression and the number of references removed.
1573 pub fn peel_n_hir_expr_refs(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<'a>, usize) {
1574     let mut remaining = count;
1575     let e = peel_hir_expr_while(expr, |e| match e.kind {
1576         ExprKind::AddrOf(BorrowKind::Ref, _, e) if remaining != 0 => {
1577             remaining -= 1;
1578             Some(e)
1579         },
1580         _ => None,
1581     });
1582     (e, count - remaining)
1583 }
1584
1585 /// Peels off all references on the expression. Returns the underlying expression and the number of
1586 /// references removed.
1587 pub fn peel_hir_expr_refs(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) {
1588     let mut count = 0;
1589     let e = peel_hir_expr_while(expr, |e| match e.kind {
1590         ExprKind::AddrOf(BorrowKind::Ref, _, e) => {
1591             count += 1;
1592             Some(e)
1593         },
1594         _ => None,
1595     });
1596     (e, count)
1597 }
1598
1599 #[macro_export]
1600 macro_rules! unwrap_cargo_metadata {
1601     ($cx: ident, $lint: ident, $deps: expr) => {{
1602         let mut command = cargo_metadata::MetadataCommand::new();
1603         if !$deps {
1604             command.no_deps();
1605         }
1606
1607         match command.exec() {
1608             Ok(metadata) => metadata,
1609             Err(err) => {
1610                 span_lint($cx, $lint, DUMMY_SP, &format!("could not read cargo metadata: {}", err));
1611                 return;
1612             },
1613         }
1614     }};
1615 }
1616
1617 pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
1618     if_chain! {
1619         if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
1620         if let Res::Def(_, def_id) = path.res;
1621         then {
1622             cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr)
1623         } else {
1624             false
1625         }
1626     }
1627 }