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