]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/default.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / default.rs
1 use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_sugg};
2 use clippy_utils::source::snippet_with_macro_callsite;
3 use clippy_utils::ty::{has_drop, is_copy};
4 use clippy_utils::{any_parent_is_automatically_derived, contains_name, get_parent_expr, match_def_path, paths};
5 use if_chain::if_chain;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_errors::Applicability;
8 use rustc_hir::def::Res;
9 use rustc_hir::{Block, Expr, ExprKind, PatKind, QPath, Stmt, StmtKind};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty;
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::symbol::{Ident, Symbol};
14 use rustc_span::Span;
15
16 declare_clippy_lint! {
17 /// ### What it does
18 /// Checks for literal calls to `Default::default()`.
19 ///
20 /// ### Why is this bad?
21 /// It's more clear to the reader to use the name of the type whose default is
22 /// being gotten than the generic `Default`.
23 ///
24 /// ### Example
25 /// ```rust
26 /// // Bad
27 /// let s: String = Default::default();
28 ///
29 /// // Good
30 /// let s = String::default();
31 /// ```
32 #[clippy::version = "pre 1.29.0"]
33 pub DEFAULT_TRAIT_ACCESS,
34 pedantic,
35 "checks for literal calls to `Default::default()`"
36 }
37
38 declare_clippy_lint! {
39 /// ### What it does
40 /// Checks for immediate reassignment of fields initialized
41 /// with Default::default().
42 ///
43 /// ### Why is this bad?
44 ///It's more idiomatic to use the [functional update syntax](https://doc.rust-lang.org/reference/expressions/struct-expr.html#functional-update-syntax).
45 ///
46 /// ### Known problems
47 /// Assignments to patterns that are of tuple type are not linted.
48 ///
49 /// ### Example
50 /// Bad:
51 /// ```
52 /// # #[derive(Default)]
53 /// # struct A { i: i32 }
54 /// let mut a: A = Default::default();
55 /// a.i = 42;
56 /// ```
57 /// Use instead:
58 /// ```
59 /// # #[derive(Default)]
60 /// # struct A { i: i32 }
61 /// let a = A {
62 /// i: 42,
63 /// .. Default::default()
64 /// };
65 /// ```
66 #[clippy::version = "1.49.0"]
67 pub FIELD_REASSIGN_WITH_DEFAULT,
68 style,
69 "binding initialized with Default should have its fields set in the initializer"
70 }
71
72 #[derive(Default)]
73 pub struct Default {
74 // Spans linted by `field_reassign_with_default`.
75 reassigned_linted: FxHashSet<Span>,
76 }
77
78 impl_lint_pass!(Default => [DEFAULT_TRAIT_ACCESS, FIELD_REASSIGN_WITH_DEFAULT]);
79
80 impl<'tcx> LateLintPass<'tcx> for Default {
81 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
82 if_chain! {
83 if !expr.span.from_expansion();
84 // Avoid cases already linted by `field_reassign_with_default`
85 if !self.reassigned_linted.contains(&expr.span);
86 if let ExprKind::Call(path, ..) = expr.kind;
87 if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id);
88 if let ExprKind::Path(ref qpath) = path.kind;
89 if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id();
90 if match_def_path(cx, def_id, &paths::DEFAULT_TRAIT_METHOD);
91 if !is_update_syntax_base(cx, expr);
92 // Detect and ignore <Foo as Default>::default() because these calls do explicitly name the type.
93 if let QPath::Resolved(None, _path) = qpath;
94 let expr_ty = cx.typeck_results().expr_ty(expr);
95 if let ty::Adt(def, ..) = expr_ty.kind();
96 then {
97 // TODO: Work out a way to put "whatever the imported way of referencing
98 // this type in this file" rather than a fully-qualified type.
99 let replacement = format!("{}::default()", cx.tcx.def_path_str(def.did()));
100 span_lint_and_sugg(
101 cx,
102 DEFAULT_TRAIT_ACCESS,
103 expr.span,
104 &format!("calling `{}` is more clear than this expression", replacement),
105 "try",
106 replacement,
107 Applicability::Unspecified, // First resolve the TODO above
108 );
109 }
110 }
111 }
112
113 #[allow(clippy::too_many_lines)]
114 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &Block<'tcx>) {
115 // start from the `let mut _ = _::default();` and look at all the following
116 // statements, see if they re-assign the fields of the binding
117 let stmts_head = match block.stmts {
118 // Skip the last statement since there cannot possibly be any following statements that re-assign fields.
119 [head @ .., _] if !head.is_empty() => head,
120 _ => return,
121 };
122 for (stmt_idx, stmt) in stmts_head.iter().enumerate() {
123 // find all binding statements like `let mut _ = T::default()` where `T::default()` is the
124 // `default` method of the `Default` trait, and store statement index in current block being
125 // checked and the name of the bound variable
126 let (local, variant, binding_name, binding_type, span) = if_chain! {
127 // only take `let ...` statements
128 if let StmtKind::Local(local) = stmt.kind;
129 if let Some(expr) = local.init;
130 if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id);
131 if !expr.span.from_expansion();
132 // only take bindings to identifiers
133 if let PatKind::Binding(_, binding_id, ident, _) = local.pat.kind;
134 // only when assigning `... = Default::default()`
135 if is_expr_default(expr, cx);
136 let binding_type = cx.typeck_results().node_type(binding_id);
137 if let Some(adt) = binding_type.ty_adt_def();
138 if adt.is_struct();
139 let variant = adt.non_enum_variant();
140 if adt.did().is_local() || !variant.is_field_list_non_exhaustive();
141 let module_did = cx.tcx.parent_module(stmt.hir_id).to_def_id();
142 if variant
143 .fields
144 .iter()
145 .all(|field| field.vis.is_accessible_from(module_did, cx.tcx));
146 let all_fields_are_copy = variant
147 .fields
148 .iter()
149 .all(|field| {
150 is_copy(cx, cx.tcx.type_of(field.did))
151 });
152 if !has_drop(cx, binding_type) || all_fields_are_copy;
153 then {
154 (local, variant, ident.name, binding_type, expr.span)
155 } else {
156 continue;
157 }
158 };
159
160 // find all "later statement"'s where the fields of the binding set as
161 // Default::default() get reassigned, unless the reassignment refers to the original binding
162 let mut first_assign = None;
163 let mut assigned_fields = Vec::new();
164 let mut cancel_lint = false;
165 for consecutive_statement in &block.stmts[stmt_idx + 1..] {
166 // find out if and which field was set by this `consecutive_statement`
167 if let Some((field_ident, assign_rhs)) = field_reassigned_by_stmt(consecutive_statement, binding_name) {
168 // interrupt and cancel lint if assign_rhs references the original binding
169 if contains_name(binding_name, assign_rhs) {
170 cancel_lint = true;
171 break;
172 }
173
174 // if the field was previously assigned, replace the assignment, otherwise insert the assignment
175 if let Some(prev) = assigned_fields
176 .iter_mut()
177 .find(|(field_name, _)| field_name == &field_ident.name)
178 {
179 *prev = (field_ident.name, assign_rhs);
180 } else {
181 assigned_fields.push((field_ident.name, assign_rhs));
182 }
183
184 // also set first instance of error for help message
185 if first_assign.is_none() {
186 first_assign = Some(consecutive_statement);
187 }
188 }
189 // interrupt if no field was assigned, since we only want to look at consecutive statements
190 else {
191 break;
192 }
193 }
194
195 // if there are incorrectly assigned fields, do a span_lint_and_note to suggest
196 // construction using `Ty { fields, ..Default::default() }`
197 if !assigned_fields.is_empty() && !cancel_lint {
198 // if all fields of the struct are not assigned, add `.. Default::default()` to the suggestion.
199 let ext_with_default = !variant
200 .fields
201 .iter()
202 .all(|field| assigned_fields.iter().any(|(a, _)| a == &field.name));
203
204 let field_list = assigned_fields
205 .into_iter()
206 .map(|(field, rhs)| {
207 // extract and store the assigned value for help message
208 let value_snippet = snippet_with_macro_callsite(cx, rhs.span, "..");
209 format!("{}: {}", field, value_snippet)
210 })
211 .collect::<Vec<String>>()
212 .join(", ");
213
214 // give correct suggestion if generics are involved (see #6944)
215 let binding_type = if_chain! {
216 if let ty::Adt(adt_def, substs) = binding_type.kind();
217 if !substs.is_empty();
218 then {
219 let adt_def_ty_name = cx.tcx.item_name(adt_def.did());
220 let generic_args = substs.iter().collect::<Vec<_>>();
221 let tys_str = generic_args
222 .iter()
223 .map(ToString::to_string)
224 .collect::<Vec<_>>()
225 .join(", ");
226 format!("{}::<{}>", adt_def_ty_name, &tys_str)
227 } else {
228 binding_type.to_string()
229 }
230 };
231
232 let sugg = if ext_with_default {
233 if field_list.is_empty() {
234 format!("{}::default()", binding_type)
235 } else {
236 format!("{} {{ {}, ..Default::default() }}", binding_type, field_list)
237 }
238 } else {
239 format!("{} {{ {} }}", binding_type, field_list)
240 };
241
242 // span lint once per statement that binds default
243 span_lint_and_note(
244 cx,
245 FIELD_REASSIGN_WITH_DEFAULT,
246 first_assign.unwrap().span,
247 "field assignment outside of initializer for an instance created with Default::default()",
248 Some(local.span),
249 &format!(
250 "consider initializing the variable with `{}` and removing relevant reassignments",
251 sugg
252 ),
253 );
254 self.reassigned_linted.insert(span);
255 }
256 }
257 }
258 }
259
260 /// Checks if the given expression is the `default` method belonging to the `Default` trait.
261 fn is_expr_default<'tcx>(expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> bool {
262 if_chain! {
263 if let ExprKind::Call(fn_expr, _) = &expr.kind;
264 if let ExprKind::Path(qpath) = &fn_expr.kind;
265 if let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id);
266 then {
267 // right hand side of assignment is `Default::default`
268 match_def_path(cx, def_id, &paths::DEFAULT_TRAIT_METHOD)
269 } else {
270 false
271 }
272 }
273 }
274
275 /// Returns the reassigned field and the assigning expression (right-hand side of assign).
276 fn field_reassigned_by_stmt<'tcx>(this: &Stmt<'tcx>, binding_name: Symbol) -> Option<(Ident, &'tcx Expr<'tcx>)> {
277 if_chain! {
278 // only take assignments
279 if let StmtKind::Semi(later_expr) = this.kind;
280 if let ExprKind::Assign(assign_lhs, assign_rhs, _) = later_expr.kind;
281 // only take assignments to fields where the left-hand side field is a field of
282 // the same binding as the previous statement
283 if let ExprKind::Field(binding, field_ident) = assign_lhs.kind;
284 if let ExprKind::Path(QPath::Resolved(_, path)) = binding.kind;
285 if let Some(second_binding_name) = path.segments.last();
286 if second_binding_name.ident.name == binding_name;
287 then {
288 Some((field_ident, assign_rhs))
289 } else {
290 None
291 }
292 }
293 }
294
295 /// Returns whether `expr` is the update syntax base: `Foo { a: 1, .. base }`
296 fn is_update_syntax_base<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
297 if_chain! {
298 if let Some(parent) = get_parent_expr(cx, expr);
299 if let ExprKind::Struct(_, _, Some(base)) = parent.kind;
300 then {
301 base.hir_id == expr.hir_id
302 } else {
303 false
304 }
305 }
306 }