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