1 use crate::utils::paths;
2 use crate::utils::sugg::DiagnosticBuilderExt;
3 use crate::utils::{get_trait_def_id, implements_trait, return_ty, same_tys, span_lint_hir_and_then};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::HirIdSet;
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_middle::ty::{self, Ty};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::source_map::Span;
15 declare_clippy_lint! {
16 /// **What it does:** Checks for types with a `fn new() -> Self` method and no
18 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
20 /// It detects both the case when a manual
21 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
22 /// implementation is required and also when it can be created with
23 /// `#[derive(Default)]`
25 /// **Why is this bad?** The user might expect to be able to use
26 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
27 /// type can be constructed without arguments.
29 /// **Known problems:** Hopefully none.
37 /// fn new() -> Self {
48 /// impl Default for Foo {
49 /// fn default() -> Self {
56 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
57 /// can be derived by `#[derive(Default)]`:
63 /// fn new() -> Self {
72 /// #[derive(Default)]
76 /// fn new() -> Self {
82 /// You can also have `new()` call `Default::default()`.
83 pub NEW_WITHOUT_DEFAULT,
85 "`fn new() -> Self` method without `Default` implementation"
88 #[derive(Clone, Default)]
89 pub struct NewWithoutDefault {
90 impling_types: Option<HirIdSet>,
93 impl_lint_pass!(NewWithoutDefault => [NEW_WITHOUT_DEFAULT]);
95 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
96 #[allow(clippy::too_many_lines)]
97 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
98 if let hir::ItemKind::Impl {
99 of_trait: None, items, ..
102 for assoc_item in items {
103 if let hir::AssocItemKind::Method { has_self: false } = assoc_item.kind {
104 let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
105 if in_external_macro(cx.sess(), impl_item.span) {
108 if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
109 let name = impl_item.ident.name;
110 let id = impl_item.hir_id;
111 if sig.header.constness == hir::Constness::Const {
112 // can't be implemented by default
115 if sig.header.unsafety == hir::Unsafety::Unsafe {
116 // can't be implemented for unsafe new
119 if impl_item.generics.params.iter().any(|gen| match gen.kind {
120 hir::GenericParamKind::Type { .. } => true,
123 // when the result of `new()` depends on a type parameter we should not require
128 if sig.decl.inputs.is_empty() && name == sym!(new) && cx.access_levels.is_reachable(id) {
129 let self_did = cx.tcx.hir().local_def_id(cx.tcx.hir().get_parent_item(id));
130 let self_ty = cx.tcx.type_of(self_did);
132 if same_tys(cx, self_ty, return_ty(cx, id));
133 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
135 if self.impling_types.is_none() {
136 let mut impls = HirIdSet::default();
137 cx.tcx.for_each_impl(default_trait_id, |d| {
138 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
139 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
140 impls.insert(hir_id);
144 self.impling_types = Some(impls);
147 // Check if a Default implementation exists for the Self type, regardless of
150 if let Some(ref impling_types) = self.impling_types;
151 if let Some(self_def) = cx.tcx.type_of(self_did).ty_adt_def();
152 if let Some(self_def_id) = self_def.did.as_local();
154 let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_def_id);
155 if impling_types.contains(&self_id) {
161 if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
162 span_lint_hir_and_then(
168 "you should consider deriving a `Default` implementation for `{}`",
172 db.suggest_item_with_attr(
176 "#[derive(Default)]",
177 Applicability::MaybeIncorrect,
181 span_lint_hir_and_then(
187 "you should consider adding a `Default` implementation for `{}`",
191 db.suggest_prepend_item(
195 &create_new_without_default_suggest_msg(self_ty),
196 Applicability::MaybeIncorrect,
211 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
214 "impl Default for {} {{
215 fn default() -> Self {{
221 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
223 ty::Adt(adt_def, substs) if adt_def.is_struct() => {
224 for field in adt_def.all_fields() {
225 let f_ty = field.ty(cx.tcx, substs);
226 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
230 Some(cx.tcx.def_span(adt_def.did))