]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types/mod.rs
785f2c511d0f1ac8975b910ea436bc20c4a0bf69
[rust.git] / clippy_lints / src / types / mod.rs
1 #![allow(rustc::default_hash_types)]
2
3 mod borrowed_box;
4 mod box_vec;
5 mod linked_list;
6 mod option_option;
7 mod rc_buffer;
8 mod redundant_allocation;
9 mod utils;
10 mod vec_box;
11
12 use std::borrow::Cow;
13 use std::collections::BTreeMap;
14
15 use clippy_utils::diagnostics::{multispan_sugg, span_lint, span_lint_and_then};
16 use clippy_utils::source::{snippet, snippet_opt};
17 use clippy_utils::ty::is_type_diagnostic_item;
18 use if_chain::if_chain;
19 use rustc_errors::DiagnosticBuilder;
20 use rustc_hir as hir;
21 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
22 use rustc_hir::{
23     Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem, ImplItemKind, Item,
24     ItemKind, Local, MutTy, QPath, TraitFn, TraitItem, TraitItemKind, TyKind,
25 };
26 use rustc_lint::{LateContext, LateLintPass, LintContext};
27 use rustc_middle::hir::map::Map;
28 use rustc_middle::lint::in_external_macro;
29 use rustc_middle::ty::{Ty, TyS, TypeckResults};
30 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
31 use rustc_span::source_map::Span;
32 use rustc_span::symbol::sym;
33 use rustc_target::spec::abi::Abi;
34 use rustc_typeck::hir_ty_to_ty;
35
36 use clippy_utils::paths;
37 use clippy_utils::{differing_macro_contexts, match_path};
38
39 declare_clippy_lint! {
40     /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
41     /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
42     ///
43     /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
44     /// the heap. So if you `Box` it, you just add another level of indirection
45     /// without any benefit whatsoever.
46     ///
47     /// **Known problems:** None.
48     ///
49     /// **Example:**
50     /// ```rust,ignore
51     /// struct X {
52     ///     values: Box<Vec<Foo>>,
53     /// }
54     /// ```
55     ///
56     /// Better:
57     ///
58     /// ```rust,ignore
59     /// struct X {
60     ///     values: Vec<Foo>,
61     /// }
62     /// ```
63     pub BOX_VEC,
64     perf,
65     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
66 }
67
68 declare_clippy_lint! {
69     /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
70     /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
71     ///
72     /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
73     /// the heap. So if you `Box` its contents, you just add another level of indirection.
74     ///
75     /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see [#3530](https://github.com/rust-lang/rust-clippy/issues/3530),
76     /// 1st comment).
77     ///
78     /// **Example:**
79     /// ```rust
80     /// struct X {
81     ///     values: Vec<Box<i32>>,
82     /// }
83     /// ```
84     ///
85     /// Better:
86     ///
87     /// ```rust
88     /// struct X {
89     ///     values: Vec<i32>,
90     /// }
91     /// ```
92     pub VEC_BOX,
93     complexity,
94     "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
95 }
96
97 declare_clippy_lint! {
98     /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
99     /// definitions
100     ///
101     /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
102     /// represents an optional optional value which is logically the same thing as an optional
103     /// value but has an unneeded extra level of wrapping.
104     ///
105     /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
106     /// consider a custom `enum` instead, with clear names for each case.
107     ///
108     /// **Known problems:** None.
109     ///
110     /// **Example**
111     /// ```rust
112     /// fn get_data() -> Option<Option<u32>> {
113     ///     None
114     /// }
115     /// ```
116     ///
117     /// Better:
118     ///
119     /// ```rust
120     /// pub enum Contents {
121     ///     Data(Vec<u8>), // Was Some(Some(Vec<u8>))
122     ///     NotYetFetched, // Was Some(None)
123     ///     None,          // Was None
124     /// }
125     ///
126     /// fn get_data() -> Contents {
127     ///     Contents::None
128     /// }
129     /// ```
130     pub OPTION_OPTION,
131     pedantic,
132     "usage of `Option<Option<T>>`"
133 }
134
135 declare_clippy_lint! {
136     /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
137     /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
138     ///
139     /// **Why is this bad?** Gankro says:
140     ///
141     /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
142     /// pointers and indirection.
143     /// > It wastes memory, it has terrible cache locality, and is all-around slow.
144     /// `RingBuf`, while
145     /// > "only" amortized for push/pop, should be faster in the general case for
146     /// almost every possible
147     /// > workload, and isn't even amortized at all if you can predict the capacity
148     /// you need.
149     /// >
150     /// > `LinkedList`s are only really good if you're doing a lot of merging or
151     /// splitting of lists.
152     /// > This is because they can just mangle some pointers instead of actually
153     /// copying the data. Even
154     /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
155     /// can still be better
156     /// > because of how expensive it is to seek to the middle of a `LinkedList`.
157     ///
158     /// **Known problems:** False positives – the instances where using a
159     /// `LinkedList` makes sense are few and far between, but they can still happen.
160     ///
161     /// **Example:**
162     /// ```rust
163     /// # use std::collections::LinkedList;
164     /// let x: LinkedList<usize> = LinkedList::new();
165     /// ```
166     pub LINKEDLIST,
167     pedantic,
168     "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
169 }
170
171 declare_clippy_lint! {
172     /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
173     /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
174     ///
175     /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
176     /// general.
177     ///
178     /// **Known problems:** None.
179     ///
180     /// **Example:**
181     /// ```rust,ignore
182     /// fn foo(bar: &Box<T>) { ... }
183     /// ```
184     ///
185     /// Better:
186     ///
187     /// ```rust,ignore
188     /// fn foo(bar: &T) { ... }
189     /// ```
190     pub BORROWED_BOX,
191     complexity,
192     "a borrow of a boxed type"
193 }
194
195 declare_clippy_lint! {
196     /// **What it does:** Checks for use of redundant allocations anywhere in the code.
197     ///
198     /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
199     /// add an unnecessary level of indirection.
200     ///
201     /// **Known problems:** None.
202     ///
203     /// **Example:**
204     /// ```rust
205     /// # use std::rc::Rc;
206     /// fn foo(bar: Rc<&usize>) {}
207     /// ```
208     ///
209     /// Better:
210     ///
211     /// ```rust
212     /// fn foo(bar: &usize) {}
213     /// ```
214     pub REDUNDANT_ALLOCATION,
215     perf,
216     "redundant allocation"
217 }
218
219 declare_clippy_lint! {
220     /// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
221     ///
222     /// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
223     /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
224     ///
225     /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
226     /// works if there are no additional references yet, which usually defeats the purpose of
227     /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
228     /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
229     /// be used.
230     ///
231     /// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
232     /// cases where mutation only happens before there are any additional references.
233     ///
234     /// **Example:**
235     /// ```rust,ignore
236     /// # use std::rc::Rc;
237     /// fn foo(interned: Rc<String>) { ... }
238     /// ```
239     ///
240     /// Better:
241     ///
242     /// ```rust,ignore
243     /// fn foo(interned: Rc<str>) { ... }
244     /// ```
245     pub RC_BUFFER,
246     restriction,
247     "shared ownership of a buffer type"
248 }
249
250 pub struct Types {
251     vec_box_size_threshold: u64,
252 }
253
254 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
255
256 impl<'tcx> LateLintPass<'tcx> for Types {
257     fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
258         // Skip trait implementations; see issue #605.
259         if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
260             if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
261                 return;
262             }
263         }
264
265         self.check_fn_decl(cx, decl);
266     }
267
268     fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) {
269         self.check_ty(cx, &field.ty, false);
270     }
271
272     fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
273         match item.kind {
274             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
275             TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
276             TraitItemKind::Type(..) => (),
277         }
278     }
279
280     fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
281         if let Some(ref ty) = local.ty {
282             self.check_ty(cx, ty, true);
283         }
284     }
285 }
286
287 impl Types {
288     pub fn new(vec_box_size_threshold: u64) -> Self {
289         Self { vec_box_size_threshold }
290     }
291
292     fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
293         for input in decl.inputs {
294             self.check_ty(cx, input, false);
295         }
296
297         if let FnRetTy::Return(ref ty) = decl.output {
298             self.check_ty(cx, ty, false);
299         }
300     }
301
302     /// Recursively check for `TypePass` lints in the given type. Stop at the first
303     /// lint found.
304     ///
305     /// The parameter `is_local` distinguishes the context of the type.
306     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
307         if hir_ty.span.from_expansion() {
308             return;
309         }
310         match hir_ty.kind {
311             TyKind::Path(ref qpath) if !is_local => {
312                 let hir_id = hir_ty.hir_id;
313                 let res = cx.qpath_res(qpath, hir_id);
314                 if let Some(def_id) = res.opt_def_id() {
315                     let mut triggered = false;
316                     triggered |= box_vec::check(cx, hir_ty, qpath, def_id);
317                     triggered |= redundant_allocation::check(cx, hir_ty, qpath, def_id);
318                     triggered |= rc_buffer::check(cx, hir_ty, qpath, def_id);
319                     triggered |= vec_box::check(cx, hir_ty, qpath, def_id, self.vec_box_size_threshold);
320                     triggered |= option_option::check(cx, hir_ty, qpath, def_id);
321                     triggered |= linked_list::check(cx, hir_ty, def_id);
322
323                     if triggered {
324                         return;
325                     }
326                 }
327                 match *qpath {
328                     QPath::Resolved(Some(ref ty), ref p) => {
329                         self.check_ty(cx, ty, is_local);
330                         for ty in p.segments.iter().flat_map(|seg| {
331                             seg.args
332                                 .as_ref()
333                                 .map_or_else(|| [].iter(), |params| params.args.iter())
334                                 .filter_map(|arg| match arg {
335                                     GenericArg::Type(ty) => Some(ty),
336                                     _ => None,
337                                 })
338                         }) {
339                             self.check_ty(cx, ty, is_local);
340                         }
341                     },
342                     QPath::Resolved(None, ref p) => {
343                         for ty in p.segments.iter().flat_map(|seg| {
344                             seg.args
345                                 .as_ref()
346                                 .map_or_else(|| [].iter(), |params| params.args.iter())
347                                 .filter_map(|arg| match arg {
348                                     GenericArg::Type(ty) => Some(ty),
349                                     _ => None,
350                                 })
351                         }) {
352                             self.check_ty(cx, ty, is_local);
353                         }
354                     },
355                     QPath::TypeRelative(ref ty, ref seg) => {
356                         self.check_ty(cx, ty, is_local);
357                         if let Some(ref params) = seg.args {
358                             for ty in params.args.iter().filter_map(|arg| match arg {
359                                 GenericArg::Type(ty) => Some(ty),
360                                 _ => None,
361                             }) {
362                                 self.check_ty(cx, ty, is_local);
363                             }
364                         }
365                     },
366                     QPath::LangItem(..) => {},
367                 }
368             },
369             TyKind::Rptr(ref lt, ref mut_ty) => {
370                 if !borrowed_box::check(cx, hir_ty, lt, mut_ty) {
371                     self.check_ty(cx, &mut_ty.ty, is_local);
372                 }
373             },
374             TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
375                 self.check_ty(cx, ty, is_local)
376             },
377             TyKind::Tup(tys) => {
378                 for ty in tys {
379                     self.check_ty(cx, ty, is_local);
380                 }
381             },
382             _ => {},
383         }
384     }
385 }
386
387 declare_clippy_lint! {
388     /// **What it does:** Checks for types used in structs, parameters and `let`
389     /// declarations above a certain complexity threshold.
390     ///
391     /// **Why is this bad?** Too complex types make the code less readable. Consider
392     /// using a `type` definition to simplify them.
393     ///
394     /// **Known problems:** None.
395     ///
396     /// **Example:**
397     /// ```rust
398     /// # use std::rc::Rc;
399     /// struct Foo {
400     ///     inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
401     /// }
402     /// ```
403     pub TYPE_COMPLEXITY,
404     complexity,
405     "usage of very complex types that might be better factored into `type` definitions"
406 }
407
408 pub struct TypeComplexity {
409     threshold: u64,
410 }
411
412 impl TypeComplexity {
413     #[must_use]
414     pub fn new(threshold: u64) -> Self {
415         Self { threshold }
416     }
417 }
418
419 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
420
421 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
422     fn check_fn(
423         &mut self,
424         cx: &LateContext<'tcx>,
425         _: FnKind<'tcx>,
426         decl: &'tcx FnDecl<'_>,
427         _: &'tcx Body<'_>,
428         _: Span,
429         _: HirId,
430     ) {
431         self.check_fndecl(cx, decl);
432     }
433
434     fn check_field_def(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::FieldDef<'_>) {
435         // enum variants are also struct fields now
436         self.check_type(cx, &field.ty);
437     }
438
439     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
440         match item.kind {
441             ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
442             // functions, enums, structs, impls and traits are covered
443             _ => (),
444         }
445     }
446
447     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
448         match item.kind {
449             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
450             TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
451             // methods with default impl are covered by check_fn
452             TraitItemKind::Type(..) | TraitItemKind::Fn(_, TraitFn::Provided(_)) => (),
453         }
454     }
455
456     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
457         match item.kind {
458             ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
459             // methods are covered by check_fn
460             ImplItemKind::Fn(..) => (),
461         }
462     }
463
464     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
465         if let Some(ref ty) = local.ty {
466             self.check_type(cx, ty);
467         }
468     }
469 }
470
471 impl<'tcx> TypeComplexity {
472     fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
473         for arg in decl.inputs {
474             self.check_type(cx, arg);
475         }
476         if let FnRetTy::Return(ref ty) = decl.output {
477             self.check_type(cx, ty);
478         }
479     }
480
481     fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
482         if ty.span.from_expansion() {
483             return;
484         }
485         let score = {
486             let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
487             visitor.visit_ty(ty);
488             visitor.score
489         };
490
491         if score > self.threshold {
492             span_lint(
493                 cx,
494                 TYPE_COMPLEXITY,
495                 ty.span,
496                 "very complex type used. Consider factoring parts into `type` definitions",
497             );
498         }
499     }
500 }
501
502 /// Walks a type and assigns a complexity score to it.
503 struct TypeComplexityVisitor {
504     /// total complexity score of the type
505     score: u64,
506     /// current nesting level
507     nest: u64,
508 }
509
510 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
511     type Map = Map<'tcx>;
512
513     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
514         let (add_score, sub_nest) = match ty.kind {
515             // _, &x and *x have only small overhead; don't mess with nesting level
516             TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
517
518             // the "normal" components of a type: named types, arrays/tuples
519             TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
520
521             // function types bring a lot of overhead
522             TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
523
524             TyKind::TraitObject(ref param_bounds, _, _) => {
525                 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
526                     bound
527                         .bound_generic_params
528                         .iter()
529                         .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
530                 });
531                 if has_lifetime_parameters {
532                     // complex trait bounds like A<'a, 'b>
533                     (50 * self.nest, 1)
534                 } else {
535                     // simple trait bounds like A + B
536                     (20 * self.nest, 0)
537                 }
538             },
539
540             _ => (0, 0),
541         };
542         self.score += add_score;
543         self.nest += sub_nest;
544         walk_ty(self, ty);
545         self.nest -= sub_nest;
546     }
547     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
548         NestedVisitorMap::None
549     }
550 }
551
552 declare_clippy_lint! {
553     /// **What it does:** Checks for public `impl` or `fn` missing generalization
554     /// over different hashers and implicitly defaulting to the default hashing
555     /// algorithm (`SipHash`).
556     ///
557     /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
558     /// used with them.
559     ///
560     /// **Known problems:** Suggestions for replacing constructors can contain
561     /// false-positives. Also applying suggestions can require modification of other
562     /// pieces of code, possibly including external crates.
563     ///
564     /// **Example:**
565     /// ```rust
566     /// # use std::collections::HashMap;
567     /// # use std::hash::{Hash, BuildHasher};
568     /// # trait Serialize {};
569     /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
570     ///
571     /// pub fn foo(map: &mut HashMap<i32, i32>) { }
572     /// ```
573     /// could be rewritten as
574     /// ```rust
575     /// # use std::collections::HashMap;
576     /// # use std::hash::{Hash, BuildHasher};
577     /// # trait Serialize {};
578     /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
579     ///
580     /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
581     /// ```
582     pub IMPLICIT_HASHER,
583     pedantic,
584     "missing generalization over different hashers"
585 }
586
587 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
588
589 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
590     #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
591     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
592         use rustc_span::BytePos;
593
594         fn suggestion<'tcx>(
595             cx: &LateContext<'tcx>,
596             diag: &mut DiagnosticBuilder<'_>,
597             generics_span: Span,
598             generics_suggestion_span: Span,
599             target: &ImplicitHasherType<'_>,
600             vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
601         ) {
602             let generics_snip = snippet(cx, generics_span, "");
603             // trim `<` `>`
604             let generics_snip = if generics_snip.is_empty() {
605                 ""
606             } else {
607                 &generics_snip[1..generics_snip.len() - 1]
608             };
609
610             multispan_sugg(
611                 diag,
612                 "consider adding a type parameter",
613                 vec![
614                     (
615                         generics_suggestion_span,
616                         format!(
617                             "<{}{}S: ::std::hash::BuildHasher{}>",
618                             generics_snip,
619                             if generics_snip.is_empty() { "" } else { ", " },
620                             if vis.suggestions.is_empty() {
621                                 ""
622                             } else {
623                                 // request users to add `Default` bound so that generic constructors can be used
624                                 " + Default"
625                             },
626                         ),
627                     ),
628                     (
629                         target.span(),
630                         format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
631                     ),
632                 ],
633             );
634
635             if !vis.suggestions.is_empty() {
636                 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
637             }
638         }
639
640         if !cx.access_levels.is_exported(item.hir_id()) {
641             return;
642         }
643
644         match item.kind {
645             ItemKind::Impl(ref impl_) => {
646                 let mut vis = ImplicitHasherTypeVisitor::new(cx);
647                 vis.visit_ty(impl_.self_ty);
648
649                 for target in &vis.found {
650                     if differing_macro_contexts(item.span, target.span()) {
651                         return;
652                     }
653
654                     let generics_suggestion_span = impl_.generics.span.substitute_dummy({
655                         let pos = snippet_opt(cx, item.span.until(target.span()))
656                             .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
657                         if let Some(pos) = pos {
658                             Span::new(pos, pos, item.span.data().ctxt)
659                         } else {
660                             return;
661                         }
662                     });
663
664                     let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
665                     for item in impl_.items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
666                         ctr_vis.visit_impl_item(item);
667                     }
668
669                     span_lint_and_then(
670                         cx,
671                         IMPLICIT_HASHER,
672                         target.span(),
673                         &format!(
674                             "impl for `{}` should be generalized over different hashers",
675                             target.type_name()
676                         ),
677                         move |diag| {
678                             suggestion(cx, diag, impl_.generics.span, generics_suggestion_span, target, ctr_vis);
679                         },
680                     );
681                 }
682             },
683             ItemKind::Fn(ref sig, ref generics, body_id) => {
684                 let body = cx.tcx.hir().body(body_id);
685
686                 for ty in sig.decl.inputs {
687                     let mut vis = ImplicitHasherTypeVisitor::new(cx);
688                     vis.visit_ty(ty);
689
690                     for target in &vis.found {
691                         if in_external_macro(cx.sess(), generics.span) {
692                             continue;
693                         }
694                         let generics_suggestion_span = generics.span.substitute_dummy({
695                             let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
696                                 .and_then(|snip| {
697                                     let i = snip.find("fn")?;
698                                     Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
699                                 })
700                                 .expect("failed to create span for type parameters");
701                             Span::new(pos, pos, item.span.data().ctxt)
702                         });
703
704                         let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
705                         ctr_vis.visit_body(body);
706
707                         span_lint_and_then(
708                             cx,
709                             IMPLICIT_HASHER,
710                             target.span(),
711                             &format!(
712                                 "parameter of type `{}` should be generalized over different hashers",
713                                 target.type_name()
714                             ),
715                             move |diag| {
716                                 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
717                             },
718                         );
719                     }
720                 }
721             },
722             _ => {},
723         }
724     }
725 }
726
727 enum ImplicitHasherType<'tcx> {
728     HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
729     HashSet(Span, Ty<'tcx>, Cow<'static, str>),
730 }
731
732 impl<'tcx> ImplicitHasherType<'tcx> {
733     /// Checks that `ty` is a target type without a `BuildHasher`.
734     fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
735         if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
736             let params: Vec<_> = path
737                 .segments
738                 .last()
739                 .as_ref()?
740                 .args
741                 .as_ref()?
742                 .args
743                 .iter()
744                 .filter_map(|arg| match arg {
745                     GenericArg::Type(ty) => Some(ty),
746                     _ => None,
747                 })
748                 .collect();
749             let params_len = params.len();
750
751             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
752
753             if is_type_diagnostic_item(cx, ty, sym::hashmap_type) && params_len == 2 {
754                 Some(ImplicitHasherType::HashMap(
755                     hir_ty.span,
756                     ty,
757                     snippet(cx, params[0].span, "K"),
758                     snippet(cx, params[1].span, "V"),
759                 ))
760             } else if is_type_diagnostic_item(cx, ty, sym::hashset_type) && params_len == 1 {
761                 Some(ImplicitHasherType::HashSet(
762                     hir_ty.span,
763                     ty,
764                     snippet(cx, params[0].span, "T"),
765                 ))
766             } else {
767                 None
768             }
769         } else {
770             None
771         }
772     }
773
774     fn type_name(&self) -> &'static str {
775         match *self {
776             ImplicitHasherType::HashMap(..) => "HashMap",
777             ImplicitHasherType::HashSet(..) => "HashSet",
778         }
779     }
780
781     fn type_arguments(&self) -> String {
782         match *self {
783             ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
784             ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
785         }
786     }
787
788     fn ty(&self) -> Ty<'tcx> {
789         match *self {
790             ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
791         }
792     }
793
794     fn span(&self) -> Span {
795         match *self {
796             ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
797         }
798     }
799 }
800
801 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
802     cx: &'a LateContext<'tcx>,
803     found: Vec<ImplicitHasherType<'tcx>>,
804 }
805
806 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
807     fn new(cx: &'a LateContext<'tcx>) -> Self {
808         Self { cx, found: vec![] }
809     }
810 }
811
812 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
813     type Map = Map<'tcx>;
814
815     fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
816         if let Some(target) = ImplicitHasherType::new(self.cx, t) {
817             self.found.push(target);
818         }
819
820         walk_ty(self, t);
821     }
822
823     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
824         NestedVisitorMap::None
825     }
826 }
827
828 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
829 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
830     cx: &'a LateContext<'tcx>,
831     maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
832     target: &'b ImplicitHasherType<'tcx>,
833     suggestions: BTreeMap<Span, String>,
834 }
835
836 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
837     fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
838         Self {
839             cx,
840             maybe_typeck_results: cx.maybe_typeck_results(),
841             target,
842             suggestions: BTreeMap::new(),
843         }
844     }
845 }
846
847 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
848     type Map = Map<'tcx>;
849
850     fn visit_body(&mut self, body: &'tcx Body<'_>) {
851         let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
852         walk_body(self, body);
853         self.maybe_typeck_results = old_maybe_typeck_results;
854     }
855
856     fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
857         if_chain! {
858             if let ExprKind::Call(ref fun, ref args) = e.kind;
859             if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
860             if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
861             then {
862                 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
863                     return;
864                 }
865
866                 if match_path(ty_path, &paths::HASHMAP) {
867                     if method.ident.name == sym::new {
868                         self.suggestions
869                             .insert(e.span, "HashMap::default()".to_string());
870                     } else if method.ident.name == sym!(with_capacity) {
871                         self.suggestions.insert(
872                             e.span,
873                             format!(
874                                 "HashMap::with_capacity_and_hasher({}, Default::default())",
875                                 snippet(self.cx, args[0].span, "capacity"),
876                             ),
877                         );
878                     }
879                 } else if match_path(ty_path, &paths::HASHSET) {
880                     if method.ident.name == sym::new {
881                         self.suggestions
882                             .insert(e.span, "HashSet::default()".to_string());
883                     } else if method.ident.name == sym!(with_capacity) {
884                         self.suggestions.insert(
885                             e.span,
886                             format!(
887                                 "HashSet::with_capacity_and_hasher({}, Default::default())",
888                                 snippet(self.cx, args[0].span, "capacity"),
889                             ),
890                         );
891                     }
892                 }
893             }
894         }
895
896         walk_expr(self, e);
897     }
898
899     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
900         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
901     }
902 }