rustc_lint/default_could_be_derived.rs
1use rustc_data_structures::fx::FxHashMap;
2use rustc_errors::{Applicability, Diag};
3use rustc_hir as hir;
4use rustc_hir::attrs::AttributeKind;
5use rustc_hir::find_attr;
6use rustc_middle::ty;
7use rustc_middle::ty::TyCtxt;
8use rustc_session::{declare_lint, impl_lint_pass};
9use rustc_span::Symbol;
10use rustc_span::def_id::DefId;
11use rustc_span::symbol::sym;
12
13use crate::{LateContext, LateLintPass};
14
15declare_lint! {
16 /// The `default_overrides_default_fields` lint checks for manual `impl` blocks of the
17 /// `Default` trait of types with default field values.
18 ///
19 /// ### Example
20 ///
21 /// ```rust,compile_fail
22 /// #![feature(default_field_values)]
23 /// struct Foo {
24 /// x: i32 = 101,
25 /// y: NonDefault,
26 /// }
27 ///
28 /// struct NonDefault;
29 ///
30 /// #[deny(default_overrides_default_fields)]
31 /// impl Default for Foo {
32 /// fn default() -> Foo {
33 /// Foo { x: 100, y: NonDefault }
34 /// }
35 /// }
36 /// ```
37 ///
38 /// {{produces}}
39 ///
40 /// ### Explanation
41 ///
42 /// Manually writing a `Default` implementation for a type that has
43 /// default field values runs the risk of diverging behavior between
44 /// `Type { .. }` and `<Type as Default>::default()`, which would be a
45 /// foot-gun for users of that type that would expect these to be
46 /// equivalent. If `Default` can't be derived due to some fields not
47 /// having a `Default` implementation, we encourage the use of `..` for
48 /// the fields that do have a default field value.
49 pub DEFAULT_OVERRIDES_DEFAULT_FIELDS,
50 Deny,
51 "detect `Default` impl that should use the type's default field values",
52 @feature_gate = default_field_values;
53}
54
55#[derive(Default)]
56pub(crate) struct DefaultCouldBeDerived;
57
58impl_lint_pass!(DefaultCouldBeDerived => [DEFAULT_OVERRIDES_DEFAULT_FIELDS]);
59
60impl<'tcx> LateLintPass<'tcx> for DefaultCouldBeDerived {
61 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
62 // Look for manual implementations of `Default`.
63 let Some(default_def_id) = cx.tcx.get_diagnostic_item(sym::Default) else { return };
64 let hir::ImplItemKind::Fn(_sig, body_id) = impl_item.kind else { return };
65 let assoc = cx.tcx.associated_item(impl_item.owner_id);
66 let parent = assoc.container_id(cx.tcx);
67 if find_attr!(cx.tcx.get_all_attrs(parent), AttributeKind::AutomaticallyDerived(..)) {
68 // We don't care about what `#[derive(Default)]` produces in this lint.
69 return;
70 }
71 let Some(trait_ref) = cx.tcx.impl_trait_ref(parent) else { return };
72 let trait_ref = trait_ref.instantiate_identity();
73 if trait_ref.def_id != default_def_id {
74 return;
75 }
76 let ty = trait_ref.self_ty();
77 let ty::Adt(def, _) = ty.kind() else { return };
78
79 // We now know we have a manually written definition of a `<Type as Default>::default()`.
80
81 let type_def_id = def.did();
82 let body = cx.tcx.hir_body(body_id);
83
84 // FIXME: evaluate bodies with statements and evaluate bindings to see if they would be
85 // derivable.
86 let hir::ExprKind::Block(hir::Block { stmts: _, expr: Some(expr), .. }, None) =
87 body.value.kind
88 else {
89 return;
90 };
91
92 // Keep a mapping of field name to `hir::FieldDef` for every field in the type. We'll use
93 // these to check for things like checking whether it has a default or using its span for
94 // suggestions.
95 let orig_fields = match cx.tcx.hir_get_if_local(type_def_id) {
96 Some(hir::Node::Item(hir::Item {
97 kind:
98 hir::ItemKind::Struct(
99 _,
100 _generics,
101 hir::VariantData::Struct { fields, recovered: _ },
102 ),
103 ..
104 })) => fields.iter().map(|f| (f.ident.name, f)).collect::<FxHashMap<_, _>>(),
105 _ => return,
106 };
107
108 // We check `fn default()` body is a single ADT literal and get all the fields that are
109 // being set.
110 let hir::ExprKind::Struct(_qpath, fields, tail) = expr.kind else { return };
111
112 // We have a struct literal
113 //
114 // struct Foo {
115 // field: Type,
116 // }
117 //
118 // impl Default for Foo {
119 // fn default() -> Foo {
120 // Foo {
121 // field: val,
122 // }
123 // }
124 // }
125 //
126 // We would suggest `#[derive(Default)]` if `field` has a default value, regardless of what
127 // it is; we don't want to encourage divergent behavior between `Default::default()` and
128 // `..`.
129
130 if let hir::StructTailExpr::Base(_) = tail {
131 // This is *very* niche. We'd only get here if someone wrote
132 // impl Default for Ty {
133 // fn default() -> Ty {
134 // Ty { ..something() }
135 // }
136 // }
137 // where `something()` would have to be a call or path.
138 // We have nothing meaningful to do with this.
139 return;
140 }
141
142 // At least one of the fields with a default value have been overridden in
143 // the `Default` implementation. We suggest removing it and relying on `..`
144 // instead.
145 let any_default_field_given =
146 fields.iter().any(|f| orig_fields.get(&f.ident.name).and_then(|f| f.default).is_some());
147
148 if !any_default_field_given {
149 // None of the default fields were actually provided explicitly, so the manual impl
150 // doesn't override them (the user used `..`), so there's no risk of divergent behavior.
151 return;
152 }
153
154 let Some(local) = parent.as_local() else { return };
155 let hir_id = cx.tcx.local_def_id_to_hir_id(local);
156 let hir::Node::Item(item) = cx.tcx.hir_node(hir_id) else { return };
157 cx.tcx.node_span_lint(DEFAULT_OVERRIDES_DEFAULT_FIELDS, hir_id, item.span, |diag| {
158 mk_lint(cx.tcx, diag, type_def_id, parent, orig_fields, fields);
159 });
160 }
161}
162
163fn mk_lint(
164 tcx: TyCtxt<'_>,
165 diag: &mut Diag<'_, ()>,
166 type_def_id: DefId,
167 impl_def_id: DefId,
168 orig_fields: FxHashMap<Symbol, &hir::FieldDef<'_>>,
169 fields: &[hir::ExprField<'_>],
170) {
171 diag.primary_message("`Default` impl doesn't use the declared default field values");
172
173 // For each field in the struct expression
174 // - if the field in the type has a default value, it should be removed
175 // - elif the field is an expression that could be a default value, it should be used as the
176 // field's default value (FIXME: not done).
177 // - else, we wouldn't touch this field, it would remain in the manual impl
178 let mut removed_all_fields = true;
179 for field in fields {
180 if orig_fields.get(&field.ident.name).and_then(|f| f.default).is_some() {
181 diag.span_label(field.expr.span, "this field has a default value");
182 } else {
183 removed_all_fields = false;
184 }
185 }
186
187 if removed_all_fields {
188 let msg = "to avoid divergence in behavior between `Struct { .. }` and \
189 `<Struct as Default>::default()`, derive the `Default`";
190 if let Some(hir::Node::Item(impl_)) = tcx.hir_get_if_local(impl_def_id) {
191 diag.multipart_suggestion_verbose(
192 msg,
193 vec![
194 (tcx.def_span(type_def_id).shrink_to_lo(), "#[derive(Default)] ".to_string()),
195 (impl_.span, String::new()),
196 ],
197 Applicability::MachineApplicable,
198 );
199 } else {
200 diag.help(msg);
201 }
202 } else {
203 let msg = "use the default values in the `impl` with `Struct { mandatory_field, .. }` to \
204 avoid them diverging over time";
205 diag.help(msg);
206 }
207}