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