1 use clippy_utils::diagnostics::span_lint_hir_and_then;
2 use clippy_utils::return_ty;
3 use clippy_utils::source::snippet;
4 use clippy_utils::sugg::DiagnosticExt;
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
8 use rustc_hir::HirIdSet;
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 declare_clippy_lint! {
16 /// Checks for public types with a `pub fn new() -> Self` method and no
18 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
20 /// ### Why is this bad?
21 /// The user might expect to be able to use
22 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
23 /// type can be constructed without arguments.
27 /// pub struct Foo(Bar);
30 /// pub fn new() -> Self {
36 /// To fix the lint, add a `Default` implementation that delegates to `new`:
39 /// pub struct Foo(Bar);
41 /// impl Default for Foo {
42 /// fn default() -> Self {
47 #[clippy::version = "pre 1.29.0"]
48 pub NEW_WITHOUT_DEFAULT,
50 "`pub fn new() -> Self` method without `Default` implementation"
53 #[derive(Clone, Default)]
54 pub struct NewWithoutDefault {
55 impling_types: Option<HirIdSet>,
58 impl_lint_pass!(NewWithoutDefault => [NEW_WITHOUT_DEFAULT]);
60 impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault {
61 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
62 if let hir::ItemKind::Impl(hir::Impl {
65 self_ty: impl_self_ty,
70 for assoc_item in *items {
71 if assoc_item.kind == (hir::AssocItemKind::Fn { has_self: false }) {
72 let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
73 if in_external_macro(cx.sess(), impl_item.span) {
76 if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
77 let name = impl_item.ident.name;
78 let id = impl_item.hir_id();
79 if sig.header.constness == hir::Constness::Const {
80 // can't be implemented by default
83 if sig.header.unsafety == hir::Unsafety::Unsafe {
84 // can't be implemented for unsafe new
87 if cx.tcx.is_doc_hidden(impl_item.def_id) {
88 // shouldn't be implemented when it is hidden in docs
95 .any(|gen| matches!(gen.kind, hir::GenericParamKind::Type { .. }))
97 // when the result of `new()` depends on a type parameter we should not require
103 if sig.decl.inputs.is_empty();
105 if cx.access_levels.is_reachable(impl_item.def_id);
106 let self_def_id = cx.tcx.hir().get_parent_item(id);
107 let self_ty = cx.tcx.type_of(self_def_id);
108 if self_ty == return_ty(cx, id);
109 if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default);
111 if self.impling_types.is_none() {
112 let mut impls = HirIdSet::default();
113 cx.tcx.for_each_impl(default_trait_id, |d| {
114 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
115 if let Some(local_def_id) = ty_def.did().as_local() {
116 impls.insert(cx.tcx.hir().local_def_id_to_hir_id(local_def_id));
120 self.impling_types = Some(impls);
123 // Check if a Default implementation exists for the Self type, regardless of
126 if let Some(ref impling_types) = self.impling_types;
127 if let Some(self_def) = cx.tcx.type_of(self_def_id).ty_adt_def();
128 if let Some(self_local_did) = self_def.did().as_local();
129 let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did);
130 if impling_types.contains(&self_id);
136 let generics_sugg = snippet(cx, generics.span, "");
137 let self_ty_fmt = self_ty.to_string();
138 let self_type_snip = snippet(cx, impl_self_ty.span, &self_ty_fmt);
139 span_lint_hir_and_then(
145 "you should consider adding a `Default` implementation for `{}`",
149 diag.suggest_prepend_item(
153 &create_new_without_default_suggest_msg(&self_type_snip, &generics_sugg),
154 Applicability::MaybeIncorrect,
167 fn create_new_without_default_suggest_msg(self_type_snip: &str, generics_sugg: &str) -> String {
170 "impl{} Default for {} {{
171 fn default() -> Self {{
174 }}", generics_sugg, self_type_snip)