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