]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / new_without_default.rs
1 use clippy_utils::diagnostics::span_lint_hir_and_then;
2 use clippy_utils::return_ty;
3 use clippy_utils::source::snippet;
4 use clippy_utils::sugg::DiagnosticExt;
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_hir::HirIdSet;
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::sym;
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Checks for public types with a `pub fn new() -> Self` method and no
17     /// implementation of
18     /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).
19     ///
20     /// ### Why is this bad?
21     /// The user might expect to be able to use
22     /// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the
23     /// type can be constructed without arguments.
24     ///
25     /// ### Example
26     /// ```ignore
27     /// pub struct Foo(Bar);
28     ///
29     /// impl Foo {
30     ///     pub fn new() -> Self {
31     ///         Foo(Bar::new())
32     ///     }
33     /// }
34     /// ```
35     ///
36     /// To fix the lint, add a `Default` implementation that delegates to `new`:
37     ///
38     /// ```ignore
39     /// pub struct Foo(Bar);
40     ///
41     /// impl Default for Foo {
42     ///     fn default() -> Self {
43     ///         Foo::new()
44     ///     }
45     /// }
46     /// ```
47     #[clippy::version = "pre 1.29.0"]
48     pub NEW_WITHOUT_DEFAULT,
49     style,
50     "`pub fn new() -> Self` method without `Default` implementation"
51 }
52
53 #[derive(Clone, Default)]
54 pub struct NewWithoutDefault {
55     impling_types: Option<HirIdSet>,
56 }
57
58 impl_lint_pass!(NewWithoutDefault => [NEW_WITHOUT_DEFAULT]);
59
60 impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault {
61     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
62         if let hir::ItemKind::Impl(hir::Impl {
63             of_trait: None,
64             generics,
65             self_ty: impl_self_ty,
66             items,
67             ..
68         }) = item.kind
69         {
70             for assoc_item in *items {
71                 if assoc_item.kind == (hir::AssocItemKind::Fn { has_self: false }) {
72                     let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
73                     if in_external_macro(cx.sess(), impl_item.span) {
74                         return;
75                     }
76                     if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
77                         let name = impl_item.ident.name;
78                         let id = impl_item.hir_id();
79                         if sig.header.constness == hir::Constness::Const {
80                             // can't be implemented by default
81                             return;
82                         }
83                         if sig.header.unsafety == hir::Unsafety::Unsafe {
84                             // can't be implemented for unsafe new
85                             return;
86                         }
87                         if cx.tcx.is_doc_hidden(impl_item.owner_id.def_id) {
88                             // shouldn't be implemented when it is hidden in docs
89                             return;
90                         }
91                         if !impl_item.generics.params.is_empty() {
92                             // when the result of `new()` depends on a parameter we should not require
93                             // an impl of `Default`
94                             return;
95                         }
96                         if_chain! {
97                             if sig.decl.inputs.is_empty();
98                             if name == sym::new;
99                             if cx.effective_visibilities.is_reachable(impl_item.owner_id.def_id);
100                             let self_def_id = cx.tcx.hir().get_parent_item(id);
101                             let self_ty = cx.tcx.type_of(self_def_id);
102                             if self_ty == return_ty(cx, id);
103                             if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default);
104                             then {
105                                 if self.impling_types.is_none() {
106                                     let mut impls = HirIdSet::default();
107                                     cx.tcx.for_each_impl(default_trait_id, |d| {
108                                         if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
109                                             if let Some(local_def_id) = ty_def.did().as_local() {
110                                                 impls.insert(cx.tcx.hir().local_def_id_to_hir_id(local_def_id));
111                                             }
112                                         }
113                                     });
114                                     self.impling_types = Some(impls);
115                                 }
116
117                                 // Check if a Default implementation exists for the Self type, regardless of
118                                 // generics
119                                 if_chain! {
120                                     if let Some(ref impling_types) = self.impling_types;
121                                     if let Some(self_def) = cx.tcx.type_of(self_def_id).ty_adt_def();
122                                     if let Some(self_local_did) = self_def.did().as_local();
123                                     let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did);
124                                     if impling_types.contains(&self_id);
125                                     then {
126                                         return;
127                                     }
128                                 }
129
130                                 let generics_sugg = snippet(cx, generics.span, "");
131                                 let self_ty_fmt = self_ty.to_string();
132                                 let self_type_snip = snippet(cx, impl_self_ty.span, &self_ty_fmt);
133                                 span_lint_hir_and_then(
134                                     cx,
135                                     NEW_WITHOUT_DEFAULT,
136                                     id,
137                                     impl_item.span,
138                                     &format!(
139                                         "you should consider adding a `Default` implementation for `{self_type_snip}`"
140                                     ),
141                                     |diag| {
142                                         diag.suggest_prepend_item(
143                                             cx,
144                                             item.span,
145                                             "try adding this",
146                                             &create_new_without_default_suggest_msg(&self_type_snip, &generics_sugg),
147                                             Applicability::MaybeIncorrect,
148                                         );
149                                     },
150                                 );
151                             }
152                         }
153                     }
154                 }
155             }
156         }
157     }
158 }
159
160 fn create_new_without_default_suggest_msg(self_type_snip: &str, generics_sugg: &str) -> String {
161     #[rustfmt::skip]
162     format!(
163 "impl{generics_sugg} Default for {self_type_snip} {{
164     fn default() -> Self {{
165         Self::new()
166     }}
167 }}")
168 }