1 #![allow(rustc::default_hash_types)]
8 mod redundant_allocation;
13 use std::cmp::Ordering;
14 use std::collections::BTreeMap;
16 use clippy_utils::diagnostics::{multispan_sugg, span_lint, span_lint_and_then};
17 use clippy_utils::source::{snippet, snippet_opt};
18 use clippy_utils::ty::is_type_diagnostic_item;
19 use if_chain::if_chain;
20 use rustc_errors::DiagnosticBuilder;
22 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
24 Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem, ImplItemKind, Item,
25 ItemKind, Local, MutTy, QPath, TraitFn, TraitItem, TraitItemKind, TyKind,
27 use rustc_lint::{LateContext, LateLintPass, LintContext};
28 use rustc_middle::hir::map::Map;
29 use rustc_middle::lint::in_external_macro;
30 use rustc_middle::ty::{self, IntTy, Ty, TyS, TypeckResults, UintTy};
31 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
32 use rustc_span::source_map::Span;
33 use rustc_span::symbol::sym;
34 use rustc_target::abi::LayoutOf;
35 use rustc_target::spec::abi::Abi;
36 use rustc_typeck::hir_ty_to_ty;
38 use crate::consts::{constant, Constant};
39 use clippy_utils::paths;
40 use clippy_utils::{comparisons, differing_macro_contexts, match_path, sext};
42 declare_clippy_lint! {
43 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
44 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
46 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
47 /// the heap. So if you `Box` it, you just add another level of indirection
48 /// without any benefit whatsoever.
50 /// **Known problems:** None.
55 /// values: Box<Vec<Foo>>,
68 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
71 declare_clippy_lint! {
72 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
73 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
75 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
76 /// the heap. So if you `Box` its contents, you just add another level of indirection.
78 /// **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),
84 /// values: Vec<Box<i32>>,
97 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
100 declare_clippy_lint! {
101 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
104 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
105 /// represents an optional optional value which is logically the same thing as an optional
106 /// value but has an unneeded extra level of wrapping.
108 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
109 /// consider a custom `enum` instead, with clear names for each case.
111 /// **Known problems:** None.
115 /// fn get_data() -> Option<Option<u32>> {
123 /// pub enum Contents {
124 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
125 /// NotYetFetched, // Was Some(None)
126 /// None, // Was None
129 /// fn get_data() -> Contents {
135 "usage of `Option<Option<T>>`"
138 declare_clippy_lint! {
139 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
140 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
142 /// **Why is this bad?** Gankro says:
144 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
145 /// pointers and indirection.
146 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
148 /// > "only" amortized for push/pop, should be faster in the general case for
149 /// almost every possible
150 /// > workload, and isn't even amortized at all if you can predict the capacity
153 /// > `LinkedList`s are only really good if you're doing a lot of merging or
154 /// splitting of lists.
155 /// > This is because they can just mangle some pointers instead of actually
156 /// copying the data. Even
157 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
158 /// can still be better
159 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
161 /// **Known problems:** False positives – the instances where using a
162 /// `LinkedList` makes sense are few and far between, but they can still happen.
166 /// # use std::collections::LinkedList;
167 /// let x: LinkedList<usize> = LinkedList::new();
171 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
174 declare_clippy_lint! {
175 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
176 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
178 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
181 /// **Known problems:** None.
185 /// fn foo(bar: &Box<T>) { ... }
191 /// fn foo(bar: &T) { ... }
195 "a borrow of a boxed type"
198 declare_clippy_lint! {
199 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
201 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
202 /// add an unnecessary level of indirection.
204 /// **Known problems:** None.
208 /// # use std::rc::Rc;
209 /// fn foo(bar: Rc<&usize>) {}
215 /// fn foo(bar: &usize) {}
217 pub REDUNDANT_ALLOCATION,
219 "redundant allocation"
222 declare_clippy_lint! {
223 /// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
225 /// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
226 /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
228 /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
229 /// works if there are no additional references yet, which usually defeats the purpose of
230 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
231 /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
234 /// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
235 /// cases where mutation only happens before there are any additional references.
239 /// # use std::rc::Rc;
240 /// fn foo(interned: Rc<String>) { ... }
246 /// fn foo(interned: Rc<str>) { ... }
250 "shared ownership of a buffer type"
254 vec_box_size_threshold: u64,
257 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
259 impl<'tcx> LateLintPass<'tcx> for Types {
260 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
261 // Skip trait implementations; see issue #605.
262 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
263 if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
268 self.check_fn_decl(cx, decl);
271 fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) {
272 self.check_ty(cx, &field.ty, false);
275 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
277 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
278 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
279 TraitItemKind::Type(..) => (),
283 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
284 if let Some(ref ty) = local.ty {
285 self.check_ty(cx, ty, true);
291 pub fn new(vec_box_size_threshold: u64) -> Self {
292 Self { vec_box_size_threshold }
295 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
296 for input in decl.inputs {
297 self.check_ty(cx, input, false);
300 if let FnRetTy::Return(ref ty) = decl.output {
301 self.check_ty(cx, ty, false);
305 /// Recursively check for `TypePass` lints in the given type. Stop at the first
308 /// The parameter `is_local` distinguishes the context of the type.
309 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
310 if hir_ty.span.from_expansion() {
314 TyKind::Path(ref qpath) if !is_local => {
315 let hir_id = hir_ty.hir_id;
316 let res = cx.qpath_res(qpath, hir_id);
317 if let Some(def_id) = res.opt_def_id() {
318 let mut triggered = false;
319 triggered |= box_vec::check(cx, hir_ty, qpath, def_id);
320 triggered |= redundant_allocation::check(cx, hir_ty, qpath, def_id);
321 triggered |= rc_buffer::check(cx, hir_ty, qpath, def_id);
322 triggered |= vec_box::check(cx, hir_ty, qpath, def_id, self.vec_box_size_threshold);
323 triggered |= option_option::check(cx, hir_ty, qpath, def_id);
324 triggered |= linked_list::check(cx, hir_ty, def_id);
331 QPath::Resolved(Some(ref ty), ref p) => {
332 self.check_ty(cx, ty, is_local);
333 for ty in p.segments.iter().flat_map(|seg| {
336 .map_or_else(|| [].iter(), |params| params.args.iter())
337 .filter_map(|arg| match arg {
338 GenericArg::Type(ty) => Some(ty),
342 self.check_ty(cx, ty, is_local);
345 QPath::Resolved(None, ref p) => {
346 for ty in p.segments.iter().flat_map(|seg| {
349 .map_or_else(|| [].iter(), |params| params.args.iter())
350 .filter_map(|arg| match arg {
351 GenericArg::Type(ty) => Some(ty),
355 self.check_ty(cx, ty, is_local);
358 QPath::TypeRelative(ref ty, ref seg) => {
359 self.check_ty(cx, ty, is_local);
360 if let Some(ref params) = seg.args {
361 for ty in params.args.iter().filter_map(|arg| match arg {
362 GenericArg::Type(ty) => Some(ty),
365 self.check_ty(cx, ty, is_local);
369 QPath::LangItem(..) => {},
372 TyKind::Rptr(ref lt, ref mut_ty) => {
373 if !borrowed_box::check(cx, hir_ty, lt, mut_ty) {
374 self.check_ty(cx, &mut_ty.ty, is_local);
377 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
378 self.check_ty(cx, ty, is_local)
380 TyKind::Tup(tys) => {
382 self.check_ty(cx, ty, is_local);
390 declare_clippy_lint! {
391 /// **What it does:** Checks for types used in structs, parameters and `let`
392 /// declarations above a certain complexity threshold.
394 /// **Why is this bad?** Too complex types make the code less readable. Consider
395 /// using a `type` definition to simplify them.
397 /// **Known problems:** None.
401 /// # use std::rc::Rc;
403 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
408 "usage of very complex types that might be better factored into `type` definitions"
411 pub struct TypeComplexity {
415 impl TypeComplexity {
417 pub fn new(threshold: u64) -> Self {
422 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
424 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
427 cx: &LateContext<'tcx>,
429 decl: &'tcx FnDecl<'_>,
434 self.check_fndecl(cx, decl);
437 fn check_field_def(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::FieldDef<'_>) {
438 // enum variants are also struct fields now
439 self.check_type(cx, &field.ty);
442 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
444 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
445 // functions, enums, structs, impls and traits are covered
450 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
452 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
453 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
454 // methods with default impl are covered by check_fn
455 TraitItemKind::Type(..) | TraitItemKind::Fn(_, TraitFn::Provided(_)) => (),
459 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
461 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
462 // methods are covered by check_fn
463 ImplItemKind::Fn(..) => (),
467 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
468 if let Some(ref ty) = local.ty {
469 self.check_type(cx, ty);
474 impl<'tcx> TypeComplexity {
475 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
476 for arg in decl.inputs {
477 self.check_type(cx, arg);
479 if let FnRetTy::Return(ref ty) = decl.output {
480 self.check_type(cx, ty);
484 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
485 if ty.span.from_expansion() {
489 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
490 visitor.visit_ty(ty);
494 if score > self.threshold {
499 "very complex type used. Consider factoring parts into `type` definitions",
505 /// Walks a type and assigns a complexity score to it.
506 struct TypeComplexityVisitor {
507 /// total complexity score of the type
509 /// current nesting level
513 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
514 type Map = Map<'tcx>;
516 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
517 let (add_score, sub_nest) = match ty.kind {
518 // _, &x and *x have only small overhead; don't mess with nesting level
519 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
521 // the "normal" components of a type: named types, arrays/tuples
522 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
524 // function types bring a lot of overhead
525 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
527 TyKind::TraitObject(ref param_bounds, _, _) => {
528 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
530 .bound_generic_params
532 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
534 if has_lifetime_parameters {
535 // complex trait bounds like A<'a, 'b>
538 // simple trait bounds like A + B
545 self.score += add_score;
546 self.nest += sub_nest;
548 self.nest -= sub_nest;
550 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
551 NestedVisitorMap::None
555 declare_clippy_lint! {
556 /// **What it does:** Checks for comparisons where the relation is always either
557 /// true or false, but where one side has been upcast so that the comparison is
558 /// necessary. Only integer types are checked.
560 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
561 /// will mistakenly imply that it is possible for `x` to be outside the range of
564 /// **Known problems:**
565 /// https://github.com/rust-lang/rust-clippy/issues/886
570 /// (x as u32) > 300;
572 pub INVALID_UPCAST_COMPARISONS,
574 "a comparison involving an upcast which is always true or false"
577 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
579 #[derive(Copy, Clone, Debug, Eq)]
586 #[allow(clippy::cast_sign_loss)]
588 fn cmp_s_u(s: i128, u: u128) -> Ordering {
591 } else if u > (i128::MAX as u128) {
599 impl PartialEq for FullInt {
601 fn eq(&self, other: &Self) -> bool {
602 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
606 impl PartialOrd for FullInt {
608 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
609 Some(match (self, other) {
610 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
611 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
612 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
613 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
618 impl Ord for FullInt {
620 fn cmp(&self, other: &Self) -> Ordering {
621 self.partial_cmp(other)
622 .expect("`partial_cmp` for FullInt can never return `None`")
626 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
627 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
628 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
629 let cast_ty = cx.typeck_results().expr_ty(expr);
630 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
631 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
634 match pre_cast_ty.kind() {
635 ty::Int(int_ty) => Some(match int_ty {
636 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
637 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
638 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
639 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
640 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
641 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
643 ty::Uint(uint_ty) => Some(match uint_ty {
644 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
645 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
646 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
647 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
648 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
649 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
658 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
659 let val = constant(cx, cx.typeck_results(), expr)?.0;
660 if let Constant::Int(const_int) = val {
661 match *cx.typeck_results().expr_ty(expr).kind() {
662 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
663 ty::Uint(_) => Some(FullInt::U(const_int)),
671 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
672 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
675 INVALID_UPCAST_COMPARISONS,
678 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
679 snippet(cx, cast_val.span, "the expression"),
680 if always { "true" } else { "false" },
686 fn upcast_comparison_bounds_err<'tcx>(
687 cx: &LateContext<'tcx>,
689 rel: comparisons::Rel,
690 lhs_bounds: Option<(FullInt, FullInt)>,
695 use clippy_utils::comparisons::Rel;
697 if let Some((lb, ub)) = lhs_bounds {
698 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
699 if rel == Rel::Eq || rel == Rel::Ne {
700 if norm_rhs_val < lb || norm_rhs_val > ub {
701 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
703 } else if match rel {
718 Rel::Eq | Rel::Ne => unreachable!(),
720 err_upcast_comparison(cx, span, lhs, true)
721 } else if match rel {
736 Rel::Eq | Rel::Ne => unreachable!(),
738 err_upcast_comparison(cx, span, lhs, false)
744 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
745 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
746 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
747 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
748 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
754 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
755 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
757 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
758 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
763 declare_clippy_lint! {
764 /// **What it does:** Checks for public `impl` or `fn` missing generalization
765 /// over different hashers and implicitly defaulting to the default hashing
766 /// algorithm (`SipHash`).
768 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
771 /// **Known problems:** Suggestions for replacing constructors can contain
772 /// false-positives. Also applying suggestions can require modification of other
773 /// pieces of code, possibly including external crates.
777 /// # use std::collections::HashMap;
778 /// # use std::hash::{Hash, BuildHasher};
779 /// # trait Serialize {};
780 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
782 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
784 /// could be rewritten as
786 /// # use std::collections::HashMap;
787 /// # use std::hash::{Hash, BuildHasher};
788 /// # trait Serialize {};
789 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
791 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
795 "missing generalization over different hashers"
798 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
800 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
801 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
802 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
803 use rustc_span::BytePos;
806 cx: &LateContext<'tcx>,
807 diag: &mut DiagnosticBuilder<'_>,
809 generics_suggestion_span: Span,
810 target: &ImplicitHasherType<'_>,
811 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
813 let generics_snip = snippet(cx, generics_span, "");
815 let generics_snip = if generics_snip.is_empty() {
818 &generics_snip[1..generics_snip.len() - 1]
823 "consider adding a type parameter",
826 generics_suggestion_span,
828 "<{}{}S: ::std::hash::BuildHasher{}>",
830 if generics_snip.is_empty() { "" } else { ", " },
831 if vis.suggestions.is_empty() {
834 // request users to add `Default` bound so that generic constructors can be used
841 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
846 if !vis.suggestions.is_empty() {
847 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
851 if !cx.access_levels.is_exported(item.hir_id()) {
856 ItemKind::Impl(ref impl_) => {
857 let mut vis = ImplicitHasherTypeVisitor::new(cx);
858 vis.visit_ty(impl_.self_ty);
860 for target in &vis.found {
861 if differing_macro_contexts(item.span, target.span()) {
865 let generics_suggestion_span = impl_.generics.span.substitute_dummy({
866 let pos = snippet_opt(cx, item.span.until(target.span()))
867 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
868 if let Some(pos) = pos {
869 Span::new(pos, pos, item.span.data().ctxt)
875 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
876 for item in impl_.items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
877 ctr_vis.visit_impl_item(item);
885 "impl for `{}` should be generalized over different hashers",
889 suggestion(cx, diag, impl_.generics.span, generics_suggestion_span, target, ctr_vis);
894 ItemKind::Fn(ref sig, ref generics, body_id) => {
895 let body = cx.tcx.hir().body(body_id);
897 for ty in sig.decl.inputs {
898 let mut vis = ImplicitHasherTypeVisitor::new(cx);
901 for target in &vis.found {
902 if in_external_macro(cx.sess(), generics.span) {
905 let generics_suggestion_span = generics.span.substitute_dummy({
906 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
908 let i = snip.find("fn")?;
909 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
911 .expect("failed to create span for type parameters");
912 Span::new(pos, pos, item.span.data().ctxt)
915 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
916 ctr_vis.visit_body(body);
923 "parameter of type `{}` should be generalized over different hashers",
927 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
938 enum ImplicitHasherType<'tcx> {
939 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
940 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
943 impl<'tcx> ImplicitHasherType<'tcx> {
944 /// Checks that `ty` is a target type without a `BuildHasher`.
945 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
946 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
947 let params: Vec<_> = path
955 .filter_map(|arg| match arg {
956 GenericArg::Type(ty) => Some(ty),
960 let params_len = params.len();
962 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
964 if is_type_diagnostic_item(cx, ty, sym::hashmap_type) && params_len == 2 {
965 Some(ImplicitHasherType::HashMap(
968 snippet(cx, params[0].span, "K"),
969 snippet(cx, params[1].span, "V"),
971 } else if is_type_diagnostic_item(cx, ty, sym::hashset_type) && params_len == 1 {
972 Some(ImplicitHasherType::HashSet(
975 snippet(cx, params[0].span, "T"),
985 fn type_name(&self) -> &'static str {
987 ImplicitHasherType::HashMap(..) => "HashMap",
988 ImplicitHasherType::HashSet(..) => "HashSet",
992 fn type_arguments(&self) -> String {
994 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
995 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
999 fn ty(&self) -> Ty<'tcx> {
1001 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
1005 fn span(&self) -> Span {
1007 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
1012 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
1013 cx: &'a LateContext<'tcx>,
1014 found: Vec<ImplicitHasherType<'tcx>>,
1017 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
1018 fn new(cx: &'a LateContext<'tcx>) -> Self {
1019 Self { cx, found: vec![] }
1023 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
1024 type Map = Map<'tcx>;
1026 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
1027 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
1028 self.found.push(target);
1034 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1035 NestedVisitorMap::None
1039 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
1040 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1041 cx: &'a LateContext<'tcx>,
1042 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
1043 target: &'b ImplicitHasherType<'tcx>,
1044 suggestions: BTreeMap<Span, String>,
1047 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1048 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
1051 maybe_typeck_results: cx.maybe_typeck_results(),
1053 suggestions: BTreeMap::new(),
1058 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1059 type Map = Map<'tcx>;
1061 fn visit_body(&mut self, body: &'tcx Body<'_>) {
1062 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
1063 walk_body(self, body);
1064 self.maybe_typeck_results = old_maybe_typeck_results;
1067 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
1069 if let ExprKind::Call(ref fun, ref args) = e.kind;
1070 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
1071 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
1073 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
1077 if match_path(ty_path, &paths::HASHMAP) {
1078 if method.ident.name == sym::new {
1080 .insert(e.span, "HashMap::default()".to_string());
1081 } else if method.ident.name == sym!(with_capacity) {
1082 self.suggestions.insert(
1085 "HashMap::with_capacity_and_hasher({}, Default::default())",
1086 snippet(self.cx, args[0].span, "capacity"),
1090 } else if match_path(ty_path, &paths::HASHSET) {
1091 if method.ident.name == sym::new {
1093 .insert(e.span, "HashSet::default()".to_string());
1094 } else if method.ident.name == sym!(with_capacity) {
1095 self.suggestions.insert(
1098 "HashSet::with_capacity_and_hasher({}, Default::default())",
1099 snippet(self.cx, args[0].span, "capacity"),
1110 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1111 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())