1 #![allow(rustc::default_hash_types)]
8 mod redundant_allocation;
13 use std::collections::BTreeMap;
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;
21 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
23 Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem, ImplItemKind, Item,
24 ItemKind, Local, MutTy, QPath, TraitFn, TraitItem, TraitItemKind, TyKind,
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;
36 use clippy_utils::paths;
37 use clippy_utils::{differing_macro_contexts, match_path};
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.
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.
47 /// **Known problems:** None.
52 /// values: Box<Vec<Foo>>,
65 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
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.
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.
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),
81 /// values: Vec<Box<i32>>,
94 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
97 declare_clippy_lint! {
98 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
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.
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.
108 /// **Known problems:** None.
112 /// fn get_data() -> Option<Option<u32>> {
120 /// pub enum Contents {
121 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
122 /// NotYetFetched, // Was Some(None)
123 /// None, // Was None
126 /// fn get_data() -> Contents {
132 "usage of `Option<Option<T>>`"
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`).
139 /// **Why is this bad?** Gankro says:
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.
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
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`.
158 /// **Known problems:** False positives – the instances where using a
159 /// `LinkedList` makes sense are few and far between, but they can still happen.
163 /// # use std::collections::LinkedList;
164 /// let x: LinkedList<usize> = LinkedList::new();
168 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
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.
175 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
178 /// **Known problems:** None.
182 /// fn foo(bar: &Box<T>) { ... }
188 /// fn foo(bar: &T) { ... }
192 "a borrow of a boxed type"
195 declare_clippy_lint! {
196 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
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.
201 /// **Known problems:** None.
205 /// # use std::rc::Rc;
206 /// fn foo(bar: Rc<&usize>) {}
212 /// fn foo(bar: &usize) {}
214 pub REDUNDANT_ALLOCATION,
216 "redundant allocation"
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`.
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>`.
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
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.
236 /// # use std::rc::Rc;
237 /// fn foo(interned: Rc<String>) { ... }
243 /// fn foo(interned: Rc<str>) { ... }
247 "shared ownership of a buffer type"
251 vec_box_size_threshold: u64,
254 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
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 {
265 self.check_fn_decl(cx, decl);
268 fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) {
269 self.check_ty(cx, &field.ty, false);
272 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
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(..) => (),
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);
288 pub fn new(vec_box_size_threshold: u64) -> Self {
289 Self { vec_box_size_threshold }
292 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
293 for input in decl.inputs {
294 self.check_ty(cx, input, false);
297 if let FnRetTy::Return(ref ty) = decl.output {
298 self.check_ty(cx, ty, false);
302 /// Recursively check for `TypePass` lints in the given type. Stop at the first
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() {
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);
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| {
333 .map_or_else(|| [].iter(), |params| params.args.iter())
334 .filter_map(|arg| match arg {
335 GenericArg::Type(ty) => Some(ty),
339 self.check_ty(cx, ty, is_local);
342 QPath::Resolved(None, ref p) => {
343 for ty in p.segments.iter().flat_map(|seg| {
346 .map_or_else(|| [].iter(), |params| params.args.iter())
347 .filter_map(|arg| match arg {
348 GenericArg::Type(ty) => Some(ty),
352 self.check_ty(cx, ty, is_local);
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),
362 self.check_ty(cx, ty, is_local);
366 QPath::LangItem(..) => {},
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);
374 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
375 self.check_ty(cx, ty, is_local)
377 TyKind::Tup(tys) => {
379 self.check_ty(cx, ty, is_local);
387 declare_clippy_lint! {
388 /// **What it does:** Checks for types used in structs, parameters and `let`
389 /// declarations above a certain complexity threshold.
391 /// **Why is this bad?** Too complex types make the code less readable. Consider
392 /// using a `type` definition to simplify them.
394 /// **Known problems:** None.
398 /// # use std::rc::Rc;
400 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
405 "usage of very complex types that might be better factored into `type` definitions"
408 pub struct TypeComplexity {
412 impl TypeComplexity {
414 pub fn new(threshold: u64) -> Self {
419 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
421 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
424 cx: &LateContext<'tcx>,
426 decl: &'tcx FnDecl<'_>,
431 self.check_fndecl(cx, decl);
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);
439 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
441 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
442 // functions, enums, structs, impls and traits are covered
447 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
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(_)) => (),
456 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
458 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
459 // methods are covered by check_fn
460 ImplItemKind::Fn(..) => (),
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);
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);
476 if let FnRetTy::Return(ref ty) = decl.output {
477 self.check_type(cx, ty);
481 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
482 if ty.span.from_expansion() {
486 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
487 visitor.visit_ty(ty);
491 if score > self.threshold {
496 "very complex type used. Consider factoring parts into `type` definitions",
502 /// Walks a type and assigns a complexity score to it.
503 struct TypeComplexityVisitor {
504 /// total complexity score of the type
506 /// current nesting level
510 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
511 type Map = Map<'tcx>;
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),
518 // the "normal" components of a type: named types, arrays/tuples
519 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
521 // function types bring a lot of overhead
522 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
524 TyKind::TraitObject(ref param_bounds, _, _) => {
525 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
527 .bound_generic_params
529 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
531 if has_lifetime_parameters {
532 // complex trait bounds like A<'a, 'b>
535 // simple trait bounds like A + B
542 self.score += add_score;
543 self.nest += sub_nest;
545 self.nest -= sub_nest;
547 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
548 NestedVisitorMap::None
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`).
557 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
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.
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> { }
571 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
573 /// could be rewritten as
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> { }
580 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
584 "missing generalization over different hashers"
587 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
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;
595 cx: &LateContext<'tcx>,
596 diag: &mut DiagnosticBuilder<'_>,
598 generics_suggestion_span: Span,
599 target: &ImplicitHasherType<'_>,
600 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
602 let generics_snip = snippet(cx, generics_span, "");
604 let generics_snip = if generics_snip.is_empty() {
607 &generics_snip[1..generics_snip.len() - 1]
612 "consider adding a type parameter",
615 generics_suggestion_span,
617 "<{}{}S: ::std::hash::BuildHasher{}>",
619 if generics_snip.is_empty() { "" } else { ", " },
620 if vis.suggestions.is_empty() {
623 // request users to add `Default` bound so that generic constructors can be used
630 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
635 if !vis.suggestions.is_empty() {
636 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
640 if !cx.access_levels.is_exported(item.hir_id()) {
645 ItemKind::Impl(ref impl_) => {
646 let mut vis = ImplicitHasherTypeVisitor::new(cx);
647 vis.visit_ty(impl_.self_ty);
649 for target in &vis.found {
650 if differing_macro_contexts(item.span, target.span()) {
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)
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);
674 "impl for `{}` should be generalized over different hashers",
678 suggestion(cx, diag, impl_.generics.span, generics_suggestion_span, target, ctr_vis);
683 ItemKind::Fn(ref sig, ref generics, body_id) => {
684 let body = cx.tcx.hir().body(body_id);
686 for ty in sig.decl.inputs {
687 let mut vis = ImplicitHasherTypeVisitor::new(cx);
690 for target in &vis.found {
691 if in_external_macro(cx.sess(), generics.span) {
694 let generics_suggestion_span = generics.span.substitute_dummy({
695 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
697 let i = snip.find("fn")?;
698 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
700 .expect("failed to create span for type parameters");
701 Span::new(pos, pos, item.span.data().ctxt)
704 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
705 ctr_vis.visit_body(body);
712 "parameter of type `{}` should be generalized over different hashers",
716 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
727 enum ImplicitHasherType<'tcx> {
728 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
729 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
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
744 .filter_map(|arg| match arg {
745 GenericArg::Type(ty) => Some(ty),
749 let params_len = params.len();
751 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
753 if is_type_diagnostic_item(cx, ty, sym::hashmap_type) && params_len == 2 {
754 Some(ImplicitHasherType::HashMap(
757 snippet(cx, params[0].span, "K"),
758 snippet(cx, params[1].span, "V"),
760 } else if is_type_diagnostic_item(cx, ty, sym::hashset_type) && params_len == 1 {
761 Some(ImplicitHasherType::HashSet(
764 snippet(cx, params[0].span, "T"),
774 fn type_name(&self) -> &'static str {
776 ImplicitHasherType::HashMap(..) => "HashMap",
777 ImplicitHasherType::HashSet(..) => "HashSet",
781 fn type_arguments(&self) -> String {
783 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
784 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
788 fn ty(&self) -> Ty<'tcx> {
790 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
794 fn span(&self) -> Span {
796 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
801 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
802 cx: &'a LateContext<'tcx>,
803 found: Vec<ImplicitHasherType<'tcx>>,
806 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
807 fn new(cx: &'a LateContext<'tcx>) -> Self {
808 Self { cx, found: vec![] }
812 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
813 type Map = Map<'tcx>;
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);
823 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
824 NestedVisitorMap::None
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>,
836 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
837 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
840 maybe_typeck_results: cx.maybe_typeck_results(),
842 suggestions: BTreeMap::new(),
847 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
848 type Map = Map<'tcx>;
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;
856 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
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;
862 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
866 if match_path(ty_path, &paths::HASHMAP) {
867 if method.ident.name == sym::new {
869 .insert(e.span, "HashMap::default()".to_string());
870 } else if method.ident.name == sym!(with_capacity) {
871 self.suggestions.insert(
874 "HashMap::with_capacity_and_hasher({}, Default::default())",
875 snippet(self.cx, args[0].span, "capacity"),
879 } else if match_path(ty_path, &paths::HASHSET) {
880 if method.ident.name == sym::new {
882 .insert(e.span, "HashSet::default()".to_string());
883 } else if method.ident.name == sym!(with_capacity) {
884 self.suggestions.insert(
887 "HashSet::with_capacity_and_hasher({}, Default::default())",
888 snippet(self.cx, args[0].span, "capacity"),
899 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
900 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())