]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
Auto merge of #5010 - lzutao:recurse-remove_blocks, r=phansch
[rust.git] / clippy_lints / src / utils / mod.rs
1 #[macro_use]
2 pub mod sym;
3
4 pub mod attrs;
5 pub mod author;
6 pub mod camel_case;
7 pub mod comparisons;
8 pub mod conf;
9 pub mod constants;
10 mod diagnostics;
11 pub mod higher;
12 mod hir_utils;
13 pub mod inspector;
14 pub mod internal_lints;
15 pub mod paths;
16 pub mod ptr;
17 pub mod sugg;
18 pub mod usage;
19 pub use self::attrs::*;
20 pub use self::diagnostics::*;
21 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
22
23 use std::borrow::Cow;
24 use std::mem;
25
26 use if_chain::if_chain;
27 use matches::matches;
28 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
29 use rustc::lint::{LateContext, Level, Lint, LintContext};
30 use rustc::traits;
31 use rustc::ty::{
32     self,
33     layout::{self, IntegerExt},
34     subst::GenericArg,
35     Binder, Ty, TyCtxt,
36 };
37 use rustc_errors::Applicability;
38 use rustc_hir as hir;
39 use rustc_hir::def::{DefKind, Res};
40 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
41 use rustc_hir::Node;
42 use rustc_hir::*;
43 use rustc_span::hygiene::ExpnKind;
44 use rustc_span::source_map::{Span, DUMMY_SP};
45 use rustc_span::symbol::{kw, Symbol};
46 use smallvec::SmallVec;
47 use syntax::ast::{self, Attribute, LitKind};
48 use syntax::attr;
49
50 use crate::consts::{constant, Constant};
51 use crate::reexport::*;
52
53 /// Returns `true` if the two spans come from differing expansions (i.e., one is
54 /// from a macro and one isn't).
55 #[must_use]
56 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
57     rhs.ctxt() != lhs.ctxt()
58 }
59
60 /// Returns `true` if the given `NodeId` is inside a constant context
61 ///
62 /// # Example
63 ///
64 /// ```rust,ignore
65 /// if in_constant(cx, expr.hir_id) {
66 ///     // Do something
67 /// }
68 /// ```
69 pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool {
70     let parent_id = cx.tcx.hir().get_parent_item(id);
71     match cx.tcx.hir().get(parent_id) {
72         Node::Item(&Item {
73             kind: ItemKind::Const(..),
74             ..
75         })
76         | Node::TraitItem(&TraitItem {
77             kind: TraitItemKind::Const(..),
78             ..
79         })
80         | Node::ImplItem(&ImplItem {
81             kind: ImplItemKind::Const(..),
82             ..
83         })
84         | Node::AnonConst(_)
85         | Node::Item(&Item {
86             kind: ItemKind::Static(..),
87             ..
88         }) => true,
89         Node::Item(&Item {
90             kind: ItemKind::Fn(ref sig, ..),
91             ..
92         })
93         | Node::ImplItem(&ImplItem {
94             kind: ImplItemKind::Method(ref sig, _),
95             ..
96         }) => sig.header.constness == Constness::Const,
97         _ => false,
98     }
99 }
100
101 /// Returns `true` if this `span` was expanded by any macro.
102 #[must_use]
103 pub fn in_macro(span: Span) -> bool {
104     if span.from_expansion() {
105         if let ExpnKind::Desugaring(..) = span.ctxt().outer_expn_data().kind {
106             false
107         } else {
108             true
109         }
110     } else {
111         false
112     }
113 }
114 // If the snippet is empty, it's an attribute that was inserted during macro
115 // expansion and we want to ignore those, because they could come from external
116 // sources that the user has no control over.
117 // For some reason these attributes don't have any expansion info on them, so
118 // we have to check it this way until there is a better way.
119 pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
120     if let Some(snippet) = snippet_opt(cx, span) {
121         if snippet.is_empty() {
122             return false;
123         }
124     }
125     true
126 }
127
128 /// Checks if type is struct, enum or union type with the given def path.
129 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
130     match ty.kind {
131         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
132         _ => false,
133     }
134 }
135
136 /// Checks if the type is equal to a diagnostic item
137 pub fn is_type_diagnostic_item(cx: &LateContext<'_, '_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
138     match ty.kind {
139         ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
140         _ => false,
141     }
142 }
143
144 /// Checks if the method call given in `expr` belongs to the given trait.
145 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr<'_>, path: &[&str]) -> bool {
146     let def_id = cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
147     let trt_id = cx.tcx.trait_of_item(def_id);
148     if let Some(trt_id) = trt_id {
149         match_def_path(cx, trt_id, path)
150     } else {
151         false
152     }
153 }
154
155 /// Checks if an expression references a variable of the given name.
156 pub fn match_var(expr: &Expr<'_>, var: Name) -> bool {
157     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
158         if path.segments.len() == 1 && path.segments[0].ident.name == var {
159             return true;
160         }
161     }
162     false
163 }
164
165 pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
166     match *path {
167         QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
168         QPath::TypeRelative(_, ref seg) => seg,
169     }
170 }
171
172 pub fn single_segment_path<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
173     match *path {
174         QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
175         QPath::Resolved(..) => None,
176         QPath::TypeRelative(_, ref seg) => Some(seg),
177     }
178 }
179
180 /// Matches a `QPath` against a slice of segment string literals.
181 ///
182 /// There is also `match_path` if you are dealing with a `rustc_hir::Path` instead of a
183 /// `rustc_hir::QPath`.
184 ///
185 /// # Examples
186 /// ```rust,ignore
187 /// match_qpath(path, &["std", "rt", "begin_unwind"])
188 /// ```
189 pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool {
190     match *path {
191         QPath::Resolved(_, ref path) => match_path(path, segments),
192         QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
193             TyKind::Path(ref inner_path) => {
194                 !segments.is_empty()
195                     && match_qpath(inner_path, &segments[..(segments.len() - 1)])
196                     && segment.ident.name.as_str() == segments[segments.len() - 1]
197             },
198             _ => false,
199         },
200     }
201 }
202
203 /// Matches a `Path` against a slice of segment string literals.
204 ///
205 /// There is also `match_qpath` if you are dealing with a `rustc_hir::QPath` instead of a
206 /// `rustc_hir::Path`.
207 ///
208 /// # Examples
209 ///
210 /// ```rust,ignore
211 /// if match_path(&trait_ref.path, &paths::HASH) {
212 ///     // This is the `std::hash::Hash` trait.
213 /// }
214 ///
215 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
216 ///     // This is a `rustc::lint::Lint`.
217 /// }
218 /// ```
219 pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool {
220     path.segments
221         .iter()
222         .rev()
223         .zip(segments.iter().rev())
224         .all(|(a, b)| a.ident.name.as_str() == *b)
225 }
226
227 /// Matches a `Path` against a slice of segment string literals, e.g.
228 ///
229 /// # Examples
230 /// ```rust,ignore
231 /// match_qpath(path, &["std", "rt", "begin_unwind"])
232 /// ```
233 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
234     path.segments
235         .iter()
236         .rev()
237         .zip(segments.iter().rev())
238         .all(|(a, b)| a.ident.name.as_str() == *b)
239 }
240
241 /// Gets the definition associated to a path.
242 pub fn path_to_res(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Res> {
243     let crates = cx.tcx.crates();
244     let krate = crates
245         .iter()
246         .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]);
247     if let Some(krate) = krate {
248         let krate = DefId {
249             krate: *krate,
250             index: CRATE_DEF_INDEX,
251         };
252         let mut items = cx.tcx.item_children(krate);
253         let mut path_it = path.iter().skip(1).peekable();
254
255         loop {
256             let segment = match path_it.next() {
257                 Some(segment) => segment,
258                 None => return None,
259             };
260
261             let result = SmallVec::<[_; 8]>::new();
262             for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
263                 if item.ident.name.as_str() == *segment {
264                     if path_it.peek().is_none() {
265                         return Some(item.res);
266                     }
267
268                     items = cx.tcx.item_children(item.res.def_id());
269                     break;
270                 }
271             }
272         }
273     } else {
274         None
275     }
276 }
277
278 pub fn qpath_res(cx: &LateContext<'_, '_>, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
279     match qpath {
280         hir::QPath::Resolved(_, path) => path.res,
281         hir::QPath::TypeRelative(..) => {
282             if cx.tcx.has_typeck_tables(id.owner_def_id()) {
283                 cx.tcx.typeck_tables_of(id.owner_def_id()).qpath_res(qpath, id)
284             } else {
285                 Res::Err
286             }
287         },
288     }
289 }
290
291 /// Convenience function to get the `DefId` of a trait by path.
292 /// It could be a trait or trait alias.
293 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
294     let res = match path_to_res(cx, path) {
295         Some(res) => res,
296         None => return None,
297     };
298
299     match res {
300         Res::Def(DefKind::Trait, trait_id) | Res::Def(DefKind::TraitAlias, trait_id) => Some(trait_id),
301         Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path),
302         _ => None,
303     }
304 }
305
306 /// Checks whether a type implements a trait.
307 /// See also `get_trait_def_id`.
308 pub fn implements_trait<'a, 'tcx>(
309     cx: &LateContext<'a, 'tcx>,
310     ty: Ty<'tcx>,
311     trait_id: DefId,
312     ty_params: &[GenericArg<'tcx>],
313 ) -> bool {
314     let ty = cx.tcx.erase_regions(&ty);
315     let obligation = cx.tcx.predicate_for_trait_def(
316         cx.param_env,
317         traits::ObligationCause::dummy(),
318         trait_id,
319         0,
320         ty,
321         ty_params,
322     );
323     cx.tcx
324         .infer_ctxt()
325         .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
326 }
327
328 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
329 ///
330 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
331 ///
332 /// ```rust
333 /// struct Point(isize, isize);
334 ///
335 /// impl std::ops::Add for Point {
336 ///     type Output = Self;
337 ///
338 ///     fn add(self, other: Self) -> Self {
339 ///         Point(0, 0)
340 ///     }
341 /// }
342 /// ```
343 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'_, 'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> {
344     // Get the implemented trait for the current function
345     let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
346     if_chain! {
347         if parent_impl != hir::CRATE_HIR_ID;
348         if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
349         if let hir::ItemKind::Impl(_, _, _, _, trait_ref, _, _) = &item.kind;
350         then { return trait_ref.as_ref(); }
351     }
352     None
353 }
354
355 /// Checks whether this type implements `Drop`.
356 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
357     match ty.ty_adt_def() {
358         Some(def) => def.has_dtor(cx.tcx),
359         _ => false,
360     }
361 }
362
363 /// Returns the method names and argument list of nested method call expressions that make up
364 /// `expr`. method/span lists are sorted with the most recent call first.
365 pub fn method_calls<'tcx>(
366     expr: &'tcx Expr<'tcx>,
367     max_depth: usize,
368 ) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
369     let mut method_names = Vec::with_capacity(max_depth);
370     let mut arg_lists = Vec::with_capacity(max_depth);
371     let mut spans = Vec::with_capacity(max_depth);
372
373     let mut current = expr;
374     for _ in 0..max_depth {
375         if let ExprKind::MethodCall(path, span, args) = &current.kind {
376             if args.iter().any(|e| e.span.from_expansion()) {
377                 break;
378             }
379             method_names.push(path.ident.name);
380             arg_lists.push(&**args);
381             spans.push(*span);
382             current = &args[0];
383         } else {
384             break;
385         }
386     }
387
388     (method_names, arg_lists, spans)
389 }
390
391 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
392 ///
393 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
394 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
395 /// containing the `Expr`s for
396 /// `.bar()` and `.baz()`
397 pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
398     let mut current = expr;
399     let mut matched = Vec::with_capacity(methods.len());
400     for method_name in methods.iter().rev() {
401         // method chains are stored last -> first
402         if let ExprKind::MethodCall(ref path, _, ref args) = current.kind {
403             if path.ident.name.as_str() == *method_name {
404                 if args.iter().any(|e| e.span.from_expansion()) {
405                     return None;
406                 }
407                 matched.push(&**args); // build up `matched` backwards
408                 current = &args[0] // go to parent expression
409             } else {
410                 return None;
411             }
412         } else {
413             return None;
414         }
415     }
416     // Reverse `matched` so that it is in the same order as `methods`.
417     matched.reverse();
418     Some(matched)
419 }
420
421 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
422 pub fn is_entrypoint_fn(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
423     cx.tcx
424         .entry_fn(LOCAL_CRATE)
425         .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id)
426 }
427
428 /// Gets the name of the item the expression is in, if available.
429 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<Name> {
430     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
431     match cx.tcx.hir().find(parent_id) {
432         Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
433         Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
434             Some(ident.name)
435         },
436         _ => None,
437     }
438 }
439
440 /// Gets the name of a `Pat`, if any.
441 pub fn get_pat_name(pat: &Pat<'_>) -> Option<Name> {
442     match pat.kind {
443         PatKind::Binding(.., ref spname, _) => Some(spname.name),
444         PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
445         PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
446         _ => None,
447     }
448 }
449
450 struct ContainsName {
451     name: Name,
452     result: bool,
453 }
454
455 impl<'tcx> Visitor<'tcx> for ContainsName {
456     fn visit_name(&mut self, _: Span, name: Name) {
457         if self.name == name {
458             self.result = true;
459         }
460     }
461     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
462         NestedVisitorMap::None
463     }
464 }
465
466 /// Checks if an `Expr` contains a certain name.
467 pub fn contains_name(name: Name, expr: &Expr<'_>) -> bool {
468     let mut cn = ContainsName { name, result: false };
469     cn.visit_expr(expr);
470     cn.result
471 }
472
473 /// Converts a span to a code snippet if available, otherwise use default.
474 ///
475 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
476 /// to convert a given `Span` to a `str`.
477 ///
478 /// # Example
479 /// ```rust,ignore
480 /// snippet(cx, expr.span, "..")
481 /// ```
482 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
483     snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
484 }
485
486 /// Same as `snippet`, but it adapts the applicability level by following rules:
487 ///
488 /// - Applicability level `Unspecified` will never be changed.
489 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
490 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
491 /// `HasPlaceholders`
492 pub fn snippet_with_applicability<'a, T: LintContext>(
493     cx: &T,
494     span: Span,
495     default: &'a str,
496     applicability: &mut Applicability,
497 ) -> Cow<'a, str> {
498     if *applicability != Applicability::Unspecified && span.from_expansion() {
499         *applicability = Applicability::MaybeIncorrect;
500     }
501     snippet_opt(cx, span).map_or_else(
502         || {
503             if *applicability == Applicability::MachineApplicable {
504                 *applicability = Applicability::HasPlaceholders;
505             }
506             Cow::Borrowed(default)
507         },
508         From::from,
509     )
510 }
511
512 /// Same as `snippet`, but should only be used when it's clear that the input span is
513 /// not a macro argument.
514 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
515     snippet(cx, span.source_callsite(), default)
516 }
517
518 /// Converts a span to a code snippet. Returns `None` if not available.
519 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
520     cx.sess().source_map().span_to_snippet(span).ok()
521 }
522
523 /// Converts a span (from a block) to a code snippet if available, otherwise use
524 /// default.
525 /// This trims the code of indentation, except for the first line. Use it for
526 /// blocks or block-like
527 /// things which need to be printed as such.
528 ///
529 /// # Example
530 /// ```rust,ignore
531 /// snippet_block(cx, expr.span, "..")
532 /// ```
533 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
534     let snip = snippet(cx, span, default);
535     trim_multiline(snip, true)
536 }
537
538 /// Same as `snippet_block`, but adapts the applicability level by the rules of
539 /// `snippet_with_applicabiliy`.
540 pub fn snippet_block_with_applicability<'a, T: LintContext>(
541     cx: &T,
542     span: Span,
543     default: &'a str,
544     applicability: &mut Applicability,
545 ) -> Cow<'a, str> {
546     let snip = snippet_with_applicability(cx, span, default, applicability);
547     trim_multiline(snip, true)
548 }
549
550 /// Returns a new Span that covers the full last line of the given Span
551 pub fn last_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
552     let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
553     let line_no = source_map_and_line.line;
554     let line_start = &source_map_and_line.sf.lines[line_no];
555     Span::new(*line_start, span.hi(), span.ctxt())
556 }
557
558 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
559 /// Also takes an `Option<String>` which can be put inside the braces.
560 pub fn expr_block<'a, T: LintContext>(
561     cx: &T,
562     expr: &Expr<'_>,
563     option: Option<String>,
564     default: &'a str,
565 ) -> Cow<'a, str> {
566     let code = snippet_block(cx, expr.span, default);
567     let string = option.unwrap_or_default();
568     if expr.span.from_expansion() {
569         Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
570     } else if let ExprKind::Block(_, _) = expr.kind {
571         Cow::Owned(format!("{}{}", code, string))
572     } else if string.is_empty() {
573         Cow::Owned(format!("{{ {} }}", code))
574     } else {
575         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
576     }
577 }
578
579 /// Trim indentation from a multiline string with possibility of ignoring the
580 /// first line.
581 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
582     let s_space = trim_multiline_inner(s, ignore_first, ' ');
583     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
584     trim_multiline_inner(s_tab, ignore_first, ' ')
585 }
586
587 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
588     let x = s
589         .lines()
590         .skip(ignore_first as usize)
591         .filter_map(|l| {
592             if l.is_empty() {
593                 None
594             } else {
595                 // ignore empty lines
596                 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
597             }
598         })
599         .min()
600         .unwrap_or(0);
601     if x > 0 {
602         Cow::Owned(
603             s.lines()
604                 .enumerate()
605                 .map(|(i, l)| {
606                     if (ignore_first && i == 0) || l.is_empty() {
607                         l
608                     } else {
609                         l.split_at(x).1
610                     }
611                 })
612                 .collect::<Vec<_>>()
613                 .join("\n"),
614         )
615     } else {
616         s
617     }
618 }
619
620 /// Gets the parent expression, if any â€“- this is useful to constrain a lint.
621 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr<'_>) -> Option<&'c Expr<'c>> {
622     let map = &cx.tcx.hir();
623     let hir_id = e.hir_id;
624     let parent_id = map.get_parent_node(hir_id);
625     if hir_id == parent_id {
626         return None;
627     }
628     map.find(parent_id).and_then(|node| {
629         if let Node::Expr(parent) = node {
630             Some(parent)
631         } else {
632             None
633         }
634     })
635 }
636
637 pub fn get_enclosing_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
638     let map = &cx.tcx.hir();
639     let enclosing_node = map
640         .get_enclosing_scope(hir_id)
641         .and_then(|enclosing_id| map.find(enclosing_id));
642     if let Some(node) = enclosing_node {
643         match node {
644             Node::Block(block) => Some(block),
645             Node::Item(&Item {
646                 kind: ItemKind::Fn(_, _, eid),
647                 ..
648             })
649             | Node::ImplItem(&ImplItem {
650                 kind: ImplItemKind::Method(_, eid),
651                 ..
652             }) => match cx.tcx.hir().body(eid).value.kind {
653                 ExprKind::Block(ref block, _) => Some(block),
654                 _ => None,
655             },
656             _ => None,
657         }
658     } else {
659         None
660     }
661 }
662
663 /// Returns the base type for HIR references and pointers.
664 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
665     match ty.kind {
666         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
667         _ => ty,
668     }
669 }
670
671 /// Returns the base type for references and raw pointers.
672 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
673     match ty.kind {
674         ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
675         _ => ty,
676     }
677 }
678
679 /// Returns the base type for references and raw pointers, and count reference
680 /// depth.
681 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
682     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
683         match ty.kind {
684             ty::Ref(_, ty, _) => inner(ty, depth + 1),
685             _ => (ty, depth),
686         }
687     }
688     inner(ty, 0)
689 }
690
691 /// Checks whether the given expression is a constant integer of the given value.
692 /// unlike `is_integer_literal`, this version does const folding
693 pub fn is_integer_const(cx: &LateContext<'_, '_>, e: &Expr<'_>, value: u128) -> bool {
694     if is_integer_literal(e, value) {
695         return true;
696     }
697     let map = cx.tcx.hir();
698     let parent_item = map.get_parent_item(e.hir_id);
699     if let Some((Constant::Int(v), _)) = map
700         .maybe_body_owned_by(parent_item)
701         .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e))
702     {
703         value == v
704     } else {
705         false
706     }
707 }
708
709 /// Checks whether the given expression is a constant literal of the given value.
710 pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
711     // FIXME: use constant folding
712     if let ExprKind::Lit(ref spanned) = expr.kind {
713         if let LitKind::Int(v, _) = spanned.node {
714             return v == value;
715         }
716     }
717     false
718 }
719
720 /// Returns `true` if the given `Expr` has been coerced before.
721 ///
722 /// Examples of coercions can be found in the Nomicon at
723 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
724 ///
725 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
726 /// information on adjustments and coercions.
727 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool {
728     cx.tables.adjustments().get(e.hir_id).is_some()
729 }
730
731 /// Returns the pre-expansion span if is this comes from an expansion of the
732 /// macro `name`.
733 /// See also `is_direct_expn_of`.
734 #[must_use]
735 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
736     loop {
737         if span.from_expansion() {
738             let data = span.ctxt().outer_expn_data();
739             let mac_name = data.kind.descr();
740             let new_span = data.call_site;
741
742             if mac_name.as_str() == name {
743                 return Some(new_span);
744             } else {
745                 span = new_span;
746             }
747         } else {
748             return None;
749         }
750     }
751 }
752
753 /// Returns the pre-expansion span if the span directly comes from an expansion
754 /// of the macro `name`.
755 /// The difference with `is_expn_of` is that in
756 /// ```rust,ignore
757 /// foo!(bar!(42));
758 /// ```
759 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
760 /// `bar!` by
761 /// `is_direct_expn_of`.
762 #[must_use]
763 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
764     if span.from_expansion() {
765         let data = span.ctxt().outer_expn_data();
766         let mac_name = data.kind.descr();
767         let new_span = data.call_site;
768
769         if mac_name.as_str() == name {
770             Some(new_span)
771         } else {
772             None
773         }
774     } else {
775         None
776     }
777 }
778
779 /// Convenience function to get the return type of a function.
780 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
781     let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
782     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
783     cx.tcx.erase_late_bound_regions(&ret_ty)
784 }
785
786 /// Checks if two types are the same.
787 ///
788 /// This discards any lifetime annotations, too.
789 //
790 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` ==
791 // `for <'b> Foo<'b>`, but not for type parameters).
792 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
793     let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
794     let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
795     cx.tcx
796         .infer_ctxt()
797         .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
798 }
799
800 /// Returns `true` if the given type is an `unsafe` function.
801 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
802     match ty.kind {
803         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
804         _ => false,
805     }
806 }
807
808 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
809     ty.is_copy_modulo_regions(cx.tcx, cx.param_env, DUMMY_SP)
810 }
811
812 /// Checks if an expression is constructing a tuple-like enum variant or struct
813 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
814     if let ExprKind::Call(ref fun, _) = expr.kind {
815         if let ExprKind::Path(ref qp) = fun.kind {
816             let res = cx.tables.qpath_res(qp, fun.hir_id);
817             return match res {
818                 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(..), _) => true,
819                 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
820                 _ => false,
821             };
822         }
823     }
824     false
825 }
826
827 /// Returns `true` if a pattern is refutable.
828 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat<'_>) -> bool {
829     fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, id: HirId) -> bool {
830         matches!(
831             cx.tables.qpath_res(qpath, id),
832             def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
833         )
834     }
835
836     fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
837         i.any(|pat| is_refutable(cx, pat))
838     }
839
840     match pat.kind {
841         PatKind::Binding(..) | PatKind::Wild => false,
842         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
843         PatKind::Lit(..) | PatKind::Range(..) => true,
844         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
845         PatKind::Or(ref pats) | PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
846         PatKind::Struct(ref qpath, ref fields, _) => {
847             if is_enum_variant(cx, qpath, pat.hir_id) {
848                 true
849             } else {
850                 are_refutable(cx, fields.iter().map(|field| &*field.pat))
851             }
852         },
853         PatKind::TupleStruct(ref qpath, ref pats, _) => {
854             if is_enum_variant(cx, qpath, pat.hir_id) {
855                 true
856             } else {
857                 are_refutable(cx, pats.iter().map(|pat| &**pat))
858             }
859         },
860         PatKind::Slice(ref head, ref middle, ref tail) => {
861             are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
862         },
863     }
864 }
865
866 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
867 /// implementations have.
868 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
869     attr::contains_name(attrs, sym!(automatically_derived))
870 }
871
872 /// Remove blocks around an expression.
873 ///
874 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
875 /// themselves.
876 pub fn remove_blocks<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
877     while let ExprKind::Block(ref block, ..) = expr.kind {
878         match (block.stmts.is_empty(), block.expr.as_ref()) {
879             (true, Some(e)) => expr = e,
880             _ => break,
881         }
882     }
883     expr
884 }
885
886 pub fn is_self(slf: &Param<'_>) -> bool {
887     if let PatKind::Binding(.., name, _) = slf.pat.kind {
888         name.name == kw::SelfLower
889     } else {
890         false
891     }
892 }
893
894 pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
895     if_chain! {
896         if let TyKind::Path(ref qp) = slf.kind;
897         if let QPath::Resolved(None, ref path) = *qp;
898         if let Res::SelfTy(..) = path.res;
899         then {
900             return true
901         }
902     }
903     false
904 }
905
906 pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
907     (0..decl.inputs.len()).map(move |i| &body.params[i])
908 }
909
910 /// Checks if a given expression is a match expression expanded from the `?`
911 /// operator or the `try` macro.
912 pub fn is_try<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
913     fn is_ok(arm: &Arm<'_>) -> bool {
914         if_chain! {
915             if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
916             if match_qpath(path, &paths::RESULT_OK[1..]);
917             if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
918             if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
919             if let Res::Local(lid) = path.res;
920             if lid == hir_id;
921             then {
922                 return true;
923             }
924         }
925         false
926     }
927
928     fn is_err(arm: &Arm<'_>) -> bool {
929         if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
930             match_qpath(path, &paths::RESULT_ERR[1..])
931         } else {
932             false
933         }
934     }
935
936     if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
937         // desugared from a `?` operator
938         if let MatchSource::TryDesugar = *source {
939             return Some(expr);
940         }
941
942         if_chain! {
943             if arms.len() == 2;
944             if arms[0].guard.is_none();
945             if arms[1].guard.is_none();
946             if (is_ok(&arms[0]) && is_err(&arms[1])) ||
947                 (is_ok(&arms[1]) && is_err(&arms[0]));
948             then {
949                 return Some(expr);
950             }
951         }
952     }
953
954     None
955 }
956
957 /// Returns `true` if the lint is allowed in the current context
958 ///
959 /// Useful for skipping long running code when it's unnecessary
960 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: HirId) -> bool {
961     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
962 }
963
964 pub fn get_arg_name(pat: &Pat<'_>) -> Option<ast::Name> {
965     match pat.kind {
966         PatKind::Binding(.., ident, None) => Some(ident.name),
967         PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
968         _ => None,
969     }
970 }
971
972 pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 {
973     layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
974         .size()
975         .bits()
976 }
977
978 #[allow(clippy::cast_possible_wrap)]
979 /// Turn a constant int byte representation into an i128
980 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ast::IntTy) -> i128 {
981     let amt = 128 - int_bits(tcx, ity);
982     ((u as i128) << amt) >> amt
983 }
984
985 #[allow(clippy::cast_sign_loss)]
986 /// clip unused bytes
987 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 {
988     let amt = 128 - int_bits(tcx, ity);
989     ((u as u128) << amt) >> amt
990 }
991
992 /// clip unused bytes
993 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 {
994     let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
995         .size()
996         .bits();
997     let amt = 128 - bits;
998     (u << amt) >> amt
999 }
1000
1001 /// Removes block comments from the given `Vec` of lines.
1002 ///
1003 /// # Examples
1004 ///
1005 /// ```rust,ignore
1006 /// without_block_comments(vec!["/*", "foo", "*/"]);
1007 /// // => vec![]
1008 ///
1009 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1010 /// // => vec!["bar"]
1011 /// ```
1012 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1013     let mut without = vec![];
1014
1015     let mut nest_level = 0;
1016
1017     for line in lines {
1018         if line.contains("/*") {
1019             nest_level += 1;
1020             continue;
1021         } else if line.contains("*/") {
1022             nest_level -= 1;
1023             continue;
1024         }
1025
1026         if nest_level == 0 {
1027             without.push(line);
1028         }
1029     }
1030
1031     without
1032 }
1033
1034 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1035     let map = &tcx.hir();
1036     let mut prev_enclosing_node = None;
1037     let mut enclosing_node = node;
1038     while Some(enclosing_node) != prev_enclosing_node {
1039         if is_automatically_derived(map.attrs(enclosing_node)) {
1040             return true;
1041         }
1042         prev_enclosing_node = Some(enclosing_node);
1043         enclosing_node = map.get_parent_item(enclosing_node);
1044     }
1045     false
1046 }
1047
1048 /// Returns true if ty has `iter` or `iter_mut` methods
1049 pub fn has_iter_method(cx: &LateContext<'_, '_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
1050     // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1051     // exists and has the desired signature. Unfortunately FnCtxt is not exported
1052     // so we can't use its `lookup_method` method.
1053     let into_iter_collections: [&[&str]; 13] = [
1054         &paths::VEC,
1055         &paths::OPTION,
1056         &paths::RESULT,
1057         &paths::BTREESET,
1058         &paths::BTREEMAP,
1059         &paths::VEC_DEQUE,
1060         &paths::LINKED_LIST,
1061         &paths::BINARY_HEAP,
1062         &paths::HASHSET,
1063         &paths::HASHMAP,
1064         &paths::PATH_BUF,
1065         &paths::PATH,
1066         &paths::RECEIVER,
1067     ];
1068
1069     let ty_to_check = match probably_ref_ty.kind {
1070         ty::Ref(_, ty_to_check, _) => ty_to_check,
1071         _ => probably_ref_ty,
1072     };
1073
1074     let def_id = match ty_to_check.kind {
1075         ty::Array(..) => return Some("array"),
1076         ty::Slice(..) => return Some("slice"),
1077         ty::Adt(adt, _) => adt.did,
1078         _ => return None,
1079     };
1080
1081     for path in &into_iter_collections {
1082         if match_def_path(cx, def_id, path) {
1083             return Some(*path.last().unwrap());
1084         }
1085     }
1086     None
1087 }
1088
1089 /// Matches a function call with the given path and returns the arguments.
1090 ///
1091 /// Usage:
1092 ///
1093 /// ```rust,ignore
1094 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
1095 /// ```
1096 pub fn match_function_call<'a, 'tcx>(
1097     cx: &LateContext<'a, 'tcx>,
1098     expr: &'tcx Expr<'_>,
1099     path: &[&str],
1100 ) -> Option<&'tcx [Expr<'tcx>]> {
1101     if_chain! {
1102         if let ExprKind::Call(ref fun, ref args) = expr.kind;
1103         if let ExprKind::Path(ref qpath) = fun.kind;
1104         if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
1105         if match_def_path(cx, fun_def_id, path);
1106         then {
1107             return Some(&args)
1108         }
1109     };
1110     None
1111 }
1112
1113 /// Checks if `Ty` is normalizable. This function is useful
1114 /// to avoid crashes on `layout_of`.
1115 pub fn is_normalizable<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
1116     cx.tcx.infer_ctxt().enter(|infcx| {
1117         let cause = rustc::traits::ObligationCause::dummy();
1118         infcx.at(&cause, param_env).normalize(&ty).is_ok()
1119     })
1120 }
1121
1122 #[cfg(test)]
1123 mod test {
1124     use super::{trim_multiline, without_block_comments};
1125
1126     #[test]
1127     fn test_trim_multiline_single_line() {
1128         assert_eq!("", trim_multiline("".into(), false));
1129         assert_eq!("...", trim_multiline("...".into(), false));
1130         assert_eq!("...", trim_multiline("    ...".into(), false));
1131         assert_eq!("...", trim_multiline("\t...".into(), false));
1132         assert_eq!("...", trim_multiline("\t\t...".into(), false));
1133     }
1134
1135     #[test]
1136     #[rustfmt::skip]
1137     fn test_trim_multiline_block() {
1138         assert_eq!("\
1139     if x {
1140         y
1141     } else {
1142         z
1143     }", trim_multiline("    if x {
1144             y
1145         } else {
1146             z
1147         }".into(), false));
1148         assert_eq!("\
1149     if x {
1150     \ty
1151     } else {
1152     \tz
1153     }", trim_multiline("    if x {
1154         \ty
1155         } else {
1156         \tz
1157         }".into(), false));
1158     }
1159
1160     #[test]
1161     #[rustfmt::skip]
1162     fn test_trim_multiline_empty_line() {
1163         assert_eq!("\
1164     if x {
1165         y
1166
1167     } else {
1168         z
1169     }", trim_multiline("    if x {
1170             y
1171
1172         } else {
1173             z
1174         }".into(), false));
1175     }
1176
1177     #[test]
1178     fn test_without_block_comments_lines_without_block_comments() {
1179         let result = without_block_comments(vec!["/*", "", "*/"]);
1180         println!("result: {:?}", result);
1181         assert!(result.is_empty());
1182
1183         let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1184         assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1185
1186         let result = without_block_comments(vec!["/* rust", "", "*/"]);
1187         assert!(result.is_empty());
1188
1189         let result = without_block_comments(vec!["/* one-line comment */"]);
1190         assert!(result.is_empty());
1191
1192         let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1193         assert!(result.is_empty());
1194
1195         let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1196         assert!(result.is_empty());
1197
1198         let result = without_block_comments(vec!["foo", "bar", "baz"]);
1199         assert_eq!(result, vec!["foo", "bar", "baz"]);
1200     }
1201 }
1202
1203 pub fn match_def_path<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, did: DefId, syms: &[&str]) -> bool {
1204     let path = cx.get_def_path(did);
1205     path.len() == syms.len() && path.into_iter().zip(syms.iter()).all(|(a, &b)| a.as_str() == b)
1206 }
1207
1208 /// Returns the list of condition expressions and the list of blocks in a
1209 /// sequence of `if/else`.
1210 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1211 /// `if a { c } else if b { d } else { e }`.
1212 pub fn if_sequence<'tcx>(
1213     mut expr: &'tcx Expr<'tcx>,
1214 ) -> (SmallVec<[&'tcx Expr<'tcx>; 1]>, SmallVec<[&'tcx Block<'tcx>; 1]>) {
1215     let mut conds = SmallVec::new();
1216     let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new();
1217
1218     while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
1219         conds.push(&**cond);
1220         if let ExprKind::Block(ref block, _) = then_expr.kind {
1221             blocks.push(block);
1222         } else {
1223             panic!("ExprKind::If node is not an ExprKind::Block");
1224         }
1225
1226         if let Some(ref else_expr) = *else_expr {
1227             expr = else_expr;
1228         } else {
1229             break;
1230         }
1231     }
1232
1233     // final `else {..}`
1234     if !blocks.is_empty() {
1235         if let ExprKind::Block(ref block, _) = expr.kind {
1236             blocks.push(&**block);
1237         }
1238     }
1239
1240     (conds, blocks)
1241 }
1242
1243 pub fn parent_node_is_if_expr<'a, 'b>(expr: &Expr<'_>, cx: &LateContext<'a, 'b>) -> bool {
1244     let map = cx.tcx.hir();
1245     let parent_id = map.get_parent_node(expr.hir_id);
1246     let parent_node = map.get(parent_id);
1247
1248     match parent_node {
1249         Node::Expr(e) => higher::if_block(&e).is_some(),
1250         Node::Arm(e) => higher::if_block(&e.body).is_some(),
1251         _ => false,
1252     }
1253 }
1254
1255 // Finds the attribute with the given name, if any
1256 pub fn attr_by_name<'a>(attrs: &'a [Attribute], name: &'_ str) -> Option<&'a Attribute> {
1257     attrs
1258         .iter()
1259         .find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name))
1260 }
1261
1262 // Finds the `#[must_use]` attribute, if any
1263 pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
1264     attr_by_name(attrs, "must_use")
1265 }
1266
1267 // Returns whether the type has #[must_use] attribute
1268 pub fn is_must_use_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
1269     use ty::TyKind::*;
1270     match ty.kind {
1271         Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
1272         Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
1273         Slice(ref ty) | Array(ref ty, _) | RawPtr(ty::TypeAndMut { ref ty, .. }) | Ref(_, ref ty, _) => {
1274             // for the Array case we don't need to care for the len == 0 case
1275             // because we don't want to lint functions returning empty arrays
1276             is_must_use_ty(cx, *ty)
1277         },
1278         Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
1279         Opaque(ref def_id, _) => {
1280             for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates {
1281                 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
1282                     if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() {
1283                         return true;
1284                     }
1285                 }
1286             }
1287             false
1288         },
1289         Dynamic(binder, _) => {
1290             for predicate in binder.skip_binder().iter() {
1291                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
1292                     if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
1293                         return true;
1294                     }
1295                 }
1296             }
1297             false
1298         },
1299         _ => false,
1300     }
1301 }
1302
1303 // check if expr is calling method or function with #[must_use] attribyte
1304 pub fn is_must_use_func_call(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
1305     let did = match expr.kind {
1306         ExprKind::Call(ref path, _) => if_chain! {
1307             if let ExprKind::Path(ref qpath) = path.kind;
1308             if let def::Res::Def(_, did) = cx.tables.qpath_res(qpath, path.hir_id);
1309             then {
1310                 Some(did)
1311             } else {
1312                 None
1313             }
1314         },
1315         ExprKind::MethodCall(_, _, _) => cx.tables.type_dependent_def_id(expr.hir_id),
1316         _ => None,
1317     };
1318
1319     if let Some(did) = did {
1320         must_use_attr(&cx.tcx.get_attrs(did)).is_some()
1321     } else {
1322         false
1323     }
1324 }