1
- use crate :: utils:: { eq_expr_value, in_macro, search_same, SpanlessEq , SpanlessHash } ;
2
- use crate :: utils:: { get_parent_expr, higher, if_sequence, span_lint_and_note} ;
3
- use rustc_hir:: { Block , Expr } ;
1
+ use crate :: utils:: { both, count_eq, eq_expr_value, in_macro, search_same, SpanlessEq , SpanlessHash } ;
2
+ use crate :: utils:: {
3
+ first_line_of_span, get_parent_expr, higher, if_sequence, indent_of, reindent_multiline, snippet,
4
+ span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
5
+ } ;
6
+ use rustc_data_structures:: fx:: FxHashSet ;
7
+ use rustc_errors:: Applicability ;
8
+ use rustc_hir:: intravisit:: { self , NestedVisitorMap , Visitor } ;
9
+ use rustc_hir:: { Block , Expr , HirId } ;
4
10
use rustc_lint:: { LateContext , LateLintPass } ;
11
+ use rustc_middle:: hir:: map:: Map ;
5
12
use rustc_session:: { declare_lint_pass, declare_tool_lint} ;
13
+ use rustc_span:: source_map:: Span ;
14
+ use std:: borrow:: Cow ;
6
15
7
16
declare_clippy_lint ! {
8
17
/// **What it does:** Checks for consecutive `if`s with the same condition.
@@ -103,7 +112,45 @@ declare_clippy_lint! {
103
112
"`if` with the same `then` and `else` blocks"
104
113
}
105
114
106
- declare_lint_pass ! ( CopyAndPaste => [ IFS_SAME_COND , SAME_FUNCTIONS_IN_IF_CONDITION , IF_SAME_THEN_ELSE ] ) ;
115
+ declare_clippy_lint ! {
116
+ /// **What it does:** Checks if the `if` and `else` block contain shared code that can be
117
+ /// moved out of the blocks.
118
+ ///
119
+ /// **Why is this bad?** Duplicate code is less maintainable.
120
+ ///
121
+ /// **Known problems:** Hopefully none.
122
+ ///
123
+ /// **Example:**
124
+ /// ```ignore
125
+ /// let foo = if … {
126
+ /// println!("Hello World");
127
+ /// 13
128
+ /// } else {
129
+ /// println!("Hello World");
130
+ /// 42
131
+ /// };
132
+ /// ```
133
+ ///
134
+ /// Could be written as:
135
+ /// ```ignore
136
+ /// println!("Hello World");
137
+ /// let foo = if … {
138
+ /// 13
139
+ /// } else {
140
+ /// 42
141
+ /// };
142
+ /// ```
143
+ pub SHARED_CODE_IN_IF_BLOCKS ,
144
+ pedantic,
145
+ "`if` statement with shared code in all blocks"
146
+ }
147
+
148
+ declare_lint_pass ! ( CopyAndPaste => [
149
+ IFS_SAME_COND ,
150
+ SAME_FUNCTIONS_IN_IF_CONDITION ,
151
+ IF_SAME_THEN_ELSE ,
152
+ SHARED_CODE_IN_IF_BLOCKS
153
+ ] ) ;
107
154
108
155
impl < ' tcx > LateLintPass < ' tcx > for CopyAndPaste {
109
156
fn check_expr ( & mut self , cx : & LateContext < ' tcx > , expr : & ' tcx Expr < ' _ > ) {
@@ -118,30 +165,256 @@ impl<'tcx> LateLintPass<'tcx> for CopyAndPaste {
118
165
}
119
166
120
167
let ( conds, blocks) = if_sequence ( expr) ;
121
- lint_same_then_else ( cx , & blocks ) ;
168
+ // Conditions
122
169
lint_same_cond ( cx, & conds) ;
123
170
lint_same_fns_in_if_cond ( cx, & conds) ;
171
+ // Block duplication
172
+ lint_same_then_else ( cx, & blocks, conds. len ( ) != blocks. len ( ) , expr) ;
124
173
}
125
174
}
126
175
}
127
176
128
- /// Implementation of `IF_SAME_THEN_ELSE`.
129
- fn lint_same_then_else ( cx : & LateContext < ' _ > , blocks : & [ & Block < ' _ > ] ) {
130
- let eq: & dyn Fn ( & & Block < ' _ > , & & Block < ' _ > ) -> bool =
131
- & |& lhs, & rhs| -> bool { SpanlessEq :: new ( cx) . eq_block ( lhs, rhs) } ;
177
+ /// Implementation of `SHARED_CODE_IN_IF_BLOCKS` and `IF_SAME_THEN_ELSE` if the blocks are equal.
178
+ fn lint_same_then_else < ' tcx > (
179
+ cx : & LateContext < ' tcx > ,
180
+ blocks : & [ & Block < ' tcx > ] ,
181
+ has_unconditional_else : bool ,
182
+ expr : & ' tcx Expr < ' _ > ,
183
+ ) {
184
+ // We only lint ifs with multiple blocks
185
+ // TODO xFrednet 2021-01-01: Check if it's an else if block
186
+ if blocks. len ( ) < 2 {
187
+ return ;
188
+ }
132
189
133
- if let Some ( ( i, j) ) = search_same_sequenced ( blocks, eq) {
134
- span_lint_and_note (
190
+ let has_expr = blocks[ 0 ] . expr . is_some ( ) ;
191
+
192
+ // Check if each block has shared code
193
+ let mut start_eq = usize:: MAX ;
194
+ let mut end_eq = usize:: MAX ;
195
+ let mut expr_eq = true ;
196
+ for ( index, win) in blocks. windows ( 2 ) . enumerate ( ) {
197
+ let l_stmts = win[ 0 ] . stmts ;
198
+ let r_stmts = win[ 1 ] . stmts ;
199
+
200
+ let mut evaluator = SpanlessEq :: new ( cx) ;
201
+ let current_start_eq = count_eq ( & mut l_stmts. iter ( ) , & mut r_stmts. iter ( ) , |l, r| evaluator. eq_stmt ( l, r) ) ;
202
+ let current_end_eq = count_eq ( & mut l_stmts. iter ( ) . rev ( ) , & mut r_stmts. iter ( ) . rev ( ) , |l, r| {
203
+ evaluator. eq_stmt ( l, r)
204
+ } ) ;
205
+ let block_expr_eq = both ( & win[ 0 ] . expr , & win[ 1 ] . expr , |l, r| evaluator. eq_expr ( l, r) ) ;
206
+
207
+ // IF_SAME_THEN_ELSE
208
+ // We only lint the first two blocks (index == 0). Further blocks will be linted when that if
209
+ // statement is checked
210
+ if index == 0 && block_expr_eq && l_stmts. len ( ) == r_stmts. len ( ) && l_stmts. len ( ) == current_start_eq {
211
+ span_lint_and_note (
212
+ cx,
213
+ IF_SAME_THEN_ELSE ,
214
+ win[ 0 ] . span ,
215
+ "this `if` has identical blocks" ,
216
+ Some ( win[ 1 ] . span ) ,
217
+ "same as this" ,
218
+ ) ;
219
+
220
+ return ;
221
+ }
222
+
223
+ start_eq = start_eq. min ( current_start_eq) ;
224
+ end_eq = end_eq. min ( current_end_eq) ;
225
+ expr_eq &= block_expr_eq;
226
+
227
+ // We can return if the eq count is 0 from both sides or if it has no unconditional else case
228
+ if !has_unconditional_else || ( start_eq == 0 && end_eq == 0 && ( has_expr && !expr_eq) ) {
229
+ return ;
230
+ }
231
+ }
232
+
233
+ if has_expr && !expr_eq {
234
+ end_eq = 0 ;
235
+ }
236
+
237
+ // Check if the regions are overlapping. Set `end_eq` to prevent the overlap
238
+ let min_block_size = blocks. iter ( ) . map ( |x| x. stmts . len ( ) ) . min ( ) . unwrap ( ) ;
239
+ if ( start_eq + end_eq) > min_block_size {
240
+ end_eq = min_block_size - start_eq;
241
+ }
242
+
243
+ // Only the start is the same
244
+ if start_eq != 0 && end_eq == 0 && ( !has_expr || !expr_eq) {
245
+ emit_shared_code_in_if_blocks_lint ( cx, start_eq, 0 , false , blocks, expr) ;
246
+ } else if end_eq != 0 && ( !has_expr || !expr_eq) {
247
+ let block = blocks[ blocks. len ( ) - 1 ] ;
248
+ let stmts = block. stmts . split_at ( start_eq) . 1 ;
249
+ let ( block_stmts, moved_stmts) = stmts. split_at ( stmts. len ( ) - end_eq) ;
250
+
251
+ // Scan block
252
+ let mut walker = SymbolFinderVisitor :: new ( cx) ;
253
+ for stmt in block_stmts {
254
+ intravisit:: walk_stmt ( & mut walker, stmt) ;
255
+ }
256
+ let mut block_defs = walker. defs ;
257
+
258
+ // Scan moved stmts
259
+ let mut moved_start: Option < usize > = None ;
260
+ let mut walker = SymbolFinderVisitor :: new ( cx) ;
261
+ for ( index, stmt) in moved_stmts. iter ( ) . enumerate ( ) {
262
+ intravisit:: walk_stmt ( & mut walker, stmt) ;
263
+
264
+ for value in & walker. uses {
265
+ // Well we can't move this and all prev statements. So reset
266
+ if block_defs. contains ( & value) {
267
+ moved_start = Some ( index + 1 ) ;
268
+ walker. defs . drain ( ) . for_each ( |x| {
269
+ block_defs. insert ( x) ;
270
+ } ) ;
271
+ }
272
+ }
273
+
274
+ walker. uses . clear ( ) ;
275
+ }
276
+
277
+ if let Some ( moved_start) = moved_start {
278
+ end_eq -= moved_start;
279
+ }
280
+
281
+ let mut end_linable = true ;
282
+ if let Some ( expr) = block. expr {
283
+ intravisit:: walk_expr ( & mut walker, expr) ;
284
+ end_linable = walker. uses . iter ( ) . any ( |x| !block_defs. contains ( x) ) ;
285
+ }
286
+
287
+ emit_shared_code_in_if_blocks_lint ( cx, start_eq, end_eq, end_linable, blocks, expr) ;
288
+ }
289
+ }
290
+
291
+ fn emit_shared_code_in_if_blocks_lint (
292
+ cx : & LateContext < ' tcx > ,
293
+ start_stmts : usize ,
294
+ end_stmts : usize ,
295
+ lint_end : bool ,
296
+ blocks : & [ & Block < ' tcx > ] ,
297
+ if_expr : & ' tcx Expr < ' _ > ,
298
+ ) {
299
+ if start_stmts == 0 && !lint_end {
300
+ return ;
301
+ }
302
+
303
+ // (help, span, suggestion)
304
+ let mut suggestions: Vec < ( & str , Span , String ) > = vec ! [ ] ;
305
+
306
+ if start_stmts > 0 {
307
+ let block = blocks[ 0 ] ;
308
+ let span_start = first_line_of_span ( cx, if_expr. span ) . shrink_to_lo ( ) ;
309
+ let span_end = block. stmts [ start_stmts - 1 ] . span . source_callsite ( ) ;
310
+
311
+ let cond_span = first_line_of_span ( cx, if_expr. span ) . until ( block. span ) ;
312
+ let cond_snippet = reindent_multiline ( snippet ( cx, cond_span, "_" ) , false , None ) ;
313
+ let cond_indent = indent_of ( cx, cond_span) ;
314
+ let moved_span = block. stmts [ 0 ] . span . source_callsite ( ) . to ( span_end) ;
315
+ let moved_snippet = reindent_multiline ( snippet ( cx, moved_span, "_" ) , true , None ) ;
316
+ let suggestion = moved_snippet. to_string ( ) + "\n " + & cond_snippet + "{" ;
317
+ let suggestion = reindent_multiline ( Cow :: Borrowed ( & suggestion) , true , cond_indent) ;
318
+
319
+ let span = span_start. to ( span_end) ;
320
+ suggestions. push ( ( "START HELP" , span, suggestion. to_string ( ) ) ) ;
321
+ }
322
+
323
+ if lint_end {
324
+ let block = blocks[ blocks. len ( ) - 1 ] ;
325
+ let span_end = block. span . shrink_to_hi ( ) ;
326
+
327
+ let moved_start = if end_stmts == 0 && block. expr . is_some ( ) {
328
+ block. expr . unwrap ( ) . span
329
+ } else {
330
+ block. stmts [ block. stmts . len ( ) - end_stmts] . span
331
+ }
332
+ . source_callsite ( ) ;
333
+ let moved_end = if let Some ( expr) = block. expr {
334
+ expr. span
335
+ } else {
336
+ block. stmts [ block. stmts . len ( ) - 1 ] . span
337
+ }
338
+ . source_callsite ( ) ;
339
+
340
+ let moved_span = moved_start. to ( moved_end) ;
341
+ let moved_snipped = reindent_multiline ( snippet ( cx, moved_span, "_" ) , true , None ) ;
342
+ let indent = indent_of ( cx, if_expr. span . shrink_to_hi ( ) ) ;
343
+ let suggestion = "}\n " . to_string ( ) + & moved_snipped;
344
+ let suggestion = reindent_multiline ( Cow :: Borrowed ( & suggestion) , true , indent) ;
345
+
346
+ let span = moved_start. to ( span_end) ;
347
+ suggestions. push ( ( "END_RANGE" , span, suggestion. to_string ( ) ) ) ;
348
+ }
349
+
350
+ if suggestions. len ( ) == 1 {
351
+ let ( _, span, sugg) = & suggestions[ 0 ] ;
352
+ span_lint_and_sugg (
135
353
cx,
136
- IF_SAME_THEN_ELSE ,
137
- j. span ,
138
- "this `if` has identical blocks" ,
139
- Some ( i. span ) ,
140
- "same as this" ,
354
+ SHARED_CODE_IN_IF_BLOCKS ,
355
+ * span,
356
+ "All code blocks contain the same code" ,
357
+ "Consider moving the code out like this" ,
358
+ sugg. clone ( ) ,
359
+ Applicability :: Unspecified ,
360
+ ) ;
361
+ } else {
362
+ span_lint_and_then (
363
+ cx,
364
+ SHARED_CODE_IN_IF_BLOCKS ,
365
+ if_expr. span ,
366
+ "All if blocks contain the same code" ,
367
+ move |diag| {
368
+ for ( help, span, sugg) in suggestions {
369
+ diag. span_suggestion ( span, help, sugg, Applicability :: Unspecified ) ;
370
+ }
371
+ } ,
141
372
) ;
142
373
}
143
374
}
144
375
376
+ pub struct SymbolFinderVisitor < ' a , ' tcx > {
377
+ cx : & ' a LateContext < ' tcx > ,
378
+ defs : FxHashSet < HirId > ,
379
+ uses : FxHashSet < HirId > ,
380
+ }
381
+
382
+ impl < ' a , ' tcx > SymbolFinderVisitor < ' a , ' tcx > {
383
+ fn new ( cx : & ' a LateContext < ' tcx > ) -> Self {
384
+ SymbolFinderVisitor {
385
+ cx,
386
+ defs : FxHashSet :: default ( ) ,
387
+ uses : FxHashSet :: default ( ) ,
388
+ }
389
+ }
390
+ }
391
+
392
+ impl < ' a , ' tcx > Visitor < ' tcx > for SymbolFinderVisitor < ' a , ' tcx > {
393
+ type Map = Map < ' tcx > ;
394
+
395
+ fn nested_visit_map ( & mut self ) -> NestedVisitorMap < Self :: Map > {
396
+ NestedVisitorMap :: All ( self . cx . tcx . hir ( ) )
397
+ }
398
+
399
+ fn visit_local ( & mut self , l : & ' tcx rustc_hir:: Local < ' tcx > ) {
400
+ let local_id = l. pat . hir_id ;
401
+ self . defs . insert ( local_id) ;
402
+ if let Some ( expr) = l. init {
403
+ intravisit:: walk_expr ( self , expr) ;
404
+ }
405
+ }
406
+
407
+ fn visit_qpath ( & mut self , qpath : & ' tcx rustc_hir:: QPath < ' tcx > , id : HirId , _span : rustc_span:: Span ) {
408
+ if let rustc_hir:: QPath :: Resolved ( _, ref path) = * qpath {
409
+ if path. segments . len ( ) == 1 {
410
+ if let rustc_hir:: def:: Res :: Local ( var) = self . cx . qpath_res ( qpath, id) {
411
+ self . uses . insert ( var) ;
412
+ }
413
+ }
414
+ }
415
+ }
416
+ }
417
+
145
418
/// Implementation of `IFS_SAME_COND`.
146
419
fn lint_same_cond ( cx : & LateContext < ' _ > , conds : & [ & Expr < ' _ > ] ) {
147
420
let hash: & dyn Fn ( & & Expr < ' _ > ) -> u64 = & |expr| -> u64 {
@@ -195,15 +468,3 @@ fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
195
468
) ;
196
469
}
197
470
}
198
-
199
- fn search_same_sequenced < T , Eq > ( exprs : & [ T ] , eq : Eq ) -> Option < ( & T , & T ) >
200
- where
201
- Eq : Fn ( & T , & T ) -> bool ,
202
- {
203
- for win in exprs. windows ( 2 ) {
204
- if eq ( & win[ 0 ] , & win[ 1 ] ) {
205
- return Some ( ( & win[ 0 ] , & win[ 1 ] ) ) ;
206
- }
207
- }
208
- None
209
- }
0 commit comments