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;
6 use rustc::hir::def_id::DefId;
7 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
8 use rustc::ty::{self, Ty};
9 use rustc::util::nodemap::NodeSet;
10 use rustc::{declare_tool_lint, lint_array};
11 use rustc_errors::Applicability;
12 use syntax::source_map::Span;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for types with a `fn new() -> Self` method and no
17 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
19 /// It detects both the case when a manual
20 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
21 /// implementation is required and also when it can be created with
22 /// `#[derive(Default)]`
24 /// **Why is this bad?** The user might expect to be able to use
25 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
26 /// type can be constructed without arguments.
28 /// **Known problems:** Hopefully none.
36 /// fn new() -> Self {
47 /// impl Default for Foo {
48 /// fn default() -> Self {
55 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
56 /// can be derived by `#[derive(Default)]`:
62 /// fn new() -> Self {
71 /// #[derive(Default)]
75 /// fn new() -> Self {
81 /// You can also have `new()` call `Default::default()`.
82 pub NEW_WITHOUT_DEFAULT,
84 "`fn new() -> Self` method without `Default` implementation"
87 #[derive(Clone, Default)]
88 pub struct NewWithoutDefault {
89 impling_types: Option<NodeSet>,
92 impl LintPass for NewWithoutDefault {
93 fn get_lints(&self) -> LintArray {
94 lint_array!(NEW_WITHOUT_DEFAULT)
97 fn name(&self) -> &'static str {
102 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
103 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
104 if let hir::ItemKind::Impl(_, _, _, _, None, _, ref items) = item.node {
105 for assoc_item in items {
106 if let hir::AssociatedItemKind::Method { has_self: false } = assoc_item.kind {
107 let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
108 if in_external_macro(cx.sess(), impl_item.span) {
111 if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
112 let name = impl_item.ident.name;
113 let id = impl_item.hir_id;
114 if sig.header.constness == hir::Constness::Const {
115 // can't be implemented by default
118 if sig.header.unsafety == hir::Unsafety::Unsafe {
119 // can't be implemented for unsafe new
122 if impl_item.generics.params.iter().any(|gen| match gen.kind {
123 hir::GenericParamKind::Type { .. } => true,
126 // when the result of `new()` depends on a type parameter we should not require
131 if sig.decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) {
132 let self_did = cx.tcx.hir().local_def_id_from_hir_id(cx.tcx.hir().get_parent_item(id));
133 let self_ty = cx.tcx.type_of(self_did);
135 if same_tys(cx, self_ty, return_ty(cx, id));
136 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
138 if self.impling_types.is_none() {
139 let mut impls = NodeSet::default();
140 cx.tcx.for_each_impl(default_trait_id, |d| {
141 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
142 if let Some(node_id) = cx.tcx.hir().as_local_node_id(ty_def.did) {
143 impls.insert(node_id);
147 self.impling_types = Some(impls);
150 // Check if a Default implementation exists for the Self type, regardless of
153 if let Some(ref impling_types) = self.impling_types;
154 if let Some(self_def) = cx.tcx.type_of(self_did).ty_adt_def();
155 if self_def.did.is_local();
157 let self_id = cx.tcx.hir().local_def_id_to_node_id(self_def.did.to_local());
158 if impling_types.contains(&self_id) {
164 if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
165 span_lint_hir_and_then(
171 "you should consider deriving a `Default` implementation for `{}`",
175 db.suggest_item_with_attr(
179 "#[derive(Default)]",
180 Applicability::MaybeIncorrect,
184 span_lint_hir_and_then(
190 "you should consider adding a `Default` implementation for `{}`",
194 db.suggest_prepend_item(
198 &create_new_without_default_suggest_msg(self_ty),
199 Applicability::MaybeIncorrect,
214 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
217 "impl Default for {} {{
218 fn default() -> Self {{
224 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
226 ty::Adt(adt_def, substs) if adt_def.is_struct() => {
227 for field in adt_def.all_fields() {
228 let f_ty = field.ty(cx.tcx, substs);
229 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
233 Some(cx.tcx.def_span(adt_def.did))