@@ -131,34 +131,49 @@ fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Ex
131
131
if is_diag_trait_item( cx, method_def_id, sym:: ToString ) ;
132
132
let receiver_ty = cx. typeck_results( ) . expr_ty( receiver) ;
133
133
if let Some ( display_trait_id) = cx. tcx. get_diagnostic_item( sym:: Display ) ;
134
+ let ( n_needed_derefs, target) =
135
+ count_needed_derefs( receiver_ty, cx. typeck_results( ) . expr_adjustments( receiver) . iter( ) ) ;
136
+ if implements_trait( cx, target, display_trait_id, & [ ] ) ;
137
+ if let Some ( sized_trait_id) = cx. tcx. lang_items( ) . sized_trait( ) ;
134
138
if let Some ( receiver_snippet) = snippet_opt( cx, receiver. span) ;
135
139
then {
136
- let ( n_needed_derefs, target) = count_needed_derefs(
137
- receiver_ty,
138
- cx. typeck_results( ) . expr_adjustments( receiver) . iter( ) ,
139
- ) ;
140
- if implements_trait( cx, target, display_trait_id, & [ ] ) {
141
- if n_needed_derefs == 0 {
142
- span_lint_and_sugg(
143
- cx,
144
- TO_STRING_IN_FORMAT_ARGS ,
145
- value. span. with_lo( receiver. span. hi( ) ) ,
146
- & format!( "`to_string` applied to a type that implements `Display` in `{}!` args" , name) ,
147
- "remove this" ,
148
- String :: new( ) ,
149
- Applicability :: MachineApplicable ,
150
- ) ;
151
- } else {
152
- span_lint_and_sugg(
153
- cx,
154
- TO_STRING_IN_FORMAT_ARGS ,
155
- value. span,
156
- & format!( "`to_string` applied to a type that implements `Display` in `{}!` args" , name) ,
157
- "use this" ,
158
- format!( "{:*>width$}{}" , "" , receiver_snippet, width = n_needed_derefs) ,
159
- Applicability :: MachineApplicable ,
160
- ) ;
161
- }
140
+ let needed_ref = if implements_trait( cx, receiver_ty, sized_trait_id, & [ ] ) {
141
+ ""
142
+ } else {
143
+ "&"
144
+ } ;
145
+ if n_needed_derefs == 0 && needed_ref. is_empty( ) {
146
+ span_lint_and_sugg(
147
+ cx,
148
+ TO_STRING_IN_FORMAT_ARGS ,
149
+ value. span. with_lo( receiver. span. hi( ) ) ,
150
+ & format!(
151
+ "`to_string` applied to a type that implements `Display` in `{}!` args" ,
152
+ name
153
+ ) ,
154
+ "remove this" ,
155
+ String :: new( ) ,
156
+ Applicability :: MachineApplicable ,
157
+ ) ;
158
+ } else {
159
+ span_lint_and_sugg(
160
+ cx,
161
+ TO_STRING_IN_FORMAT_ARGS ,
162
+ value. span,
163
+ & format!(
164
+ "`to_string` applied to a type that implements `Display` in `{}!` args" ,
165
+ name
166
+ ) ,
167
+ "use this" ,
168
+ format!(
169
+ "{}{:*>width$}{}" ,
170
+ needed_ref,
171
+ "" ,
172
+ receiver_snippet,
173
+ width = n_needed_derefs
174
+ ) ,
175
+ Applicability :: MachineApplicable ,
176
+ ) ;
162
177
}
163
178
}
164
179
}
0 commit comments