1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::utils::paths;
11 use crate::utils::sugg::DiagnosticBuilderExt;
12 use crate::utils::{get_trait_def_id, implements_trait, return_ty, same_tys, span_lint_node_and_then};
13 use if_chain::if_chain;
15 use rustc::hir::def_id::DefId;
16 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
17 use rustc::ty::{self, Ty};
18 use rustc::util::nodemap::NodeSet;
19 use rustc::{declare_tool_lint, lint_array};
20 use rustc_errors::Applicability;
21 use syntax::source_map::Span;
23 /// **What it does:** Checks for types with a `fn new() -> Self` method and no
25 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
27 /// It detects both the case when a manual
28 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
29 /// implementation is required and also when it can be created with
30 /// `#[derive(Default)]
32 /// **Why is this bad?** The user might expect to be able to use
33 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
34 /// type can be constructed without arguments.
36 /// **Known problems:** Hopefully none.
44 /// fn new() -> Self {
55 /// impl Default for Foo {
56 /// fn default() -> Self {
63 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
64 /// can be derived by `#[derive(Default)]`:
70 /// fn new() -> Self {
79 /// #[derive(Default)]
83 /// fn new() -> Self {
89 /// You can also have `new()` call `Default::default()`.
90 declare_clippy_lint! {
91 pub NEW_WITHOUT_DEFAULT,
93 "`fn new() -> Self` method without `Default` implementation"
96 #[derive(Clone, Default)]
97 pub struct NewWithoutDefault {
98 impling_types: Option<NodeSet>,
101 impl LintPass for NewWithoutDefault {
102 fn get_lints(&self) -> LintArray {
103 lint_array!(NEW_WITHOUT_DEFAULT)
107 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
108 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
109 if let hir::ItemKind::Impl(_, _, _, _, None, _, ref items) = item.node {
110 for assoc_item in items {
111 if let hir::AssociatedItemKind::Method { has_self: false } = assoc_item.kind {
112 let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
113 if in_external_macro(cx.sess(), impl_item.span) {
116 if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
117 let name = impl_item.ident.name;
118 let id = impl_item.id;
119 if sig.header.constness == hir::Constness::Const {
120 // can't be implemented by default
123 if sig.header.unsafety == hir::Unsafety::Unsafe {
124 // can't be implemented for unsafe new
127 if impl_item.generics.params.iter().any(|gen| match gen.kind {
128 hir::GenericParamKind::Type { .. } => true,
131 // when the result of `new()` depends on a type parameter we should not require
136 if sig.decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) {
137 let self_did = cx.tcx.hir().local_def_id(cx.tcx.hir().get_parent(id));
138 let self_ty = cx.tcx.type_of(self_did);
140 if same_tys(cx, self_ty, return_ty(cx, id));
141 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
143 if self.impling_types.is_none() {
144 let mut impls = NodeSet::default();
145 cx.tcx.for_each_impl(default_trait_id, |d| {
146 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
147 if let Some(node_id) = cx.tcx.hir().as_local_node_id(ty_def.did) {
148 impls.insert(node_id);
152 self.impling_types = Some(impls);
155 // Check if a Default implementation exists for the Self type, regardless of
158 if let Some(ref impling_types) = self.impling_types;
159 if let Some(self_def) = cx.tcx.type_of(self_did).ty_adt_def();
160 if self_def.did.is_local();
162 let self_id = cx.tcx.hir().local_def_id_to_node_id(self_def.did.to_local());
163 if impling_types.contains(&self_id) {
169 if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
170 span_lint_node_and_then(
176 "you should consider deriving a `Default` implementation for `{}`",
180 db.suggest_item_with_attr(
184 "#[derive(Default)]",
185 Applicability::MaybeIncorrect,
189 span_lint_node_and_then(
195 "you should consider adding a `Default` implementation for `{}`",
199 db.suggest_prepend_item(
203 &create_new_without_default_suggest_msg(self_ty),
204 Applicability::MaybeIncorrect,
219 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
222 "impl Default for {} {{
223 fn default() -> Self {{
229 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
231 ty::Adt(adt_def, substs) if adt_def.is_struct() => {
232 for field in adt_def.all_fields() {
233 let f_ty = field.ty(cx.tcx, substs);
234 if !implements_trait(cx, f_ty, default_trait_id, &[]) {
238 Some(cx.tcx.def_span(adt_def.did))