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