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