1 use crate::utils::paths;
2 use crate::utils::sugg::DiagnosticBuilderExt;
3 use crate::utils::{get_trait_def_id, return_ty, span_lint_hir_and_then};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
7 use rustc_hir::HirIdSet;
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty::{Ty, TyS};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for types with a `fn new() -> Self` method and no
16 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
18 /// **Why is this bad?** The user might expect to be able to use
19 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
20 /// type can be constructed without arguments.
22 /// **Known problems:** Hopefully none.
30 /// fn new() -> Self {
36 /// To fix the lint, add a `Default` implementation that delegates to `new`:
41 /// impl Default for Foo {
42 /// fn default() -> Self {
47 pub NEW_WITHOUT_DEFAULT,
49 "`fn new() -> Self` method without `Default` implementation"
52 #[derive(Clone, Default)]
53 pub struct NewWithoutDefault {
54 impling_types: Option<HirIdSet>,
57 impl_lint_pass!(NewWithoutDefault => [NEW_WITHOUT_DEFAULT]);
59 impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault {
60 #[allow(clippy::too_many_lines)]
61 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
62 if let hir::ItemKind::Impl {
63 of_trait: None, items, ..
66 for assoc_item in items {
67 if let hir::AssocItemKind::Fn { has_self: false } = assoc_item.kind {
68 let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
69 if in_external_macro(cx.sess(), impl_item.span) {
72 if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
73 let name = impl_item.ident.name;
74 let id = impl_item.hir_id;
75 if sig.header.constness == hir::Constness::Const {
76 // can't be implemented by default
79 if sig.header.unsafety == hir::Unsafety::Unsafe {
80 // can't be implemented for unsafe new
87 .any(|gen| matches!(gen.kind, hir::GenericParamKind::Type { .. }))
89 // when the result of `new()` depends on a type parameter we should not require
94 if sig.decl.inputs.is_empty() && name == sym!(new) && cx.access_levels.is_reachable(id) {
95 let self_def_id = cx.tcx.hir().local_def_id(cx.tcx.hir().get_parent_item(id));
96 let self_ty = cx.tcx.type_of(self_def_id);
98 if TyS::same_type(self_ty, return_ty(cx, id));
99 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
101 if self.impling_types.is_none() {
102 let mut impls = HirIdSet::default();
103 cx.tcx.for_each_impl(default_trait_id, |d| {
104 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
105 if let Some(local_def_id) = ty_def.did.as_local() {
106 impls.insert(cx.tcx.hir().as_local_hir_id(local_def_id));
110 self.impling_types = Some(impls);
113 // Check if a Default implementation exists for the Self type, regardless of
116 if let Some(ref impling_types) = self.impling_types;
117 if let Some(self_def) = cx.tcx.type_of(self_def_id).ty_adt_def();
118 if let Some(self_local_did) = self_def.did.as_local();
120 let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did);
121 if impling_types.contains(&self_id) {
127 span_lint_hir_and_then(
133 "you should consider adding a `Default` implementation for `{}`",
137 diag.suggest_prepend_item(
141 &create_new_without_default_suggest_msg(self_ty),
142 Applicability::MaybeIncorrect,
156 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
159 "impl Default for {} {{
160 fn default() -> Self {{