]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Auto merge of #3597 - xfix:match-ergonomics, r=phansch
[rust.git] / clippy_lints / src / new_without_default.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
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.
9
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;
14 use rustc::hir;
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;
22
23 /// **What it does:** Checks for types with a `fn new() -> Self` method and no
24 /// implementation of
25 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
26 ///
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)]
31 ///
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.
35 ///
36 /// **Known problems:** Hopefully none.
37 ///
38 /// **Example:**
39 ///
40 /// ```rust
41 /// struct Foo(Bar);
42 ///
43 /// impl Foo {
44 ///     fn new() -> Self {
45 ///         Foo(Bar::new())
46 ///     }
47 /// }
48 /// ```
49 ///
50 /// Instead, use:
51 ///
52 /// ```rust
53 /// struct Foo(Bar);
54 ///
55 /// impl Default for Foo {
56 ///     fn default() -> Self {
57 ///         Foo(Bar::new())
58 ///     }
59 /// }
60 /// ```
61 ///
62 /// Or, if
63 /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)
64 /// can be derived by `#[derive(Default)]`:
65 ///
66 /// ```rust
67 /// struct Foo;
68 ///
69 /// impl Foo {
70 ///     fn new() -> Self {
71 ///         Foo
72 ///     }
73 /// }
74 /// ```
75 ///
76 /// Instead, use:
77 ///
78 /// ```rust
79 /// #[derive(Default)]
80 /// struct Foo;
81 ///
82 /// impl Foo {
83 ///     fn new() -> Self {
84 ///         Foo
85 ///     }
86 /// }
87 /// ```
88 ///
89 /// You can also have `new()` call `Default::default()`.
90 declare_clippy_lint! {
91     pub NEW_WITHOUT_DEFAULT,
92     style,
93     "`fn new() -> Self` method without `Default` implementation"
94 }
95
96 #[derive(Clone, Default)]
97 pub struct NewWithoutDefault {
98     impling_types: Option<NodeSet>,
99 }
100
101 impl LintPass for NewWithoutDefault {
102     fn get_lints(&self) -> LintArray {
103         lint_array!(NEW_WITHOUT_DEFAULT)
104     }
105 }
106
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) {
114                         return;
115                     }
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
121                             return;
122                         }
123                         if sig.header.unsafety == hir::Unsafety::Unsafe {
124                             // can't be implemented for unsafe new
125                             return;
126                         }
127                         if impl_item.generics.params.iter().any(|gen| match gen.kind {
128                             hir::GenericParamKind::Type { .. } => true,
129                             _ => false,
130                         }) {
131                             // when the result of `new()` depends on a type parameter we should not require
132                             // an
133                             // impl of `Default`
134                             return;
135                         }
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);
139                             if_chain! {
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);
142                                 then {
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);
149                                                 }
150                                             }
151                                         });
152                                         self.impling_types = Some(impls);
153                                     }
154
155                                     // Check if a Default implementation exists for the Self type, regardless of
156                                     // generics
157                                     if_chain! {
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();
161                                         then {
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) {
164                                                 return;
165                                             }
166                                         }
167                                     }
168
169                                     if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
170                                         span_lint_node_and_then(
171                                             cx,
172                                             NEW_WITHOUT_DEFAULT,
173                                             id,
174                                             impl_item.span,
175                                             &format!(
176                                                 "you should consider deriving a `Default` implementation for `{}`",
177                                                 self_ty
178                                             ),
179                                             |db| {
180                                                 db.suggest_item_with_attr(
181                                                     cx,
182                                                     sp,
183                                                     "try this",
184                                                     "#[derive(Default)]",
185                                                     Applicability::MaybeIncorrect,
186                                                 );
187                                             });
188                                     } else {
189                                         span_lint_node_and_then(
190                                             cx,
191                                             NEW_WITHOUT_DEFAULT,
192                                             id,
193                                             impl_item.span,
194                                             &format!(
195                                                 "you should consider adding a `Default` implementation for `{}`",
196                                                 self_ty
197                                             ),
198                                             |db| {
199                                                 db.suggest_prepend_item(
200                                                     cx,
201                                                     item.span,
202                                                     "try this",
203                                                     &create_new_without_default_suggest_msg(self_ty),
204                                                     Applicability::MaybeIncorrect,
205                                                 );
206                                             },
207                                         );
208                                     }
209                                 }
210                             }
211                         }
212                     }
213                 }
214             }
215         }
216     }
217 }
218
219 fn create_new_without_default_suggest_msg(ty: Ty<'_>) -> String {
220     #[rustfmt::skip]
221     format!(
222 "impl Default for {} {{
223     fn default() -> Self {{
224         Self::new()
225     }}
226 }}", ty)
227 }
228
229 fn can_derive_default<'t, 'c>(ty: Ty<'t>, cx: &LateContext<'c, 't>, default_trait_id: DefId) -> Option<Span> {
230     match ty.sty {
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, &[]) {
235                     return None;
236                 }
237             }
238             Some(cx.tcx.def_span(adt_def.did))
239         },
240         _ => None,
241     }
242 }