-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
mod.rs
5457 lines (5276 loc) · 181 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 bytecount;
mod bytes_count_to_len;
mod bytes_nth;
mod case_sensitive_file_extension_comparisons;
mod chars_cmp;
mod chars_cmp_with_unwrap;
mod chars_last_cmp;
mod chars_last_cmp_with_unwrap;
mod chars_next_cmp;
mod chars_next_cmp_with_unwrap;
mod clear_with_drain;
mod clone_on_copy;
mod clone_on_ref_ptr;
mod cloned_instead_of_copied;
mod collapsible_str_replace;
mod drain_collect;
mod err_expect;
mod expect_fun_call;
mod extend_with_drain;
mod filetype_is_file;
mod filter_map;
mod filter_map_bool_then;
mod filter_map_identity;
mod filter_map_next;
mod filter_next;
mod flat_map_identity;
mod flat_map_option;
mod format_collect;
mod from_iter_instead_of_collect;
mod get_first;
mod get_last_with_len;
mod get_unwrap;
mod implicit_clone;
mod inefficient_to_string;
mod inspect_for_each;
mod into_iter_on_ref;
mod is_digit_ascii_radix;
mod is_empty;
mod iter_cloned_collect;
mod iter_count;
mod iter_filter;
mod iter_kv_map;
mod iter_next_slice;
mod iter_nth;
mod iter_nth_zero;
mod iter_on_single_or_empty_collections;
mod iter_out_of_bounds;
mod iter_overeager_cloned;
mod iter_skip_next;
mod iter_skip_zero;
mod iter_with_drain;
mod iterator_step_by_zero;
mod join_absolute_paths;
mod manual_c_str_literals;
mod manual_inspect;
mod manual_is_variant_and;
mod manual_next_back;
mod manual_ok_or;
mod manual_saturating_arithmetic;
mod manual_str_repeat;
mod manual_try_fold;
mod map_all_any_identity;
mod map_clone;
mod map_collect_result_unit;
mod map_err_ignore;
mod map_flatten;
mod map_identity;
mod map_unwrap_or;
mod map_with_unused_argument_over_ranges;
mod mut_mutex_lock;
mod needless_as_bytes;
mod needless_character_iteration;
mod needless_collect;
mod needless_option_as_deref;
mod needless_option_take;
mod no_effect_replace;
mod obfuscated_if_else;
mod ok_expect;
mod open_options;
mod option_as_ref_cloned;
mod option_as_ref_deref;
mod option_map_or_err_ok;
mod option_map_or_none;
mod option_map_unwrap_or;
mod or_fun_call;
mod or_then_unwrap;
mod path_buf_push_overwrite;
mod path_ends_with_ext;
mod range_zip_with_len;
mod read_line_without_trim;
mod readonly_write_lock;
mod redundant_as_str;
mod repeat_once;
mod result_map_or_else_none;
mod search_is_some;
mod seek_from_current;
mod seek_to_start_instead_of_rewind;
mod single_char_add_str;
mod single_char_insert_string;
mod single_char_push_string;
mod skip_while_next;
mod stable_sort_primitive;
mod str_split;
mod str_splitn;
mod string_extend_chars;
mod string_lit_chars_any;
mod suspicious_command_arg_space;
mod suspicious_map;
mod suspicious_splitn;
mod suspicious_to_owned;
mod type_id_on_box;
mod uninit_assumed_init;
mod unit_hash;
mod unnecessary_fallible_conversions;
mod unnecessary_filter_map;
mod unnecessary_first_then_check;
mod unnecessary_fold;
mod unnecessary_get_then_check;
mod unnecessary_iter_cloned;
mod unnecessary_join;
mod unnecessary_lazy_eval;
mod unnecessary_literal_unwrap;
mod unnecessary_map_or;
mod unnecessary_min_or_max;
mod unnecessary_result_map_or_else;
mod unnecessary_sort_by;
mod unnecessary_to_owned;
mod unused_enumerate_index;
mod unwrap_expect_used;
mod useless_asref;
mod utils;
mod vec_resize_to_zero;
mod verbose_file_reads;
mod waker_clone_wake;
mod wrong_self_convention;
mod zst_offset;
use clippy_config::Conf;
use clippy_utils::consts::{ConstEvalCtxt, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::macros::FormatArgsStorage;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::ty::{contains_ty_adt_constructor_opaque, implements_trait, is_copy, is_type_diagnostic_item};
use clippy_utils::{contains_return, is_bool, is_trait_method, iter_input_pats, peel_blocks, return_ty};
pub use path_ends_with_ext::DEFAULT_ALLOWED_DOTFILES;
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::{Expr, ExprKind, Node, Stmt, StmtKind, TraitItem, TraitItemKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::{self, TraitRef, Ty};
use rustc_session::impl_lint_pass;
use rustc_span::{Span, sym};
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `cloned()` on an `Iterator` or `Option` where
/// `copied()` could be used instead.
///
/// ### Why is this bad?
/// `copied()` is better because it guarantees that the type being cloned
/// implements `Copy`.
///
/// ### Example
/// ```no_run
/// [1, 2, 3].iter().cloned();
/// ```
/// Use instead:
/// ```no_run
/// [1, 2, 3].iter().copied();
/// ```
#[clippy::version = "1.53.0"]
pub CLONED_INSTEAD_OF_COPIED,
pedantic,
"used `cloned` where `copied` could be used instead"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for consecutive calls to `str::replace` (2 or more)
/// that can be collapsed into a single call.
///
/// ### Why is this bad?
/// Consecutive `str::replace` calls scan the string multiple times
/// with repetitive code.
///
/// ### Example
/// ```no_run
/// let hello = "hesuo worpd"
/// .replace('s', "l")
/// .replace("u", "l")
/// .replace('p', "l");
/// ```
/// Use instead:
/// ```no_run
/// let hello = "hesuo worpd".replace(['s', 'u', 'p'], "l");
/// ```
#[clippy::version = "1.65.0"]
pub COLLAPSIBLE_STR_REPLACE,
perf,
"collapse consecutive calls to str::replace (2 or more) into a single call"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `_.cloned().<func>()` where call to `.cloned()` can be postponed.
///
/// ### Why is this bad?
/// It's often inefficient to clone all elements of an iterator, when eventually, only some
/// of them will be consumed.
///
/// ### Known Problems
/// This `lint` removes the side of effect of cloning items in the iterator.
/// A code that relies on that side-effect could fail.
///
/// ### Examples
/// ```no_run
/// # let vec = vec!["string".to_string()];
/// vec.iter().cloned().take(10);
/// vec.iter().cloned().last();
/// ```
///
/// Use instead:
/// ```no_run
/// # let vec = vec!["string".to_string()];
/// vec.iter().take(10).cloned();
/// vec.iter().last().cloned();
/// ```
#[clippy::version = "1.60.0"]
pub ITER_OVEREAGER_CLONED,
perf,
"using `cloned()` early with `Iterator::iter()` can lead to some performance inefficiencies"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `Iterator::flat_map()` where `filter_map()` could be
/// used instead.
///
/// ### Why is this bad?
/// `filter_map()` is known to always produce 0 or 1 output items per input item,
/// rather than however many the inner iterator type produces.
/// Therefore, it maintains the upper bound in `Iterator::size_hint()`,
/// and communicates to the reader that the input items are not being expanded into
/// multiple output items without their having to notice that the mapping function
/// returns an `Option`.
///
/// ### Example
/// ```no_run
/// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
/// ```
/// Use instead:
/// ```no_run
/// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
/// ```
#[clippy::version = "1.53.0"]
pub FLAT_MAP_OPTION,
pedantic,
"used `flat_map` where `filter_map` could be used instead"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s.
///
/// ### Why restrict this?
/// 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.
///
/// ### Examples
/// ```no_run
/// # let option = Some(1);
/// # let result: Result<usize, ()> = Ok(1);
/// option.unwrap();
/// result.unwrap();
/// ```
///
/// Use instead:
/// ```no_run
/// # let option = Some(1);
/// # let result: Result<usize, ()> = Ok(1);
/// option.expect("more helpful message");
/// result.expect("more helpful message");
/// ```
///
/// If [expect_used](#expect_used) is enabled, instead:
/// ```rust,ignore
/// # let option = Some(1);
/// # let result: Result<usize, ()> = Ok(1);
/// option?;
///
/// // or
///
/// result?;
/// ```
#[clippy::version = "1.45.0"]
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 `.unwrap()` related calls on `Result`s and `Option`s that are constructed.
///
/// ### Why is this bad?
/// It is better to write the value directly without the indirection.
///
/// ### Examples
/// ```no_run
/// let val1 = Some(1).unwrap();
/// let val2 = Ok::<_, ()>(1).unwrap();
/// let val3 = Err::<(), _>(1).unwrap_err();
/// ```
///
/// Use instead:
/// ```no_run
/// let val1 = 1;
/// let val2 = 1;
/// let val3 = 1;
/// ```
#[clippy::version = "1.72.0"]
pub UNNECESSARY_LITERAL_UNWRAP,
complexity,
"using `unwrap()` related calls on `Result` and `Option` constructors"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s.
///
/// ### Why restrict this?
/// 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.
///
/// ### Examples
/// ```rust,ignore
/// # let option = Some(1);
/// # let result: Result<usize, ()> = Ok(1);
/// option.expect("one");
/// result.expect("one");
/// ```
///
/// Use instead:
/// ```rust,ignore
/// # let option = Some(1);
/// # let result: Result<usize, ()> = Ok(1);
/// option?;
///
/// // or
///
/// result?;
/// ```
#[clippy::version = "1.45.0"]
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.
///
/// ### Example
/// ```no_run
/// struct X;
/// impl X {
/// fn add(&self, other: &X) -> X {
/// // ..
/// # X
/// }
/// }
/// ```
#[clippy::version = "pre 1.29.0"]
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 or suffixes, and which
/// do not adhere to standard conventions regarding how `self` is taken.
/// The actual rules are:
///
/// |Prefix |Postfix |`self` taken | `self` type |
/// |-------|------------|-------------------------------|--------------|
/// |`as_` | none |`&self` or `&mut self` | any |
/// |`from_`| none | none | any |
/// |`into_`| none |`self` | any |
/// |`is_` | none |`&mut self` or `&self` or none | any |
/// |`to_` | `_mut` |`&mut self` | any |
/// |`to_` | not `_mut` |`self` | `Copy` |
/// |`to_` | not `_mut` |`&self` | not `Copy` |
///
/// Note: Clippy doesn't trigger methods with `to_` prefix in:
/// - Traits definition.
/// Clippy can not tell if a type that implements a trait is `Copy` or not.
/// - Traits implementation, when `&self` is taken.
/// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
/// (see e.g. the `std::string::ToString` trait).
///
/// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
///
/// Please find more info here:
/// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
///
/// ### 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.
///
/// ### Example
/// ```no_run
/// # struct X;
/// impl X {
/// fn as_str(self) -> &'static str {
/// // ..
/// # ""
/// }
/// }
/// ```
///
/// Use instead:
/// ```no_run
/// # struct X;
/// impl X {
/// fn as_str(&self) -> &'static str {
/// // ..
/// # ""
/// }
/// }
/// ```
#[clippy::version = "pre 1.29.0"]
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
/// 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
/// ```no_run
/// # let x = Ok::<_, ()>(());
/// x.ok().expect("why did I do this again?");
/// ```
///
/// Use instead:
/// ```no_run
/// # let x = Ok::<_, ()>(());
/// x.expect("why did I do this again?");
/// ```
#[clippy::version = "pre 1.29.0"]
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 `.err().expect()` calls on the `Result` type.
///
/// ### Why is this bad?
/// `.expect_err()` can be called directly to avoid the extra type conversion from `err()`.
///
/// ### Example
/// ```should_panic
/// let x: Result<u32, &str> = Ok(10);
/// x.err().expect("Testing err().expect()");
/// ```
/// Use instead:
/// ```should_panic
/// let x: Result<u32, &str> = Ok(10);
/// x.expect_err("Testing expect_err");
/// ```
#[clippy::version = "1.62.0"]
pub ERR_EXPECT,
style,
r#"using `.err().expect("")` when `.expect_err("")` can be used"#
}
declare_clippy_lint! {
/// ### What it does
/// Checks for usages of the following functions with an argument that constructs a default value
/// (e.g., `Default::default` or `String::new`):
/// - `unwrap_or`
/// - `unwrap_or_else`
/// - `or_insert`
/// - `or_insert_with`
///
/// ### Why is this bad?
/// Readability. Using `unwrap_or_default` in place of `unwrap_or`/`unwrap_or_else`, or `or_default`
/// in place of `or_insert`/`or_insert_with`, is simpler and more concise.
///
/// ### Known problems
/// In some cases, the argument of `unwrap_or`, etc. is needed for type inference. The lint uses a
/// heuristic to try to identify such cases. However, the heuristic can produce false negatives.
///
/// ### Examples
/// ```no_run
/// # let x = Some(1);
/// # let mut map = std::collections::HashMap::<u64, String>::new();
/// x.unwrap_or(Default::default());
/// map.entry(42).or_insert_with(String::new);
/// ```
///
/// Use instead:
/// ```no_run
/// # let x = Some(1);
/// # let mut map = std::collections::HashMap::<u64, String>::new();
/// x.unwrap_or_default();
/// map.entry(42).or_default();
/// ```
#[clippy::version = "1.56.0"]
pub UNWRAP_OR_DEFAULT,
style,
"using `.unwrap_or`, etc. with an argument that constructs a default value"
}
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
/// ```no_run
/// # let option = Some(1);
/// # let result: Result<usize, ()> = Ok(1);
/// # fn some_function(foo: ()) -> usize { 1 }
/// option.map(|a| a + 1).unwrap_or(0);
/// option.map(|a| a > 10).unwrap_or(false);
/// result.map(|a| a + 1).unwrap_or_else(some_function);
/// ```
///
/// Use instead:
/// ```no_run
/// # let option = Some(1);
/// # let result: Result<usize, ()> = Ok(1);
/// # fn some_function(foo: ()) -> usize { 1 }
/// option.map_or(0, |a| a + 1);
/// option.is_some_and(|a| a > 10);
/// result.map_or_else(some_function, |a| a + 1);
/// ```
#[clippy::version = "1.45.0"]
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
/// ```no_run
/// # let opt = Some(1);
/// opt.map_or(None, |a| Some(a + 1));
/// ```
///
/// Use instead:
/// ```no_run
/// # let opt = Some(1);
/// opt.and_then(|a| Some(a + 1));
/// ```
#[clippy::version = "pre 1.29.0"]
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()`.
///
/// ### Example
/// ```no_run
/// # let r: Result<u32, &str> = Ok(1);
/// assert_eq!(Some(1), r.map_or(None, Some));
/// ```
///
/// Use instead:
/// ```no_run
/// # let r: Result<u32, &str> = Ok(1);
/// assert_eq!(Some(1), r.ok());
/// ```
#[clippy::version = "1.44.0"]
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?
/// This can be written more concisely as `_.map(|x| y)` or `_.map_err(|x| y)`.
///
/// ### Example
/// ```no_run
/// # 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:
///
/// ```no_run
/// # 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 });
/// ```
#[clippy::version = "1.45.0"]
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(_)`.
///
/// ### Example
/// ```no_run
/// # let vec = vec![1];
/// vec.iter().filter(|x| **x == 0).next();
/// ```
///
/// Use instead:
/// ```no_run
/// # let vec = vec![1];
/// vec.iter().find(|x| **x == 0);
/// ```
#[clippy::version = "pre 1.29.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)`.
///
/// ### Example
/// ```no_run
/// # let vec = vec![1];
/// vec.iter().skip_while(|x| **x == 0).next();
/// ```
///
/// Use instead:
/// ```no_run
/// # let vec = vec![1];
/// vec.iter().find(|x| **x != 0);
/// ```
#[clippy::version = "1.42.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(_)` on `Iterator` and `Option`
///
/// ### Why is this bad?
/// Readability, this can be written more concisely as
/// `_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option`
///
/// ### Example
/// ```no_run
/// let vec = vec![vec![1]];
/// let opt = Some(5);
///
/// vec.iter().map(|x| x.iter()).flatten();
/// opt.map(|x| Some(x * 2)).flatten();
/// ```
///
/// Use instead:
/// ```no_run
/// # let vec = vec![vec![1]];
/// # let opt = Some(5);
/// vec.iter().flat_map(|x| x.iter());
/// opt.and_then(|x| Some(x * 2));
/// ```
#[clippy::version = "1.31.0"]
pub MAP_FLATTEN,
complexity,
"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(_)` that can be written more simply
/// as `filter_map(_)`.
///
/// ### Why is this bad?
/// Redundant code in the `filter` and `map` operations is poor style and
/// less performant.
///
/// ### Example
/// ```no_run
/// (0_i32..10)
/// .filter(|n| n.checked_add(1).is_some())
/// .map(|n| n.checked_add(1).unwrap());
/// ```
///
/// Use instead:
/// ```no_run
/// (0_i32..10).filter_map(|n| n.checked_add(1));
/// ```
#[clippy::version = "1.51.0"]
pub MANUAL_FILTER_MAP,
complexity,
"using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `_.find(_).map(_)` that can be written more simply
/// as `find_map(_)`.
///
/// ### Why is this bad?
/// Redundant code in the `find` and `map` operations is poor style and
/// less performant.
///
/// ### Example
/// ```no_run
/// (0_i32..10)
/// .find(|n| n.checked_add(1).is_some())
/// .map(|n| n.checked_add(1).unwrap());
/// ```
///
/// Use instead:
/// ```no_run
/// (0_i32..10).find_map(|n| n.checked_add(1));
/// ```
#[clippy::version = "1.51.0"]
pub MANUAL_FIND_MAP,
complexity,
"using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
}
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(_)`.
///
/// ### Example
/// ```no_run
/// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
/// ```
/// Can be written as
///
/// ```no_run
/// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
/// ```
#[clippy::version = "1.36.0"]
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`.
///
/// ### Example
/// ```no_run
/// # let iter = vec![vec![0]].into_iter();
/// iter.flat_map(|x| x);
/// ```
/// Can be written as
/// ```no_run
/// # let iter = vec![vec![0]].into_iter();
/// iter.flatten();
/// ```
#[clippy::version = "1.39.0"]
pub FLAT_MAP_IDENTITY,
complexity,
"call to `flat_map` where `flatten` is sufficient"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for an iterator or string search (such as `find()`,
/// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
///
/// ### Why is this bad?
/// Readability, this can be written more concisely as:
/// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
/// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
///
/// ### Example
/// ```no_run
/// let vec = vec![1];
/// vec.iter().find(|x| **x == 0).is_some();
///
/// "hello world".find("world").is_none();
/// ```
///
/// Use instead:
/// ```no_run
/// let vec = vec![1];
/// vec.iter().any(|x| *x == 0);
///
/// !"hello world".contains("world");
/// ```
#[clippy::version = "pre 1.29.0"]
pub SEARCH_IS_SOME,
complexity,
"using an iterator or string search followed by `is_some()` or `is_none()`, which is more succinctly expressed as a call to `any()` or `contains()` (with negation in case of `is_none()`)"
}
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(_)`.
///
/// ### Example
/// ```no_run
/// let name = "foo";
/// if name.chars().next() == Some('_') {};
/// ```
///
/// Use instead:
/// ```no_run
/// let name = "foo";
/// if name.starts_with('_') {};
/// ```
#[clippy::version = "pre 1.29.0"]
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(..))`,
/// `.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`,
/// `.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()`
/// etc. instead.
///
/// ### Why is this bad?
/// The function will always be called. This is only bad if it allocates or
/// does some non-trivial amount of work.
///
/// ### 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.
///
/// The lint also cannot figure out whether the function you call is
/// actually expensive to call or not.
///
/// ### Example
/// ```no_run
/// # let foo = Some(String::new());
/// foo.unwrap_or(String::from("empty"));
/// ```
///
/// Use instead:
/// ```no_run
/// # let foo = Some(String::new());
/// foo.unwrap_or_else(|| String::from("empty"));
/// ```
#[clippy::version = "pre 1.29.0"]
pub OR_FUN_CALL,
nursery,
"using any `*or` method with a function call, which suggests `*or_else`"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for `.or(…).unwrap()` calls to Options and Results.
///
/// ### Why is this bad?
/// You should use `.unwrap_or(…)` instead for clarity.
///
/// ### Example
/// ```no_run
/// # let fallback = "fallback";
/// // Result
/// # type Error = &'static str;
/// # let result: Result<&str, Error> = Err("error");
/// let value = result.or::<Error>(Ok(fallback)).unwrap();
///
/// // Option
/// # let option: Option<&str> = None;
/// let value = option.or(Some(fallback)).unwrap();
/// ```
/// Use instead:
/// ```no_run
/// # let fallback = "fallback";
/// // Result
/// # let result: Result<&str, &str> = Err("error");
/// let value = result.unwrap_or(fallback);
///
/// // Option
/// # let option: Option<&str> = None;
/// let value = option.unwrap_or(fallback);
/// ```
#[clippy::version = "1.61.0"]
pub OR_THEN_UNWRAP,
complexity,
"checks for `.or(…).unwrap()` calls to Options and Results."
}
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
/// ```no_run
/// # let foo = Some(String::new());
/// # let err_code = "418";
/// # let err_msg = "I'm a teapot";
/// foo.expect(&format!("Err {}: {}", err_code, err_msg));