]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/new_without_default.rs
Auto merge of #8464 - Jarcho:ptr_arg_8463, r=camsteffen
[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::DiagnosticBuilderExt;
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     #[allow(clippy::too_many_lines)]
62     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
63         if let hir::ItemKind::Impl(hir::Impl {
64             of_trait: None,
65             ref generics,
66             self_ty: impl_self_ty,
67             items,
68             ..
69         }) = item.kind
70         {
71             for assoc_item in items {
72                 if assoc_item.kind == (hir::AssocItemKind::Fn { has_self: false }) {
73                     let impl_item = cx.tcx.hir().impl_item(assoc_item.id);
74                     if in_external_macro(cx.sess(), impl_item.span) {
75                         return;
76                     }
77                     if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
78                         let name = impl_item.ident.name;
79                         let id = impl_item.hir_id();
80                         if sig.header.constness == hir::Constness::Const {
81                             // can't be implemented by default
82                             return;
83                         }
84                         if sig.header.unsafety == hir::Unsafety::Unsafe {
85                             // can't be implemented for unsafe new
86                             return;
87                         }
88                         if clippy_utils::is_doc_hidden(cx.tcx.hir().attrs(id)) {
89                             // shouldn't be implemented when it is hidden in docs
90                             return;
91                         }
92                         if impl_item
93                             .generics
94                             .params
95                             .iter()
96                             .any(|gen| matches!(gen.kind, hir::GenericParamKind::Type { .. }))
97                         {
98                             // when the result of `new()` depends on a type parameter we should not require
99                             // an
100                             // impl of `Default`
101                             return;
102                         }
103                         if_chain! {
104                             if sig.decl.inputs.is_empty();
105                             if name == sym::new;
106                             if cx.access_levels.is_reachable(impl_item.def_id);
107                             let self_def_id = cx.tcx.hir().get_parent_item(id);
108                             let self_ty = cx.tcx.type_of(self_def_id);
109                             if self_ty == return_ty(cx, id);
110                             if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default);
111                             then {
112                                 if self.impling_types.is_none() {
113                                     let mut impls = HirIdSet::default();
114                                     cx.tcx.for_each_impl(default_trait_id, |d| {
115                                         if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
116                                             if let Some(local_def_id) = ty_def.did.as_local() {
117                                                 impls.insert(cx.tcx.hir().local_def_id_to_hir_id(local_def_id));
118                                             }
119                                         }
120                                     });
121                                     self.impling_types = Some(impls);
122                                 }
123
124                                 // Check if a Default implementation exists for the Self type, regardless of
125                                 // generics
126                                 if_chain! {
127                                     if let Some(ref impling_types) = self.impling_types;
128                                     if let Some(self_def) = cx.tcx.type_of(self_def_id).ty_adt_def();
129                                     if let Some(self_local_did) = self_def.did.as_local();
130                                     let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did);
131                                     if impling_types.contains(&self_id);
132                                     then {
133                                         return;
134                                     }
135                                 }
136
137                                 let generics_sugg = snippet(cx, generics.span, "");
138                                 let self_ty_fmt = self_ty.to_string();
139                                 let self_type_snip = snippet(cx, impl_self_ty.span, &self_ty_fmt);
140                                 span_lint_hir_and_then(
141                                     cx,
142                                     NEW_WITHOUT_DEFAULT,
143                                     id,
144                                     impl_item.span,
145                                     &format!(
146                                         "you should consider adding a `Default` implementation for `{}`",
147                                         self_type_snip
148                                     ),
149                                     |diag| {
150                                         diag.suggest_prepend_item(
151                                             cx,
152                                             item.span,
153                                             "try adding this",
154                                             &create_new_without_default_suggest_msg(&self_type_snip, &generics_sugg),
155                                             Applicability::MaybeIncorrect,
156                                         );
157                                     },
158                                 );
159                             }
160                         }
161                     }
162                 }
163             }
164         }
165     }
166 }
167
168 fn create_new_without_default_suggest_msg(self_type_snip: &str, generics_sugg: &str) -> String {
169     #[rustfmt::skip]
170     format!(
171 "impl{} Default for {} {{
172     fn default() -> Self {{
173         Self::new()
174     }}
175 }}", generics_sugg, self_type_snip)
176 }