-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
mod.rs
3922 lines (3670 loc) · 138 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod bind_instead_of_map;
mod inefficient_to_string;
mod manual_saturating_arithmetic;
mod option_map_unwrap_or;
mod unnecessary_filter_map;
mod unnecessary_lazy_eval;
use std::borrow::Cow;
use std::fmt;
use std::iter;
use bind_instead_of_map::BindInsteadOfMap;
use if_chain::if_chain;
use rustc_ast::ast;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{TraitItem, TraitItemKind};
use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
use rustc_middle::hir::map::Map;
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::{self, TraitRef, Ty, TyS};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::symbol::{sym, SymbolStr};
use crate::consts::{constant, Constant};
use crate::utils::eager_or_lazy::is_lazyness_candidate;
use crate::utils::usage::mutated_variables;
use crate::utils::{
contains_ty, get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait, in_macro,
is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment, match_def_path, match_qpath,
match_trait_method, match_type, match_var, method_calls, method_chain_args, paths, remove_blocks, return_ty,
single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite, span_lint,
span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg, walk_ptrs_ty_depth, SpanlessEq,
};
declare_clippy_lint! {
/// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
///
/// **Why is this bad?** It is better to handle the `None` or `Err` case,
/// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
/// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
/// `Allow` by default.
///
/// `result.unwrap()` will let the thread panic on `Err` values.
/// Normally, you want to implement more sophisticated error handling,
/// and propagate errors upwards with `?` operator.
///
/// Even if you want to panic on errors, not all `Error`s implement good
/// messages on display. Therefore, it may be beneficial to look at the places
/// where they may get displayed. Activate this lint to do just that.
///
/// **Known problems:** None.
///
/// **Examples:**
/// ```rust
/// # let opt = Some(1);
///
/// // Bad
/// opt.unwrap();
///
/// // Good
/// opt.expect("more helpful message");
/// ```
///
/// // or
///
/// ```rust
/// # let res: Result<usize, ()> = Ok(1);
///
/// // Bad
/// res.unwrap();
///
/// // Good
/// res.expect("more helpful message");
/// ```
pub UNWRAP_USED,
restriction,
"using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
}
declare_clippy_lint! {
/// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
///
/// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
/// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
/// this lint is `Allow` by default.
///
/// `result.expect()` will let the thread panic on `Err`
/// values. Normally, you want to implement more sophisticated error handling,
/// and propagate errors upwards with `?` operator.
///
/// **Known problems:** None.
///
/// **Examples:**
/// ```rust,ignore
/// # let opt = Some(1);
///
/// // Bad
/// opt.expect("one");
///
/// // Good
/// let opt = Some(1);
/// opt?;
/// ```
///
/// // or
///
/// ```rust
/// # let res: Result<usize, ()> = Ok(1);
///
/// // Bad
/// res.expect("one");
///
/// // Good
/// res?;
/// # Ok::<(), ()>(())
/// ```
pub EXPECT_USED,
restriction,
"using `.expect()` on `Result` or `Option`, which might be better handled"
}
declare_clippy_lint! {
/// **What it does:** Checks for methods that should live in a trait
/// implementation of a `std` trait (see [llogiq's blog
/// post](http://llogiq.github.io/2015/07/30/traits.html) for further
/// information) instead of an inherent implementation.
///
/// **Why is this bad?** Implementing the traits improve ergonomics for users of
/// the code, often with very little cost. Also people seeing a `mul(...)`
/// method
/// may expect `*` to work equally, so you should have good reason to disappoint
/// them.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// struct X;
/// impl X {
/// fn add(&self, other: &X) -> X {
/// // ..
/// # X
/// }
/// }
/// ```
pub SHOULD_IMPLEMENT_TRAIT,
style,
"defining a method that should be implementing a std trait"
}
declare_clippy_lint! {
/// **What it does:** Checks for methods with certain name prefixes and which
/// doesn't match how self is taken. The actual rules are:
///
/// |Prefix |`self` taken |
/// |-------|----------------------|
/// |`as_` |`&self` or `&mut self`|
/// |`from_`| none |
/// |`into_`|`self` |
/// |`is_` |`&self` or none |
/// |`to_` |`&self` |
///
/// **Why is this bad?** Consistency breeds readability. If you follow the
/// conventions, your users won't be surprised that they, e.g., need to supply a
/// mutable reference to a `as_..` function.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// # struct X;
/// impl X {
/// fn as_str(self) -> &'static str {
/// // ..
/// # ""
/// }
/// }
/// ```
pub WRONG_SELF_CONVENTION,
style,
"defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
}
declare_clippy_lint! {
/// **What it does:** This is the same as
/// [`wrong_self_convention`](#wrong_self_convention), but for public items.
///
/// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
///
/// **Known problems:** Actually *renaming* the function may break clients if
/// the function is part of the public interface. In that case, be mindful of
/// the stability guarantees you've given your users.
///
/// **Example:**
/// ```rust
/// # struct X;
/// impl<'a> X {
/// pub fn as_str(self) -> &'a str {
/// "foo"
/// }
/// }
/// ```
pub WRONG_PUB_SELF_CONVENTION,
restriction,
"defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `ok().expect(..)`.
///
/// **Why is this bad?** Because you usually call `expect()` on the `Result`
/// directly to get a better error message.
///
/// **Known problems:** The error type needs to implement `Debug`
///
/// **Example:**
/// ```rust
/// # let x = Ok::<_, ()>(());
///
/// // Bad
/// x.ok().expect("why did I do this again?");
///
/// // Good
/// x.expect("why did I do this again?");
/// ```
pub OK_EXPECT,
style,
"using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
/// `result.map(_).unwrap_or_else(_)`.
///
/// **Why is this bad?** Readability, these can be written more concisely (resp.) as
/// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
///
/// **Known problems:** The order of the arguments is not in execution order
///
/// **Examples:**
/// ```rust
/// # let x = Some(1);
///
/// // Bad
/// x.map(|a| a + 1).unwrap_or(0);
///
/// // Good
/// x.map_or(0, |a| a + 1);
/// ```
///
/// // or
///
/// ```rust
/// # let x: Result<usize, ()> = Ok(1);
/// # fn some_function(foo: ()) -> usize { 1 }
///
/// // Bad
/// x.map(|a| a + 1).unwrap_or_else(some_function);
///
/// // Good
/// x.map_or_else(some_function, |a| a + 1);
/// ```
pub MAP_UNWRAP_OR,
pedantic,
"using `.map(f).unwrap_or(a)` or `.map(f).unwrap_or_else(func)`, which are more succinctly expressed as `map_or(a, f)` or `map_or_else(a, f)`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.map_or(None, _)`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.and_then(_)`.
///
/// **Known problems:** The order of the arguments is not in execution order.
///
/// **Example:**
/// ```rust
/// # let opt = Some(1);
///
/// // Bad
/// opt.map_or(None, |a| Some(a + 1));
///
/// // Good
/// opt.and_then(|a| Some(a + 1));
/// ```
pub OPTION_MAP_OR_NONE,
style,
"using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.map_or(None, Some)`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.ok()`.
///
/// **Known problems:** None.
///
/// **Example:**
///
/// Bad:
/// ```rust
/// # let r: Result<u32, &str> = Ok(1);
/// assert_eq!(Some(1), r.map_or(None, Some));
/// ```
///
/// Good:
/// ```rust
/// # let r: Result<u32, &str> = Ok(1);
/// assert_eq!(Some(1), r.ok());
/// ```
pub RESULT_MAP_OR_INTO_OPTION,
style,
"using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
/// `_.or_else(|x| Err(y))`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.map(|x| y)` or `_.map_err(|x| y)`.
///
/// **Known problems:** None
///
/// **Example:**
///
/// ```rust
/// # fn opt() -> Option<&'static str> { Some("42") }
/// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
/// let _ = opt().and_then(|s| Some(s.len()));
/// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
/// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
/// ```
///
/// The correct use would be:
///
/// ```rust
/// # fn opt() -> Option<&'static str> { Some("42") }
/// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
/// let _ = opt().map(|s| s.len());
/// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
/// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
/// ```
pub BIND_INSTEAD_OF_MAP,
complexity,
"using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.filter(_).next()`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.find(_)`.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// # let vec = vec![1];
/// vec.iter().filter(|x| **x == 0).next();
/// ```
/// Could be written as
/// ```rust
/// # let vec = vec![1];
/// vec.iter().find(|x| **x == 0);
/// ```
pub FILTER_NEXT,
complexity,
"using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.find(!condition)`.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// # let vec = vec![1];
/// vec.iter().skip_while(|x| **x == 0).next();
/// ```
/// Could be written as
/// ```rust
/// # let vec = vec![1];
/// vec.iter().find(|x| **x != 0);
/// ```
pub SKIP_WHILE_NEXT,
complexity,
"using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.flat_map(_)`
///
/// **Known problems:**
///
/// **Example:**
/// ```rust
/// let vec = vec![vec![1]];
///
/// // Bad
/// vec.iter().map(|x| x.iter()).flatten();
///
/// // Good
/// vec.iter().flat_map(|x| x.iter());
/// ```
pub MAP_FLATTEN,
pedantic,
"using combinations of `flatten` and `map` which can usually be written as a single method call"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.filter(_).map(_)`,
/// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.filter_map(_)`.
///
/// **Known problems:** Often requires a condition + Option/Iterator creation
/// inside the closure.
///
/// **Example:**
/// ```rust
/// let vec = vec![1];
///
/// // Bad
/// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
///
/// // Good
/// vec.iter().filter_map(|x| if *x == 0 {
/// Some(*x * 2)
/// } else {
/// None
/// });
/// ```
pub FILTER_MAP,
pedantic,
"using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.filter_map(_).next()`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.find_map(_)`.
///
/// **Known problems:** None
///
/// **Example:**
/// ```rust
/// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
/// ```
/// Can be written as
///
/// ```rust
/// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
/// ```
pub FILTER_MAP_NEXT,
pedantic,
"using combination of `filter_map` and `next` which can usually be written as a single method call"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `flat_map(|x| x)`.
///
/// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
///
/// **Known problems:** None
///
/// **Example:**
/// ```rust
/// # let iter = vec![vec![0]].into_iter();
/// iter.flat_map(|x| x);
/// ```
/// Can be written as
/// ```rust
/// # let iter = vec![vec![0]].into_iter();
/// iter.flatten();
/// ```
pub FLAT_MAP_IDENTITY,
complexity,
"call to `flat_map` where `flatten` is sufficient"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.find(_).map(_)`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.find_map(_)`.
///
/// **Known problems:** Often requires a condition + Option/Iterator creation
/// inside the closure.
///
/// **Example:**
/// ```rust
/// (0..3).find(|x| *x == 2).map(|x| x * 2);
/// ```
/// Can be written as
/// ```rust
/// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
/// ```
pub FIND_MAP,
pedantic,
"using a combination of `find` and `map` can usually be written as a single method call"
}
declare_clippy_lint! {
/// **What it does:** Checks for an iterator search (such as `find()`,
/// `position()`, or `rposition()`) followed by a call to `is_some()`.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.any(_)`.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// # let vec = vec![1];
/// vec.iter().find(|x| **x == 0).is_some();
/// ```
/// Could be written as
/// ```rust
/// # let vec = vec![1];
/// vec.iter().any(|x| *x == 0);
/// ```
pub SEARCH_IS_SOME,
complexity,
"using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
/// if it starts with a given char.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.starts_with(_)`.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let name = "foo";
/// if name.chars().next() == Some('_') {};
/// ```
/// Could be written as
/// ```rust
/// let name = "foo";
/// if name.starts_with('_') {};
/// ```
pub CHARS_NEXT_CMP,
style,
"using `.chars().next()` to check if a string starts with a char"
}
declare_clippy_lint! {
/// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
/// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
/// `unwrap_or_default` instead.
///
/// **Why is this bad?** The function will always be called and potentially
/// allocate an object acting as the default.
///
/// **Known problems:** If the function has side-effects, not calling it will
/// change the semantic of the program, but you shouldn't rely on that anyway.
///
/// **Example:**
/// ```rust
/// # let foo = Some(String::new());
/// foo.unwrap_or(String::new());
/// ```
/// this can instead be written:
/// ```rust
/// # let foo = Some(String::new());
/// foo.unwrap_or_else(String::new);
/// ```
/// or
/// ```rust
/// # let foo = Some(String::new());
/// foo.unwrap_or_default();
/// ```
pub OR_FUN_CALL,
perf,
"using any `*or` method with a function call, which suggests `*or_else`"
}
declare_clippy_lint! {
/// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
/// etc., and suggests to use `unwrap_or_else` instead
///
/// **Why is this bad?** The function will always be called.
///
/// **Known problems:** If the function has side-effects, not calling it will
/// change the semantics of the program, but you shouldn't rely on that anyway.
///
/// **Example:**
/// ```rust
/// # let foo = Some(String::new());
/// # let err_code = "418";
/// # let err_msg = "I'm a teapot";
/// foo.expect(&format!("Err {}: {}", err_code, err_msg));
/// ```
/// or
/// ```rust
/// # let foo = Some(String::new());
/// # let err_code = "418";
/// # let err_msg = "I'm a teapot";
/// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
/// ```
/// this can instead be written:
/// ```rust
/// # let foo = Some(String::new());
/// # let err_code = "418";
/// # let err_msg = "I'm a teapot";
/// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
/// ```
pub EXPECT_FUN_CALL,
perf,
"using any `expect` method with a function call"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
///
/// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
/// generics, not for using the `clone` method on a concrete type.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// 42u64.clone();
/// ```
pub CLONE_ON_COPY,
complexity,
"using `clone` on a `Copy` type"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
/// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
/// function syntax instead (e.g., `Rc::clone(foo)`).
///
/// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
/// can obscure the fact that only the pointer is being cloned, not the underlying
/// data.
///
/// **Example:**
/// ```rust
/// # use std::rc::Rc;
/// let x = Rc::new(1);
///
/// // Bad
/// x.clone();
///
/// // Good
/// Rc::clone(&x);
/// ```
pub CLONE_ON_REF_PTR,
restriction,
"using 'clone' on a ref-counted pointer"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `.clone()` on an `&&T`.
///
/// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
/// cloning the underlying `T`.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// fn main() {
/// let x = vec![1];
/// let y = &&x;
/// let z = y.clone();
/// println!("{:p} {:p}", *y, z); // prints out the same pointer
/// }
/// ```
pub CLONE_DOUBLE_REF,
correctness,
"using `clone` on `&&T`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
/// `T` implements `ToString` directly (like `&&str` or `&&String`).
///
/// **Why is this bad?** This bypasses the specialized implementation of
/// `ToString` and instead goes through the more expensive string formatting
/// facilities.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// // Generic implementation for `T: Display` is used (slow)
/// ["foo", "bar"].iter().map(|s| s.to_string());
///
/// // OK, the specialized impl is used
/// ["foo", "bar"].iter().map(|&s| s.to_string());
/// ```
pub INEFFICIENT_TO_STRING,
pedantic,
"using `to_string` on `&&T` where `T: ToString`"
}
declare_clippy_lint! {
/// **What it does:** Checks for `new` not returning a type that contains `Self`.
///
/// **Why is this bad?** As a convention, `new` methods are used to make a new
/// instance of a type.
///
/// **Known problems:** None.
///
/// **Example:**
/// In an impl block:
/// ```rust
/// # struct Foo;
/// # struct NotAFoo;
/// impl Foo {
/// fn new() -> NotAFoo {
/// # NotAFoo
/// }
/// }
/// ```
///
/// ```rust
/// # struct Foo;
/// struct Bar(Foo);
/// impl Foo {
/// // Bad. The type name must contain `Self`
/// fn new() -> Bar {
/// # Bar(Foo)
/// }
/// }
/// ```
///
/// ```rust
/// # struct Foo;
/// # struct FooError;
/// impl Foo {
/// // Good. Return type contains `Self`
/// fn new() -> Result<Foo, FooError> {
/// # Ok(Foo)
/// }
/// }
/// ```
///
/// Or in a trait definition:
/// ```rust
/// pub trait Trait {
/// // Bad. The type name must contain `Self`
/// fn new();
/// }
/// ```
///
/// ```rust
/// pub trait Trait {
/// // Good. Return type contains `Self`
/// fn new() -> Self;
/// }
/// ```
pub NEW_RET_NO_SELF,
style,
"not returning type containing `Self` in a `new` method"
}
declare_clippy_lint! {
/// **What it does:** Checks for string methods that receive a single-character
/// `str` as an argument, e.g., `_.split("x")`.
///
/// **Why is this bad?** Performing these methods using a `char` is faster than
/// using a `str`.
///
/// **Known problems:** Does not catch multi-byte unicode characters.
///
/// **Example:**
/// ```rust,ignore
/// // Bad
/// _.split("x");
///
/// // Good
/// _.split('x');
pub SINGLE_CHAR_PATTERN,
perf,
"using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
}
declare_clippy_lint! {
/// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
///
/// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
/// actually intend to panic.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust,should_panic
/// for x in (0..100).step_by(0) {
/// //..
/// }
/// ```
pub ITERATOR_STEP_BY_ZERO,
correctness,
"using `Iterator::step_by(0)`, which will panic at runtime"
}
declare_clippy_lint! {
/// **What it does:** Checks for the use of `iter.nth(0)`.
///
/// **Why is this bad?** `iter.next()` is equivalent to
/// `iter.nth(0)`, as they both consume the next element,
/// but is more readable.
///
/// **Known problems:** None.
///
/// **Example:**
///
/// ```rust
/// # use std::collections::HashSet;
/// // Bad
/// # let mut s = HashSet::new();
/// # s.insert(1);
/// let x = s.iter().nth(0);
///
/// // Good
/// # let mut s = HashSet::new();
/// # s.insert(1);
/// let x = s.iter().next();
/// ```
pub ITER_NTH_ZERO,
style,
"replace `iter.nth(0)` with `iter.next()`"
}
declare_clippy_lint! {
/// **What it does:** Checks for use of `.iter().nth()` (and the related
/// `.iter_mut().nth()`) on standard library types with O(1) element access.
///
/// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
/// readable.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let some_vec = vec![0, 1, 2, 3];
/// let bad_vec = some_vec.iter().nth(3);
/// let bad_slice = &some_vec[..].iter().nth(3);
/// ```
/// The correct use would be:
/// ```rust
/// let some_vec = vec![0, 1, 2, 3];
/// let bad_vec = some_vec.get(3);
/// let bad_slice = &some_vec[..].get(3);
/// ```
pub ITER_NTH,
perf,
"using `.iter().nth()` on a standard library type with O(1) element access"
}
declare_clippy_lint! {
/// **What it does:** Checks for use of `.skip(x).next()` on iterators.
///
/// **Why is this bad?** `.nth(x)` is cleaner
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let some_vec = vec![0, 1, 2, 3];
/// let bad_vec = some_vec.iter().skip(3).next();
/// let bad_slice = &some_vec[..].iter().skip(3).next();
/// ```
/// The correct use would be:
/// ```rust
/// let some_vec = vec![0, 1, 2, 3];
/// let bad_vec = some_vec.iter().nth(3);
/// let bad_slice = &some_vec[..].iter().nth(3);
/// ```
pub ITER_SKIP_NEXT,
style,
"using `.skip(x).next()` on an iterator"
}
declare_clippy_lint! {
/// **What it does:** Checks for use of `.get().unwrap()` (or
/// `.get_mut().unwrap`) on a standard library type which implements `Index`
///
/// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
/// concise.
///
/// **Known problems:** Not a replacement for error handling: Using either
/// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
/// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
/// temporary placeholder for dealing with the `Option` type, then this does
/// not mitigate the need for error handling. If there is a chance that `.get()`
/// will be `None` in your program, then it is advisable that the `None` case
/// is handled in a future refactor instead of using `.unwrap()` or the Index
/// trait.
///
/// **Example:**
/// ```rust
/// let mut some_vec = vec![0, 1, 2, 3];
/// let last = some_vec.get(3).unwrap();
/// *some_vec.get_mut(0).unwrap() = 1;
/// ```
/// The correct use would be:
/// ```rust
/// let mut some_vec = vec![0, 1, 2, 3];
/// let last = some_vec[3];
/// some_vec[0] = 1;
/// ```
pub GET_UNWRAP,
restriction,
"using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
}
declare_clippy_lint! {
/// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
/// `&str` or `String`.
///
/// **Why is this bad?** `.push_str(s)` is clearer
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let abc = "abc";
/// let def = String::from("def");
/// let mut s = String::new();
/// s.extend(abc.chars());
/// s.extend(def.chars());
/// ```
/// The correct use would be:
/// ```rust
/// let abc = "abc";
/// let def = String::from("def");
/// let mut s = String::new();
/// s.push_str(abc);
/// s.push_str(&def);
/// ```
pub STRING_EXTEND_CHARS,
style,
"using `x.extend(s.chars())` where s is a `&str` or `String`"
}
declare_clippy_lint! {
/// **What it does:** Checks for the use of `.cloned().collect()` on slice to
/// create a `Vec`.
///
/// **Why is this bad?** `.to_vec()` is clearer
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let s = [1, 2, 3, 4, 5];
/// let s2: Vec<isize> = s[..].iter().cloned().collect();
/// ```
/// The better use would be:
/// ```rust
/// let s = [1, 2, 3, 4, 5];
/// let s2: Vec<isize> = s.to_vec();
/// ```
pub ITER_CLONED_COLLECT,
style,
"using `.cloned().collect()` on slice to create a `Vec`"
}
declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.chars().last()` or
/// `_.chars().next_back()` on a `str` to check if it ends with a given char.
///
/// **Why is this bad?** Readability, this can be written more concisely as
/// `_.ends_with(_)`.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// # let name = "_";
///
/// // Bad
/// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
///
/// // Good
/// name.ends_with('_') || name.ends_with('-');
/// ```