1 mod bind_instead_of_map;
2 mod bytes_nth;
3 mod chars_cmp;
4 mod chars_cmp_with_unwrap;
5 mod chars_last_cmp;
6 mod chars_last_cmp_with_unwrap;
7 mod chars_next_cmp;
8 mod chars_next_cmp_with_unwrap;
9 mod clone_on_copy;
10 mod clone_on_ref_ptr;
11 mod cloned_instead_of_copied;
12 mod expect_fun_call;
13 mod expect_used;
14 mod extend_with_drain;
15 mod filetype_is_file;
16 mod filter_map;
17 mod filter_map_identity;
18 mod filter_map_next;
19 mod filter_next;
20 mod flat_map_identity;
21 mod flat_map_option;
22 mod from_iter_instead_of_collect;
23 mod get_unwrap;
24 mod implicit_clone;
25 mod inefficient_to_string;
26 mod inspect_for_each;
27 mod into_iter_on_ref;
28 mod iter_cloned_collect;
29 mod iter_count;
30 mod iter_next_slice;
31 mod iter_nth;
32 mod iter_nth_zero;
33 mod iter_skip_next;
34 mod iterator_step_by_zero;
35 mod manual_saturating_arithmetic;
36 mod manual_split_once;
37 mod manual_str_repeat;
38 mod map_collect_result_unit;
39 mod map_flatten;
40 mod map_identity;
41 mod map_unwrap_or;
42 mod ok_expect;
43 mod option_as_ref_deref;
44 mod option_map_or_none;
45 mod option_map_unwrap_or;
46 mod or_fun_call;
47 mod search_is_some;
48 mod single_char_add_str;
49 mod single_char_insert_string;
50 mod single_char_pattern;
51 mod single_char_push_string;
52 mod skip_while_next;
53 mod string_extend_chars;
54 mod suspicious_map;
55 mod suspicious_splitn;
56 mod uninit_assumed_init;
57 mod unnecessary_filter_map;
58 mod unnecessary_fold;
59 mod unnecessary_lazy_eval;
60 mod unwrap_or_else_default;
61 mod unwrap_used;
62 mod useless_asref;
63 mod utils;
64 mod wrong_self_convention;
65 mod zst_offset;
66 
67 use bind_instead_of_map::BindInsteadOfMap;
68 use clippy_utils::consts::{constant, Constant};
69 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
70 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
71 use clippy_utils::{contains_return, get_trait_def_id, in_macro, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
72 use if_chain::if_chain;
73 use rustc_hir as hir;
74 use rustc_hir::def::Res;
75 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
76 use rustc_lint::{LateContext, LateLintPass, LintContext};
77 use rustc_middle::lint::in_external_macro;
78 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
79 use rustc_semver::RustcVersion;
80 use rustc_session::{declare_tool_lint, impl_lint_pass};
81 use rustc_span::symbol::SymbolStr;
82 use rustc_span::{sym, Span};
83 use rustc_typeck::hir_ty_to_ty;
84 
85 declare_clippy_lint! {
86     /// ### What it does
87     /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
88     /// `copied()` could be used instead.
89     ///
90     /// ### Why is this bad?
91     /// `copied()` is better because it guarantees that the type being cloned
92     /// implements `Copy`.
93     ///
94     /// ### Example
95     /// ```rust
96     /// [1, 2, 3].iter().cloned();
97     /// ```
98     /// Use instead:
99     /// ```rust
100     /// [1, 2, 3].iter().copied();
101     /// ```
102     pub CLONED_INSTEAD_OF_COPIED,
103     pedantic,
104     "used `cloned` where `copied` could be used instead"
105 }
106 
107 declare_clippy_lint! {
108     /// ### What it does
109     /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
110     /// used instead.
111     ///
112     /// ### Why is this bad?
113     /// When applicable, `filter_map()` is more clear since it shows that
114     /// `Option` is used to produce 0 or 1 items.
115     ///
116     /// ### Example
117     /// ```rust
118     /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
119     /// ```
120     /// Use instead:
121     /// ```rust
122     /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
123     /// ```
124     pub FLAT_MAP_OPTION,
125     pedantic,
126     "used `flat_map` where `filter_map` could be used instead"
127 }
128 
129 declare_clippy_lint! {
130     /// ### What it does
131     /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
132     ///
133     /// ### Why is this bad?
134     /// It is better to handle the `None` or `Err` case,
135     /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
136     /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
137     /// `Allow` by default.
138     ///
139     /// `result.unwrap()` will let the thread panic on `Err` values.
140     /// Normally, you want to implement more sophisticated error handling,
141     /// and propagate errors upwards with `?` operator.
142     ///
143     /// Even if you want to panic on errors, not all `Error`s implement good
144     /// messages on display. Therefore, it may be beneficial to look at the places
145     /// where they may get displayed. Activate this lint to do just that.
146     ///
147     /// ### Examples
148     /// ```rust
149     /// # let opt = Some(1);
150     ///
151     /// // Bad
152     /// opt.unwrap();
153     ///
154     /// // Good
155     /// opt.expect("more helpful message");
156     /// ```
157     ///
158     /// // or
159     ///
160     /// ```rust
161     /// # let res: Result<usize, ()> = Ok(1);
162     ///
163     /// // Bad
164     /// res.unwrap();
165     ///
166     /// // Good
167     /// res.expect("more helpful message");
168     /// ```
169     pub UNWRAP_USED,
170     restriction,
171     "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
172 }
173 
174 declare_clippy_lint! {
175     /// ### What it does
176     /// Checks for `.expect()` calls on `Option`s and `Result`s.
177     ///
178     /// ### Why is this bad?
179     /// Usually it is better to handle the `None` or `Err` case.
180     /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
181     /// this lint is `Allow` by default.
182     ///
183     /// `result.expect()` will let the thread panic on `Err`
184     /// values. Normally, you want to implement more sophisticated error handling,
185     /// and propagate errors upwards with `?` operator.
186     ///
187     /// ### Examples
188     /// ```rust,ignore
189     /// # let opt = Some(1);
190     ///
191     /// // Bad
192     /// opt.expect("one");
193     ///
194     /// // Good
195     /// let opt = Some(1);
196     /// opt?;
197     /// ```
198     ///
199     /// // or
200     ///
201     /// ```rust
202     /// # let res: Result<usize, ()> = Ok(1);
203     ///
204     /// // Bad
205     /// res.expect("one");
206     ///
207     /// // Good
208     /// res?;
209     /// # Ok::<(), ()>(())
210     /// ```
211     pub EXPECT_USED,
212     restriction,
213     "using `.expect()` on `Result` or `Option`, which might be better handled"
214 }
215 
216 declare_clippy_lint! {
217     /// ### What it does
218     /// Checks for methods that should live in a trait
219     /// implementation of a `std` trait (see [llogiq's blog
220     /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
221     /// information) instead of an inherent implementation.
222     ///
223     /// ### Why is this bad?
224     /// Implementing the traits improve ergonomics for users of
225     /// the code, often with very little cost. Also people seeing a `mul(...)`
226     /// method
227     /// may expect `*` to work equally, so you should have good reason to disappoint
228     /// them.
229     ///
230     /// ### Example
231     /// ```rust
232     /// struct X;
233     /// impl X {
234     ///     fn add(&self, other: &X) -> X {
235     ///         // ..
236     /// # X
237     ///     }
238     /// }
239     /// ```
240     pub SHOULD_IMPLEMENT_TRAIT,
241     style,
242     "defining a method that should be implementing a std trait"
243 }
244 
245 declare_clippy_lint! {
246     /// ### What it does
247     /// Checks for methods with certain name prefixes and which
248     /// doesn't match how self is taken. The actual rules are:
249     ///
250     /// |Prefix |Postfix     |`self` taken           | `self` type  |
251     /// |-------|------------|-----------------------|--------------|
252     /// |`as_`  | none       |`&self` or `&mut self` | any          |
253     /// |`from_`| none       | none                  | any          |
254     /// |`into_`| none       |`self`                 | any          |
255     /// |`is_`  | none       |`&self` or none        | any          |
256     /// |`to_`  | `_mut`     |`&mut self`            | any          |
257     /// |`to_`  | not `_mut` |`self`                 | `Copy`       |
258     /// |`to_`  | not `_mut` |`&self`                | not `Copy`   |
259     ///
260     /// Note: Clippy doesn't trigger methods with `to_` prefix in:
261     /// - Traits definition.
262     /// Clippy can not tell if a type that implements a trait is `Copy` or not.
263     /// - Traits implementation, when `&self` is taken.
264     /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
265     /// (see e.g. the `std::string::ToString` trait).
266     ///
267     /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
268     ///
269     /// Please find more info here:
270     /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
271     ///
272     /// ### Why is this bad?
273     /// Consistency breeds readability. If you follow the
274     /// conventions, your users won't be surprised that they, e.g., need to supply a
275     /// mutable reference to a `as_..` function.
276     ///
277     /// ### Example
278     /// ```rust
279     /// # struct X;
280     /// impl X {
281     ///     fn as_str(self) -> &'static str {
282     ///         // ..
283     /// # ""
284     ///     }
285     /// }
286     /// ```
287     pub WRONG_SELF_CONVENTION,
288     style,
289     "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
290 }
291 
292 declare_clippy_lint! {
293     /// ### What it does
294     /// Checks for usage of `ok().expect(..)`.
295     ///
296     /// ### Why is this bad?
297     /// Because you usually call `expect()` on the `Result`
298     /// directly to get a better error message.
299     ///
300     /// ### Known problems
301     /// The error type needs to implement `Debug`
302     ///
303     /// ### Example
304     /// ```rust
305     /// # let x = Ok::<_, ()>(());
306     ///
307     /// // Bad
308     /// x.ok().expect("why did I do this again?");
309     ///
310     /// // Good
311     /// x.expect("why did I do this again?");
312     /// ```
313     pub OK_EXPECT,
314     style,
315     "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
316 }
317 
318 declare_clippy_lint! {
319     /// ### What it does
320     /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
321     /// `Result` values.
322     ///
323     /// ### Why is this bad?
324     /// Readability, these can be written as `_.unwrap_or_default`, which is
325     /// simpler and more concise.
326     ///
327     /// ### Examples
328     /// ```rust
329     /// # let x = Some(1);
330     ///
331     /// // Bad
332     /// x.unwrap_or_else(Default::default);
333     /// x.unwrap_or_else(u32::default);
334     ///
335     /// // Good
336     /// x.unwrap_or_default();
337     /// ```
338     pub UNWRAP_OR_ELSE_DEFAULT,
339     style,
340     "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
341 }
342 
343 declare_clippy_lint! {
344     /// ### What it does
345     /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
346     /// `result.map(_).unwrap_or_else(_)`.
347     ///
348     /// ### Why is this bad?
349     /// Readability, these can be written more concisely (resp.) as
350     /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
351     ///
352     /// ### Known problems
353     /// The order of the arguments is not in execution order
354     ///
355     /// ### Examples
356     /// ```rust
357     /// # let x = Some(1);
358     ///
359     /// // Bad
360     /// x.map(|a| a + 1).unwrap_or(0);
361     ///
362     /// // Good
363     /// x.map_or(0, |a| a + 1);
364     /// ```
365     ///
366     /// // or
367     ///
368     /// ```rust
369     /// # let x: Result<usize, ()> = Ok(1);
370     /// # fn some_function(foo: ()) -> usize { 1 }
371     ///
372     /// // Bad
373     /// x.map(|a| a + 1).unwrap_or_else(some_function);
374     ///
375     /// // Good
376     /// x.map_or_else(some_function, |a| a + 1);
377     /// ```
378     pub MAP_UNWRAP_OR,
379     pedantic,
380     "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)`"
381 }
382 
383 declare_clippy_lint! {
384     /// ### What it does
385     /// Checks for usage of `_.map_or(None, _)`.
386     ///
387     /// ### Why is this bad?
388     /// Readability, this can be written more concisely as
389     /// `_.and_then(_)`.
390     ///
391     /// ### Known problems
392     /// The order of the arguments is not in execution order.
393     ///
394     /// ### Example
395     /// ```rust
396     /// # let opt = Some(1);
397     ///
398     /// // Bad
399     /// opt.map_or(None, |a| Some(a + 1));
400     ///
401     /// // Good
402     /// opt.and_then(|a| Some(a + 1));
403     /// ```
404     pub OPTION_MAP_OR_NONE,
405     style,
406     "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
407 }
408 
409 declare_clippy_lint! {
410     /// ### What it does
411     /// Checks for usage of `_.map_or(None, Some)`.
412     ///
413     /// ### Why is this bad?
414     /// Readability, this can be written more concisely as
415     /// `_.ok()`.
416     ///
417     /// ### Example
418     /// Bad:
419     /// ```rust
420     /// # let r: Result<u32, &str> = Ok(1);
421     /// assert_eq!(Some(1), r.map_or(None, Some));
422     /// ```
423     ///
424     /// Good:
425     /// ```rust
426     /// # let r: Result<u32, &str> = Ok(1);
427     /// assert_eq!(Some(1), r.ok());
428     /// ```
429     pub RESULT_MAP_OR_INTO_OPTION,
430     style,
431     "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
432 }
433 
434 declare_clippy_lint! {
435     /// ### What it does
436     /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
437     /// `_.or_else(|x| Err(y))`.
438     ///
439     /// ### Why is this bad?
440     /// Readability, this can be written more concisely as
441     /// `_.map(|x| y)` or `_.map_err(|x| y)`.
442     ///
443     /// ### Example
444     /// ```rust
445     /// # fn opt() -> Option<&'static str> { Some("42") }
446     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
447     /// let _ = opt().and_then(|s| Some(s.len()));
448     /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
449     /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
450     /// ```
451     ///
452     /// The correct use would be:
453     ///
454     /// ```rust
455     /// # fn opt() -> Option<&'static str> { Some("42") }
456     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
457     /// let _ = opt().map(|s| s.len());
458     /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
459     /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
460     /// ```
461     pub BIND_INSTEAD_OF_MAP,
462     complexity,
463     "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
464 }
465 
466 declare_clippy_lint! {
467     /// ### What it does
468     /// Checks for usage of `_.filter(_).next()`.
469     ///
470     /// ### Why is this bad?
471     /// Readability, this can be written more concisely as
472     /// `_.find(_)`.
473     ///
474     /// ### Example
475     /// ```rust
476     /// # let vec = vec![1];
477     /// vec.iter().filter(|x| **x == 0).next();
478     /// ```
479     /// Could be written as
480     /// ```rust
481     /// # let vec = vec![1];
482     /// vec.iter().find(|x| **x == 0);
483     /// ```
484     pub FILTER_NEXT,
485     complexity,
486     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
487 }
488 
489 declare_clippy_lint! {
490     /// ### What it does
491     /// Checks for usage of `_.skip_while(condition).next()`.
492     ///
493     /// ### Why is this bad?
494     /// Readability, this can be written more concisely as
495     /// `_.find(!condition)`.
496     ///
497     /// ### Example
498     /// ```rust
499     /// # let vec = vec![1];
500     /// vec.iter().skip_while(|x| **x == 0).next();
501     /// ```
502     /// Could be written as
503     /// ```rust
504     /// # let vec = vec![1];
505     /// vec.iter().find(|x| **x != 0);
506     /// ```
507     pub SKIP_WHILE_NEXT,
508     complexity,
509     "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
510 }
511 
512 declare_clippy_lint! {
513     /// ### What it does
514     /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
515     ///
516     /// ### Why is this bad?
517     /// Readability, this can be written more concisely as
518     /// `_.flat_map(_)`
519     ///
520     /// ### Example
521     /// ```rust
522     /// let vec = vec![vec![1]];
523     ///
524     /// // Bad
525     /// vec.iter().map(|x| x.iter()).flatten();
526     ///
527     /// // Good
528     /// vec.iter().flat_map(|x| x.iter());
529     /// ```
530     pub MAP_FLATTEN,
531     pedantic,
532     "using combinations of `flatten` and `map` which can usually be written as a single method call"
533 }
534 
535 declare_clippy_lint! {
536     /// ### What it does
537     /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
538     /// as `filter_map(_)`.
539     ///
540     /// ### Why is this bad?
541     /// Redundant code in the `filter` and `map` operations is poor style and
542     /// less performant.
543     ///
544      /// ### Example
545     /// Bad:
546     /// ```rust
547     /// (0_i32..10)
548     ///     .filter(|n| n.checked_add(1).is_some())
549     ///     .map(|n| n.checked_add(1).unwrap());
550     /// ```
551     ///
552     /// Good:
553     /// ```rust
554     /// (0_i32..10).filter_map(|n| n.checked_add(1));
555     /// ```
556     pub MANUAL_FILTER_MAP,
557     complexity,
558     "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
559 }
560 
561 declare_clippy_lint! {
562     /// ### What it does
563     /// Checks for usage of `_.find(_).map(_)` that can be written more simply
564     /// as `find_map(_)`.
565     ///
566     /// ### Why is this bad?
567     /// Redundant code in the `find` and `map` operations is poor style and
568     /// less performant.
569     ///
570      /// ### Example
571     /// Bad:
572     /// ```rust
573     /// (0_i32..10)
574     ///     .find(|n| n.checked_add(1).is_some())
575     ///     .map(|n| n.checked_add(1).unwrap());
576     /// ```
577     ///
578     /// Good:
579     /// ```rust
580     /// (0_i32..10).find_map(|n| n.checked_add(1));
581     /// ```
582     pub MANUAL_FIND_MAP,
583     complexity,
584     "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
585 }
586 
587 declare_clippy_lint! {
588     /// ### What it does
589     /// Checks for usage of `_.filter_map(_).next()`.
590     ///
591     /// ### Why is this bad?
592     /// Readability, this can be written more concisely as
593     /// `_.find_map(_)`.
594     ///
595     /// ### Example
596     /// ```rust
597     ///  (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
598     /// ```
599     /// Can be written as
600     ///
601     /// ```rust
602     ///  (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
603     /// ```
604     pub FILTER_MAP_NEXT,
605     pedantic,
606     "using combination of `filter_map` and `next` which can usually be written as a single method call"
607 }
608 
609 declare_clippy_lint! {
610     /// ### What it does
611     /// Checks for usage of `flat_map(|x| x)`.
612     ///
613     /// ### Why is this bad?
614     /// Readability, this can be written more concisely by using `flatten`.
615     ///
616     /// ### Example
617     /// ```rust
618     /// # let iter = vec![vec![0]].into_iter();
619     /// iter.flat_map(|x| x);
620     /// ```
621     /// Can be written as
622     /// ```rust
623     /// # let iter = vec![vec![0]].into_iter();
624     /// iter.flatten();
625     /// ```
626     pub FLAT_MAP_IDENTITY,
627     complexity,
628     "call to `flat_map` where `flatten` is sufficient"
629 }
630 
631 declare_clippy_lint! {
632     /// ### What it does
633     /// Checks for an iterator or string search (such as `find()`,
634     /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
635     ///
636     /// ### Why is this bad?
637     /// Readability, this can be written more concisely as:
638     /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
639     /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
640     ///
641     /// ### Example
642     /// ```rust
643     /// let vec = vec![1];
644     /// vec.iter().find(|x| **x == 0).is_some();
645     ///
646     /// let _ = "hello world".find("world").is_none();
647     /// ```
648     /// Could be written as
649     /// ```rust
650     /// let vec = vec![1];
651     /// vec.iter().any(|x| *x == 0);
652     ///
653     /// let _ = !"hello world".contains("world");
654     /// ```
655     pub SEARCH_IS_SOME,
656     complexity,
657     "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()`)"
658 }
659 
660 declare_clippy_lint! {
661     /// ### What it does
662     /// Checks for usage of `.chars().next()` on a `str` to check
663     /// if it starts with a given char.
664     ///
665     /// ### Why is this bad?
666     /// Readability, this can be written more concisely as
667     /// `_.starts_with(_)`.
668     ///
669     /// ### Example
670     /// ```rust
671     /// let name = "foo";
672     /// if name.chars().next() == Some('_') {};
673     /// ```
674     /// Could be written as
675     /// ```rust
676     /// let name = "foo";
677     /// if name.starts_with('_') {};
678     /// ```
679     pub CHARS_NEXT_CMP,
680     style,
681     "using `.chars().next()` to check if a string starts with a char"
682 }
683 
684 declare_clippy_lint! {
685     /// ### What it does
686     /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
687     /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
688     /// `unwrap_or_default` instead.
689     ///
690     /// ### Why is this bad?
691     /// The function will always be called and potentially
692     /// allocate an object acting as the default.
693     ///
694     /// ### Known problems
695     /// If the function has side-effects, not calling it will
696     /// change the semantic of the program, but you shouldn't rely on that anyway.
697     ///
698     /// ### Example
699     /// ```rust
700     /// # let foo = Some(String::new());
701     /// foo.unwrap_or(String::new());
702     /// ```
703     /// this can instead be written:
704     /// ```rust
705     /// # let foo = Some(String::new());
706     /// foo.unwrap_or_else(String::new);
707     /// ```
708     /// or
709     /// ```rust
710     /// # let foo = Some(String::new());
711     /// foo.unwrap_or_default();
712     /// ```
713     pub OR_FUN_CALL,
714     perf,
715     "using any `*or` method with a function call, which suggests `*or_else`"
716 }
717 
718 declare_clippy_lint! {
719     /// ### What it does
720     /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
721     /// etc., and suggests to use `unwrap_or_else` instead
722     ///
723     /// ### Why is this bad?
724     /// The function will always be called.
725     ///
726     /// ### Known problems
727     /// If the function has side-effects, not calling it will
728     /// change the semantics of the program, but you shouldn't rely on that anyway.
729     ///
730     /// ### Example
731     /// ```rust
732     /// # let foo = Some(String::new());
733     /// # let err_code = "418";
734     /// # let err_msg = "I'm a teapot";
735     /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
736     /// ```
737     /// or
738     /// ```rust
739     /// # let foo = Some(String::new());
740     /// # let err_code = "418";
741     /// # let err_msg = "I'm a teapot";
742     /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
743     /// ```
744     /// this can instead be written:
745     /// ```rust
746     /// # let foo = Some(String::new());
747     /// # let err_code = "418";
748     /// # let err_msg = "I'm a teapot";
749     /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
750     /// ```
751     pub EXPECT_FUN_CALL,
752     perf,
753     "using any `expect` method with a function call"
754 }
755 
756 declare_clippy_lint! {
757     /// ### What it does
758     /// Checks for usage of `.clone()` on a `Copy` type.
759     ///
760     /// ### Why is this bad?
761     /// The only reason `Copy` types implement `Clone` is for
762     /// generics, not for using the `clone` method on a concrete type.
763     ///
764     /// ### Example
765     /// ```rust
766     /// 42u64.clone();
767     /// ```
768     pub CLONE_ON_COPY,
769     complexity,
770     "using `clone` on a `Copy` type"
771 }
772 
773 declare_clippy_lint! {
774     /// ### What it does
775     /// Checks for usage of `.clone()` on a ref-counted pointer,
776     /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
777     /// function syntax instead (e.g., `Rc::clone(foo)`).
778     ///
779     /// ### Why is this bad?
780     /// Calling '.clone()' on an Rc, Arc, or Weak
781     /// can obscure the fact that only the pointer is being cloned, not the underlying
782     /// data.
783     ///
784     /// ### Example
785     /// ```rust
786     /// # use std::rc::Rc;
787     /// let x = Rc::new(1);
788     ///
789     /// // Bad
790     /// x.clone();
791     ///
792     /// // Good
793     /// Rc::clone(&x);
794     /// ```
795     pub CLONE_ON_REF_PTR,
796     restriction,
797     "using 'clone' on a ref-counted pointer"
798 }
799 
800 declare_clippy_lint! {
801     /// ### What it does
802     /// Checks for usage of `.clone()` on an `&&T`.
803     ///
804     /// ### Why is this bad?
805     /// Cloning an `&&T` copies the inner `&T`, instead of
806     /// cloning the underlying `T`.
807     ///
808     /// ### Example
809     /// ```rust
810     /// fn main() {
811     ///     let x = vec![1];
812     ///     let y = &&x;
813     ///     let z = y.clone();
814     ///     println!("{:p} {:p}", *y, z); // prints out the same pointer
815     /// }
816     /// ```
817     pub CLONE_DOUBLE_REF,
818     correctness,
819     "using `clone` on `&&T`"
820 }
821 
822 declare_clippy_lint! {
823     /// ### What it does
824     /// Checks for usage of `.to_string()` on an `&&T` where
825     /// `T` implements `ToString` directly (like `&&str` or `&&String`).
826     ///
827     /// ### Why is this bad?
828     /// This bypasses the specialized implementation of
829     /// `ToString` and instead goes through the more expensive string formatting
830     /// facilities.
831     ///
832     /// ### Example
833     /// ```rust
834     /// // Generic implementation for `T: Display` is used (slow)
835     /// ["foo", "bar"].iter().map(|s| s.to_string());
836     ///
837     /// // OK, the specialized impl is used
838     /// ["foo", "bar"].iter().map(|&s| s.to_string());
839     /// ```
840     pub INEFFICIENT_TO_STRING,
841     pedantic,
842     "using `to_string` on `&&T` where `T: ToString`"
843 }
844 
845 declare_clippy_lint! {
846     /// ### What it does
847     /// Checks for `new` not returning a type that contains `Self`.
848     ///
849     /// ### Why is this bad?
850     /// As a convention, `new` methods are used to make a new
851     /// instance of a type.
852     ///
853     /// ### Example
854     /// In an impl block:
855     /// ```rust
856     /// # struct Foo;
857     /// # struct NotAFoo;
858     /// impl Foo {
859     ///     fn new() -> NotAFoo {
860     /// # NotAFoo
861     ///     }
862     /// }
863     /// ```
864     ///
865     /// ```rust
866     /// # struct Foo;
867     /// struct Bar(Foo);
868     /// impl Foo {
869     ///     // Bad. The type name must contain `Self`
870     ///     fn new() -> Bar {
871     /// # Bar(Foo)
872     ///     }
873     /// }
874     /// ```
875     ///
876     /// ```rust
877     /// # struct Foo;
878     /// # struct FooError;
879     /// impl Foo {
880     ///     // Good. Return type contains `Self`
881     ///     fn new() -> Result<Foo, FooError> {
882     /// # Ok(Foo)
883     ///     }
884     /// }
885     /// ```
886     ///
887     /// Or in a trait definition:
888     /// ```rust
889     /// pub trait Trait {
890     ///     // Bad. The type name must contain `Self`
891     ///     fn new();
892     /// }
893     /// ```
894     ///
895     /// ```rust
896     /// pub trait Trait {
897     ///     // Good. Return type contains `Self`
898     ///     fn new() -> Self;
899     /// }
900     /// ```
901     pub NEW_RET_NO_SELF,
902     style,
903     "not returning type containing `Self` in a `new` method"
904 }
905 
906 declare_clippy_lint! {
907     /// ### What it does
908     /// Checks for string methods that receive a single-character
909     /// `str` as an argument, e.g., `_.split("x")`.
910     ///
911     /// ### Why is this bad?
912     /// Performing these methods using a `char` is faster than
913     /// using a `str`.
914     ///
915     /// ### Known problems
916     /// Does not catch multi-byte unicode characters.
917     ///
918     /// ### Example
919     /// ```rust,ignore
920     /// // Bad
921     /// _.split("x");
922     ///
923     /// // Good
924     /// _.split('x');
925     pub SINGLE_CHAR_PATTERN,
926     perf,
927     "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
928 }
929 
930 declare_clippy_lint! {
931     /// ### What it does
932     /// Checks for calling `.step_by(0)` on iterators which panics.
933     ///
934     /// ### Why is this bad?
935     /// This very much looks like an oversight. Use `panic!()` instead if you
936     /// actually intend to panic.
937     ///
938     /// ### Example
939     /// ```rust,should_panic
940     /// for x in (0..100).step_by(0) {
941     ///     //..
942     /// }
943     /// ```
944     pub ITERATOR_STEP_BY_ZERO,
945     correctness,
946     "using `Iterator::step_by(0)`, which will panic at runtime"
947 }
948 
949 declare_clippy_lint! {
950     /// ### What it does
951     /// Checks for indirect collection of populated `Option`
952     ///
953     /// ### Why is this bad?
954     /// `Option` is like a collection of 0-1 things, so `flatten`
955     /// automatically does this without suspicious-looking `unwrap` calls.
956     ///
957     /// ### Example
958     /// ```rust
959     /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
960     /// ```
961     /// Use instead:
962     /// ```rust
963     /// let _ = std::iter::empty::<Option<i32>>().flatten();
964     /// ```
965     pub OPTION_FILTER_MAP,
966     complexity,
967     "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
968 }
969 
970 declare_clippy_lint! {
971     /// ### What it does
972     /// Checks for the use of `iter.nth(0)`.
973     ///
974     /// ### Why is this bad?
975     /// `iter.next()` is equivalent to
976     /// `iter.nth(0)`, as they both consume the next element,
977     ///  but is more readable.
978     ///
979     /// ### Example
980     /// ```rust
981     /// # use std::collections::HashSet;
982     /// // Bad
983     /// # let mut s = HashSet::new();
984     /// # s.insert(1);
985     /// let x = s.iter().nth(0);
986     ///
987     /// // Good
988     /// # let mut s = HashSet::new();
989     /// # s.insert(1);
990     /// let x = s.iter().next();
991     /// ```
992     pub ITER_NTH_ZERO,
993     style,
994     "replace `iter.nth(0)` with `iter.next()`"
995 }
996 
997 declare_clippy_lint! {
998     /// ### What it does
999     /// Checks for use of `.iter().nth()` (and the related
1000     /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1001     ///
1002     /// ### Why is this bad?
1003     /// `.get()` and `.get_mut()` are more efficient and more
1004     /// readable.
1005     ///
1006     /// ### Example
1007     /// ```rust
1008     /// let some_vec = vec![0, 1, 2, 3];
1009     /// let bad_vec = some_vec.iter().nth(3);
1010     /// let bad_slice = &some_vec[..].iter().nth(3);
1011     /// ```
1012     /// The correct use would be:
1013     /// ```rust
1014     /// let some_vec = vec![0, 1, 2, 3];
1015     /// let bad_vec = some_vec.get(3);
1016     /// let bad_slice = &some_vec[..].get(3);
1017     /// ```
1018     pub ITER_NTH,
1019     perf,
1020     "using `.iter().nth()` on a standard library type with O(1) element access"
1021 }
1022 
1023 declare_clippy_lint! {
1024     /// ### What it does
1025     /// Checks for use of `.skip(x).next()` on iterators.
1026     ///
1027     /// ### Why is this bad?
1028     /// `.nth(x)` is cleaner
1029     ///
1030     /// ### Example
1031     /// ```rust
1032     /// let some_vec = vec![0, 1, 2, 3];
1033     /// let bad_vec = some_vec.iter().skip(3).next();
1034     /// let bad_slice = &some_vec[..].iter().skip(3).next();
1035     /// ```
1036     /// The correct use would be:
1037     /// ```rust
1038     /// let some_vec = vec![0, 1, 2, 3];
1039     /// let bad_vec = some_vec.iter().nth(3);
1040     /// let bad_slice = &some_vec[..].iter().nth(3);
1041     /// ```
1042     pub ITER_SKIP_NEXT,
1043     style,
1044     "using `.skip(x).next()` on an iterator"
1045 }
1046 
1047 declare_clippy_lint! {
1048     /// ### What it does
1049     /// Checks for use of `.get().unwrap()` (or
1050     /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1051     ///
1052     /// ### Why is this bad?
1053     /// Using the Index trait (`[]`) is more clear and more
1054     /// concise.
1055     ///
1056     /// ### Known problems
1057     /// Not a replacement for error handling: Using either
1058     /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1059     /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1060     /// temporary placeholder for dealing with the `Option` type, then this does
1061     /// not mitigate the need for error handling. If there is a chance that `.get()`
1062     /// will be `None` in your program, then it is advisable that the `None` case
1063     /// is handled in a future refactor instead of using `.unwrap()` or the Index
1064     /// trait.
1065     ///
1066     /// ### Example
1067     /// ```rust
1068     /// let mut some_vec = vec![0, 1, 2, 3];
1069     /// let last = some_vec.get(3).unwrap();
1070     /// *some_vec.get_mut(0).unwrap() = 1;
1071     /// ```
1072     /// The correct use would be:
1073     /// ```rust
1074     /// let mut some_vec = vec![0, 1, 2, 3];
1075     /// let last = some_vec[3];
1076     /// some_vec[0] = 1;
1077     /// ```
1078     pub GET_UNWRAP,
1079     restriction,
1080     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1081 }
1082 
1083 declare_clippy_lint! {
1084     /// ### What it does
1085     /// Checks for occurrences where one vector gets extended instead of append
1086     ///
1087     /// ### Why is this bad?
1088     /// Using `append` instead of `extend` is more concise and faster
1089     ///
1090     /// ### Example
1091     /// ```rust
1092     /// let mut a = vec![1, 2, 3];
1093     /// let mut b = vec![4, 5, 6];
1094     ///
1095     /// // Bad
1096     /// a.extend(b.drain(..));
1097     ///
1098     /// // Good
1099     /// a.append(&mut b);
1100     /// ```
1101     pub EXTEND_WITH_DRAIN,
1102     perf,
1103     "using vec.append(&mut vec) to move the full range of a vecor to another"
1104 }
1105 
1106 declare_clippy_lint! {
1107     /// ### What it does
1108     /// Checks for the use of `.extend(s.chars())` where s is a
1109     /// `&str` or `String`.
1110     ///
1111     /// ### Why is this bad?
1112     /// `.push_str(s)` is clearer
1113     ///
1114     /// ### Example
1115     /// ```rust
1116     /// let abc = "abc";
1117     /// let def = String::from("def");
1118     /// let mut s = String::new();
1119     /// s.extend(abc.chars());
1120     /// s.extend(def.chars());
1121     /// ```
1122     /// The correct use would be:
1123     /// ```rust
1124     /// let abc = "abc";
1125     /// let def = String::from("def");
1126     /// let mut s = String::new();
1127     /// s.push_str(abc);
1128     /// s.push_str(&def);
1129     /// ```
1130     pub STRING_EXTEND_CHARS,
1131     style,
1132     "using `x.extend(s.chars())` where s is a `&str` or `String`"
1133 }
1134 
1135 declare_clippy_lint! {
1136     /// ### What it does
1137     /// Checks for the use of `.cloned().collect()` on slice to
1138     /// create a `Vec`.
1139     ///
1140     /// ### Why is this bad?
1141     /// `.to_vec()` is clearer
1142     ///
1143     /// ### Example
1144     /// ```rust
1145     /// let s = [1, 2, 3, 4, 5];
1146     /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1147     /// ```
1148     /// The better use would be:
1149     /// ```rust
1150     /// let s = [1, 2, 3, 4, 5];
1151     /// let s2: Vec<isize> = s.to_vec();
1152     /// ```
1153     pub ITER_CLONED_COLLECT,
1154     style,
1155     "using `.cloned().collect()` on slice to create a `Vec`"
1156 }
1157 
1158 declare_clippy_lint! {
1159     /// ### What it does
1160     /// Checks for usage of `_.chars().last()` or
1161     /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1162     ///
1163     /// ### Why is this bad?
1164     /// Readability, this can be written more concisely as
1165     /// `_.ends_with(_)`.
1166     ///
1167     /// ### Example
1168     /// ```rust
1169     /// # let name = "_";
1170     ///
1171     /// // Bad
1172     /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1173     ///
1174     /// // Good
1175     /// name.ends_with('_') || name.ends_with('-');
1176     /// ```
1177     pub CHARS_LAST_CMP,
1178     style,
1179     "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1180 }
1181 
1182 declare_clippy_lint! {
1183     /// ### What it does
1184     /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1185     /// types before and after the call are the same.
1186     ///
1187     /// ### Why is this bad?
1188     /// The call is unnecessary.
1189     ///
1190     /// ### Example
1191     /// ```rust
1192     /// # fn do_stuff(x: &[i32]) {}
1193     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1194     /// do_stuff(x.as_ref());
1195     /// ```
1196     /// The correct use would be:
1197     /// ```rust
1198     /// # fn do_stuff(x: &[i32]) {}
1199     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1200     /// do_stuff(x);
1201     /// ```
1202     pub USELESS_ASREF,
1203     complexity,
1204     "using `as_ref` where the types before and after the call are the same"
1205 }
1206 
1207 declare_clippy_lint! {
1208     /// ### What it does
1209     /// Checks for using `fold` when a more succinct alternative exists.
1210     /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1211     /// `sum` or `product`.
1212     ///
1213     /// ### Why is this bad?
1214     /// Readability.
1215     ///
1216     /// ### Example
1217     /// ```rust
1218     /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1219     /// ```
1220     /// This could be written as:
1221     /// ```rust
1222     /// let _ = (0..3).any(|x| x > 2);
1223     /// ```
1224     pub UNNECESSARY_FOLD,
1225     style,
1226     "using `fold` when a more succinct alternative exists"
1227 }
1228 
1229 declare_clippy_lint! {
1230     /// ### What it does
1231     /// Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1232     /// More specifically it checks if the closure provided is only performing one of the
1233     /// filter or map operations and suggests the appropriate option.
1234     ///
1235     /// ### Why is this bad?
1236     /// Complexity. The intent is also clearer if only a single
1237     /// operation is being performed.
1238     ///
1239     /// ### Example
1240     /// ```rust
1241     /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1242     ///
1243     /// // As there is no transformation of the argument this could be written as:
1244     /// let _ = (0..3).filter(|&x| x > 2);
1245     /// ```
1246     ///
1247     /// ```rust
1248     /// let _ = (0..4).filter_map(|x| Some(x + 1));
1249     ///
1250     /// // As there is no conditional check on the argument this could be written as:
1251     /// let _ = (0..4).map(|x| x + 1);
1252     /// ```
1253     pub UNNECESSARY_FILTER_MAP,
1254     complexity,
1255     "using `filter_map` when a more succinct alternative exists"
1256 }
1257 
1258 declare_clippy_lint! {
1259     /// ### What it does
1260     /// Checks for `into_iter` calls on references which should be replaced by `iter`
1261     /// or `iter_mut`.
1262     ///
1263     /// ### Why is this bad?
1264     /// Readability. Calling `into_iter` on a reference will not move out its
1265     /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1266     /// `iter_mut` directly.
1267     ///
1268     /// ### Example
1269     /// ```rust
1270     /// // Bad
1271     /// let _ = (&vec![3, 4, 5]).into_iter();
1272     ///
1273     /// // Good
1274     /// let _ = (&vec![3, 4, 5]).iter();
1275     /// ```
1276     pub INTO_ITER_ON_REF,
1277     style,
1278     "using `.into_iter()` on a reference"
1279 }
1280 
1281 declare_clippy_lint! {
1282     /// ### What it does
1283     /// Checks for calls to `map` followed by a `count`.
1284     ///
1285     /// ### Why is this bad?
1286     /// It looks suspicious. Maybe `map` was confused with `filter`.
1287     /// If the `map` call is intentional, this should be rewritten
1288     /// using `inspect`. Or, if you intend to drive the iterator to
1289     /// completion, you can just use `for_each` instead.
1290     ///
1291     /// ### Example
1292     /// ```rust
1293     /// let _ = (0..3).map(|x| x + 2).count();
1294     /// ```
1295     pub SUSPICIOUS_MAP,
1296     suspicious,
1297     "suspicious usage of map"
1298 }
1299 
1300 declare_clippy_lint! {
1301     /// ### What it does
1302     /// Checks for `MaybeUninit::uninit().assume_init()`.
1303     ///
1304     /// ### Why is this bad?
1305     /// For most types, this is undefined behavior.
1306     ///
1307     /// ### Known problems
1308     /// For now, we accept empty tuples and tuples / arrays
1309     /// of `MaybeUninit`. There may be other types that allow uninitialized
1310     /// data, but those are not yet rigorously defined.
1311     ///
1312     /// ### Example
1313     /// ```rust
1314     /// // Beware the UB
1315     /// use std::mem::MaybeUninit;
1316     ///
1317     /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1318     /// ```
1319     ///
1320     /// Note that the following is OK:
1321     ///
1322     /// ```rust
1323     /// use std::mem::MaybeUninit;
1324     ///
1325     /// let _: [MaybeUninit<bool>; 5] = unsafe {
1326     ///     MaybeUninit::uninit().assume_init()
1327     /// };
1328     /// ```
1329     pub UNINIT_ASSUMED_INIT,
1330     correctness,
1331     "`MaybeUninit::uninit().assume_init()`"
1332 }
1333 
1334 declare_clippy_lint! {
1335     /// ### What it does
1336     /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1337     ///
1338     /// ### Why is this bad?
1339     /// These can be written simply with `saturating_add/sub` methods.
1340     ///
1341     /// ### Example
1342     /// ```rust
1343     /// # let y: u32 = 0;
1344     /// # let x: u32 = 100;
1345     /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1346     /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1347     /// ```
1348     ///
1349     /// can be written using dedicated methods for saturating addition/subtraction as:
1350     ///
1351     /// ```rust
1352     /// # let y: u32 = 0;
1353     /// # let x: u32 = 100;
1354     /// let add = x.saturating_add(y);
1355     /// let sub = x.saturating_sub(y);
1356     /// ```
1357     pub MANUAL_SATURATING_ARITHMETIC,
1358     style,
1359     "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1360 }
1361 
1362 declare_clippy_lint! {
1363     /// ### What it does
1364     /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1365     /// zero-sized types
1366     ///
1367     /// ### Why is this bad?
1368     /// This is a no-op, and likely unintended
1369     ///
1370     /// ### Example
1371     /// ```rust
1372     /// unsafe { (&() as *const ()).offset(1) };
1373     /// ```
1374     pub ZST_OFFSET,
1375     correctness,
1376     "Check for offset calculations on raw pointers to zero-sized types"
1377 }
1378 
1379 declare_clippy_lint! {
1380     /// ### What it does
1381     /// Checks for `FileType::is_file()`.
1382     ///
1383     /// ### Why is this bad?
1384     /// When people testing a file type with `FileType::is_file`
1385     /// they are testing whether a path is something they can get bytes from. But
1386     /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1387     /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1388     ///
1389     /// ### Example
1390     /// ```rust
1391     /// # || {
1392     /// let metadata = std::fs::metadata("foo.txt")?;
1393     /// let filetype = metadata.file_type();
1394     ///
1395     /// if filetype.is_file() {
1396     ///     // read file
1397     /// }
1398     /// # Ok::<_, std::io::Error>(())
1399     /// # };
1400     /// ```
1401     ///
1402     /// should be written as:
1403     ///
1404     /// ```rust
1405     /// # || {
1406     /// let metadata = std::fs::metadata("foo.txt")?;
1407     /// let filetype = metadata.file_type();
1408     ///
1409     /// if !filetype.is_dir() {
1410     ///     // read file
1411     /// }
1412     /// # Ok::<_, std::io::Error>(())
1413     /// # };
1414     /// ```
1415     pub FILETYPE_IS_FILE,
1416     restriction,
1417     "`FileType::is_file` is not recommended to test for readable file type"
1418 }
1419 
1420 declare_clippy_lint! {
1421     /// ### What it does
1422     /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1423     ///
1424     /// ### Why is this bad?
1425     /// Readability, this can be written more concisely as
1426     /// `_.as_deref()`.
1427     ///
1428     /// ### Example
1429     /// ```rust
1430     /// # let opt = Some("".to_string());
1431     /// opt.as_ref().map(String::as_str)
1432     /// # ;
1433     /// ```
1434     /// Can be written as
1435     /// ```rust
1436     /// # let opt = Some("".to_string());
1437     /// opt.as_deref()
1438     /// # ;
1439     /// ```
1440     pub OPTION_AS_REF_DEREF,
1441     complexity,
1442     "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1443 }
1444 
1445 declare_clippy_lint! {
1446     /// ### What it does
1447     /// Checks for usage of `iter().next()` on a Slice or an Array
1448     ///
1449     /// ### Why is this bad?
1450     /// These can be shortened into `.get()`
1451     ///
1452     /// ### Example
1453     /// ```rust
1454     /// # let a = [1, 2, 3];
1455     /// # let b = vec![1, 2, 3];
1456     /// a[2..].iter().next();
1457     /// b.iter().next();
1458     /// ```
1459     /// should be written as:
1460     /// ```rust
1461     /// # let a = [1, 2, 3];
1462     /// # let b = vec![1, 2, 3];
1463     /// a.get(2);
1464     /// b.get(0);
1465     /// ```
1466     pub ITER_NEXT_SLICE,
1467     style,
1468     "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1469 }
1470 
1471 declare_clippy_lint! {
1472     /// ### What it does
1473     /// Warns when using `push_str`/`insert_str` with a single-character string literal
1474     /// where `push`/`insert` with a `char` would work fine.
1475     ///
1476     /// ### Why is this bad?
1477     /// It's less clear that we are pushing a single character.
1478     ///
1479     /// ### Example
1480     /// ```rust
1481     /// let mut string = String::new();
1482     /// string.insert_str(0, "R");
1483     /// string.push_str("R");
1484     /// ```
1485     /// Could be written as
1486     /// ```rust
1487     /// let mut string = String::new();
1488     /// string.insert(0, 'R');
1489     /// string.push('R');
1490     /// ```
1491     pub SINGLE_CHAR_ADD_STR,
1492     style,
1493     "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1494 }
1495 
1496 declare_clippy_lint! {
1497     /// ### What it does
1498     /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1499     /// lazily evaluated closures on `Option` and `Result`.
1500     ///
1501     /// This lint suggests changing the following functions, when eager evaluation results in
1502     /// simpler code:
1503     ///  - `unwrap_or_else` to `unwrap_or`
1504     ///  - `and_then` to `and`
1505     ///  - `or_else` to `or`
1506     ///  - `get_or_insert_with` to `get_or_insert`
1507     ///  - `ok_or_else` to `ok_or`
1508     ///
1509     /// ### Why is this bad?
1510     /// Using eager evaluation is shorter and simpler in some cases.
1511     ///
1512     /// ### Known problems
1513     /// It is possible, but not recommended for `Deref` and `Index` to have
1514     /// side effects. Eagerly evaluating them can change the semantics of the program.
1515     ///
1516     /// ### Example
1517     /// ```rust
1518     /// // example code where clippy issues a warning
1519     /// let opt: Option<u32> = None;
1520     ///
1521     /// opt.unwrap_or_else(|| 42);
1522     /// ```
1523     /// Use instead:
1524     /// ```rust
1525     /// let opt: Option<u32> = None;
1526     ///
1527     /// opt.unwrap_or(42);
1528     /// ```
1529     pub UNNECESSARY_LAZY_EVALUATIONS,
1530     style,
1531     "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1532 }
1533 
1534 declare_clippy_lint! {
1535     /// ### What it does
1536     /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1537     ///
1538     /// ### Why is this bad?
1539     /// Using `try_for_each` instead is more readable and idiomatic.
1540     ///
1541     /// ### Example
1542     /// ```rust
1543     /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1544     /// ```
1545     /// Use instead:
1546     /// ```rust
1547     /// (0..3).try_for_each(|t| Err(t));
1548     /// ```
1549     pub MAP_COLLECT_RESULT_UNIT,
1550     style,
1551     "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1552 }
1553 
1554 declare_clippy_lint! {
1555     /// ### What it does
1556     /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1557     /// trait.
1558     ///
1559     /// ### Why is this bad?
1560     /// It is recommended style to use collect. See
1561     /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1562     ///
1563     /// ### Example
1564     /// ```rust
1565     /// use std::iter::FromIterator;
1566     ///
1567     /// let five_fives = std::iter::repeat(5).take(5);
1568     ///
1569     /// let v = Vec::from_iter(five_fives);
1570     ///
1571     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1572     /// ```
1573     /// Use instead:
1574     /// ```rust
1575     /// let five_fives = std::iter::repeat(5).take(5);
1576     ///
1577     /// let v: Vec<i32> = five_fives.collect();
1578     ///
1579     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1580     /// ```
1581     pub FROM_ITER_INSTEAD_OF_COLLECT,
1582     pedantic,
1583     "use `.collect()` instead of `::from_iter()`"
1584 }
1585 
1586 declare_clippy_lint! {
1587     /// ### What it does
1588     /// Checks for usage of `inspect().for_each()`.
1589     ///
1590     /// ### Why is this bad?
1591     /// It is the same as performing the computation
1592     /// inside `inspect` at the beginning of the closure in `for_each`.
1593     ///
1594     /// ### Example
1595     /// ```rust
1596     /// [1,2,3,4,5].iter()
1597     /// .inspect(|&x| println!("inspect the number: {}", x))
1598     /// .for_each(|&x| {
1599     ///     assert!(x >= 0);
1600     /// });
1601     /// ```
1602     /// Can be written as
1603     /// ```rust
1604     /// [1,2,3,4,5].iter()
1605     /// .for_each(|&x| {
1606     ///     println!("inspect the number: {}", x);
1607     ///     assert!(x >= 0);
1608     /// });
1609     /// ```
1610     pub INSPECT_FOR_EACH,
1611     complexity,
1612     "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1613 }
1614 
1615 declare_clippy_lint! {
1616     /// ### What it does
1617     /// Checks for usage of `filter_map(|x| x)`.
1618     ///
1619     /// ### Why is this bad?
1620     /// Readability, this can be written more concisely by using `flatten`.
1621     ///
1622     /// ### Example
1623     /// ```rust
1624     /// # let iter = vec![Some(1)].into_iter();
1625     /// iter.filter_map(|x| x);
1626     /// ```
1627     /// Use instead:
1628     /// ```rust
1629     /// # let iter = vec![Some(1)].into_iter();
1630     /// iter.flatten();
1631     /// ```
1632     pub FILTER_MAP_IDENTITY,
1633     complexity,
1634     "call to `filter_map` where `flatten` is sufficient"
1635 }
1636 
1637 declare_clippy_lint! {
1638     /// ### What it does
1639     /// Checks for instances of `map(f)` where `f` is the identity function.
1640     ///
1641     /// ### Why is this bad?
1642     /// It can be written more concisely without the call to `map`.
1643     ///
1644     /// ### Example
1645     /// ```rust
1646     /// let x = [1, 2, 3];
1647     /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1648     /// ```
1649     /// Use instead:
1650     /// ```rust
1651     /// let x = [1, 2, 3];
1652     /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1653     /// ```
1654     pub MAP_IDENTITY,
1655     complexity,
1656     "using iterator.map(|x| x)"
1657 }
1658 
1659 declare_clippy_lint! {
1660     /// ### What it does
1661     /// Checks for the use of `.bytes().nth()`.
1662     ///
1663     /// ### Why is this bad?
1664     /// `.as_bytes().get()` is more efficient and more
1665     /// readable.
1666     ///
1667     /// ### Example
1668     /// ```rust
1669     /// // Bad
1670     /// let _ = "Hello".bytes().nth(3);
1671     ///
1672     /// // Good
1673     /// let _ = "Hello".as_bytes().get(3);
1674     /// ```
1675     pub BYTES_NTH,
1676     style,
1677     "replace `.bytes().nth()` with `.as_bytes().get()`"
1678 }
1679 
1680 declare_clippy_lint! {
1681     /// ### What it does
1682     /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1683     ///
1684     /// ### Why is this bad?
1685     /// These methods do the same thing as `_.clone()` but may be confusing as
1686     /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1687     ///
1688     /// ### Example
1689     /// ```rust
1690     /// let a = vec![1, 2, 3];
1691     /// let b = a.to_vec();
1692     /// let c = a.to_owned();
1693     /// ```
1694     /// Use instead:
1695     /// ```rust
1696     /// let a = vec![1, 2, 3];
1697     /// let b = a.clone();
1698     /// let c = a.clone();
1699     /// ```
1700     pub IMPLICIT_CLONE,
1701     pedantic,
1702     "implicitly cloning a value by invoking a function on its dereferenced type"
1703 }
1704 
1705 declare_clippy_lint! {
1706     /// ### What it does
1707     /// Checks for the use of `.iter().count()`.
1708     ///
1709     /// ### Why is this bad?
1710     /// `.len()` is more efficient and more
1711     /// readable.
1712     ///
1713     /// ### Example
1714     /// ```rust
1715     /// // Bad
1716     /// let some_vec = vec![0, 1, 2, 3];
1717     /// let _ = some_vec.iter().count();
1718     /// let _ = &some_vec[..].iter().count();
1719     ///
1720     /// // Good
1721     /// let some_vec = vec![0, 1, 2, 3];
1722     /// let _ = some_vec.len();
1723     /// let _ = &some_vec[..].len();
1724     /// ```
1725     pub ITER_COUNT,
1726     complexity,
1727     "replace `.iter().count()` with `.len()`"
1728 }
1729 
1730 declare_clippy_lint! {
1731     /// ### What it does
1732     /// Checks for calls to [`splitn`]
1733     /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1734     /// related functions with either zero or one splits.
1735     ///
1736     /// ### Why is this bad?
1737     /// These calls don't actually split the value and are
1738     /// likely to be intended as a different number.
1739     ///
1740     /// ### Example
1741     /// ```rust
1742     /// // Bad
1743     /// let s = "";
1744     /// for x in s.splitn(1, ":") {
1745     ///     // use x
1746     /// }
1747     ///
1748     /// // Good
1749     /// let s = "";
1750     /// for x in s.splitn(2, ":") {
1751     ///     // use x
1752     /// }
1753     /// ```
1754     pub SUSPICIOUS_SPLITN,
1755     correctness,
1756     "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
1757 }
1758 
1759 declare_clippy_lint! {
1760     /// ### What it does
1761     /// Checks for manual implementations of `str::repeat`
1762     ///
1763     /// ### Why is this bad?
1764     /// These are both harder to read, as well as less performant.
1765     ///
1766     /// ### Example
1767     /// ```rust
1768     /// // Bad
1769     /// let x: String = std::iter::repeat('x').take(10).collect();
1770     ///
1771     /// // Good
1772     /// let x: String = "x".repeat(10);
1773     /// ```
1774     pub MANUAL_STR_REPEAT,
1775     perf,
1776     "manual implementation of `str::repeat`"
1777 }
1778 
1779 declare_clippy_lint! {
1780     /// ### What it does
1781     /// Checks for usages of `str::splitn(2, _)`
1782     ///
1783     /// ### Why is this bad?
1784     /// `split_once` is both clearer in intent and slightly more efficient.
1785     ///
1786     /// ### Example
1787     /// ```rust,ignore
1788     /// // Bad
1789     ///  let (key, value) = _.splitn(2, '=').next_tuple()?;
1790     ///  let value = _.splitn(2, '=').nth(1)?;
1791     ///
1792     /// // Good
1793     /// let (key, value) = _.split_once('=')?;
1794     /// let value = _.split_once('=')?.1;
1795     /// ```
1796     pub MANUAL_SPLIT_ONCE,
1797     complexity,
1798     "replace `.splitn(2, pat)` with `.split_once(pat)`"
1799 }
1800 
1801 pub struct Methods {
1802     avoid_breaking_exported_api: bool,
1803     msrv: Option<RustcVersion>,
1804 }
1805 
1806 impl Methods {
1807     #[must_use]
new(avoid_breaking_exported_api: bool, msrv: Option<RustcVersion>) -> Self1808     pub fn new(avoid_breaking_exported_api: bool, msrv: Option<RustcVersion>) -> Self {
1809         Self {
1810             avoid_breaking_exported_api,
1811             msrv,
1812         }
1813     }
1814 }
1815 
1816 impl_lint_pass!(Methods => [
1817     UNWRAP_USED,
1818     EXPECT_USED,
1819     SHOULD_IMPLEMENT_TRAIT,
1820     WRONG_SELF_CONVENTION,
1821     OK_EXPECT,
1822     UNWRAP_OR_ELSE_DEFAULT,
1823     MAP_UNWRAP_OR,
1824     RESULT_MAP_OR_INTO_OPTION,
1825     OPTION_MAP_OR_NONE,
1826     BIND_INSTEAD_OF_MAP,
1827     OR_FUN_CALL,
1828     EXPECT_FUN_CALL,
1829     CHARS_NEXT_CMP,
1830     CHARS_LAST_CMP,
1831     CLONE_ON_COPY,
1832     CLONE_ON_REF_PTR,
1833     CLONE_DOUBLE_REF,
1834     CLONED_INSTEAD_OF_COPIED,
1835     FLAT_MAP_OPTION,
1836     INEFFICIENT_TO_STRING,
1837     NEW_RET_NO_SELF,
1838     SINGLE_CHAR_PATTERN,
1839     SINGLE_CHAR_ADD_STR,
1840     SEARCH_IS_SOME,
1841     FILTER_NEXT,
1842     SKIP_WHILE_NEXT,
1843     FILTER_MAP_IDENTITY,
1844     MAP_IDENTITY,
1845     MANUAL_FILTER_MAP,
1846     MANUAL_FIND_MAP,
1847     OPTION_FILTER_MAP,
1848     FILTER_MAP_NEXT,
1849     FLAT_MAP_IDENTITY,
1850     MAP_FLATTEN,
1851     ITERATOR_STEP_BY_ZERO,
1852     ITER_NEXT_SLICE,
1853     ITER_COUNT,
1854     ITER_NTH,
1855     ITER_NTH_ZERO,
1856     BYTES_NTH,
1857     ITER_SKIP_NEXT,
1858     GET_UNWRAP,
1859     STRING_EXTEND_CHARS,
1860     ITER_CLONED_COLLECT,
1861     USELESS_ASREF,
1862     UNNECESSARY_FOLD,
1863     UNNECESSARY_FILTER_MAP,
1864     INTO_ITER_ON_REF,
1865     SUSPICIOUS_MAP,
1866     UNINIT_ASSUMED_INIT,
1867     MANUAL_SATURATING_ARITHMETIC,
1868     ZST_OFFSET,
1869     FILETYPE_IS_FILE,
1870     OPTION_AS_REF_DEREF,
1871     UNNECESSARY_LAZY_EVALUATIONS,
1872     MAP_COLLECT_RESULT_UNIT,
1873     FROM_ITER_INSTEAD_OF_COLLECT,
1874     INSPECT_FOR_EACH,
1875     IMPLICIT_CLONE,
1876     SUSPICIOUS_SPLITN,
1877     MANUAL_STR_REPEAT,
1878     EXTEND_WITH_DRAIN,
1879     MANUAL_SPLIT_ONCE
1880 ]);
1881 
1882 /// Extracts a method call name, args, and `Span` of the method name.
method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(SymbolStr, &'tcx [hir::Expr<'tcx>], Span)>1883 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(SymbolStr, &'tcx [hir::Expr<'tcx>], Span)> {
1884     if let ExprKind::MethodCall(path, span, args, _) = recv.kind {
1885         if !args.iter().any(|e| e.span.from_expansion()) {
1886             return Some((path.ident.name.as_str(), args, span));
1887         }
1888     }
1889     None
1890 }
1891 
1892 /// Same as `method_call` but the `SymbolStr` is dereferenced into a temporary `&str`
1893 macro_rules! method_call {
1894     ($expr:expr) => {
1895         method_call($expr)
1896             .as_ref()
1897             .map(|&(ref name, args, span)| (&**name, args, span))
1898     };
1899 }
1900 
1901 impl<'tcx> LateLintPass<'tcx> for Methods {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>)1902     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1903         if in_macro(expr.span) {
1904             return;
1905         }
1906 
1907         check_methods(cx, expr, self.msrv.as_ref());
1908 
1909         match expr.kind {
1910             hir::ExprKind::Call(func, args) => {
1911                 from_iter_instead_of_collect::check(cx, expr, args, func);
1912             },
1913             hir::ExprKind::MethodCall(method_call, ref method_span, args, _) => {
1914                 or_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1915                 expect_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1916                 clone_on_copy::check(cx, expr, method_call.ident.name, args);
1917                 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
1918                 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
1919                 single_char_add_str::check(cx, expr, args);
1920                 into_iter_on_ref::check(cx, expr, *method_span, method_call.ident.name, args);
1921                 single_char_pattern::check(cx, expr, method_call.ident.name, args);
1922             },
1923             hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
1924                 let mut info = BinaryExprInfo {
1925                     expr,
1926                     chain: lhs,
1927                     other: rhs,
1928                     eq: op.node == hir::BinOpKind::Eq,
1929                 };
1930                 lint_binary_expr_with_method_call(cx, &mut info);
1931             },
1932             _ => (),
1933         }
1934     }
1935 
1936     #[allow(clippy::too_many_lines)]
check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>)1937     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1938         if in_external_macro(cx.sess(), impl_item.span) {
1939             return;
1940         }
1941         let name = impl_item.ident.name.as_str();
1942         let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
1943         let item = cx.tcx.hir().expect_item(parent);
1944         let self_ty = cx.tcx.type_of(item.def_id);
1945 
1946         let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
1947         if_chain! {
1948             if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1949             if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
1950 
1951             let method_sig = cx.tcx.fn_sig(impl_item.def_id);
1952             let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1953 
1954             let first_arg_ty = &method_sig.inputs().iter().next();
1955 
1956             // check conventions w.r.t. conversion method names and predicates
1957             if let Some(first_arg_ty) = first_arg_ty;
1958 
1959             then {
1960                 // if this impl block implements a trait, lint in trait definition instead
1961                 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
1962                     // check missing trait implementations
1963                     for method_config in &TRAIT_METHODS {
1964                         if name == method_config.method_name &&
1965                             sig.decl.inputs.len() == method_config.param_count &&
1966                             method_config.output_type.matches(&sig.decl.output) &&
1967                             method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1968                             fn_header_equals(method_config.fn_header, sig.header) &&
1969                             method_config.lifetime_param_cond(impl_item)
1970                         {
1971                             span_lint_and_help(
1972                                 cx,
1973                                 SHOULD_IMPLEMENT_TRAIT,
1974                                 impl_item.span,
1975                                 &format!(
1976                                     "method `{}` can be confused for the standard trait method `{}::{}`",
1977                                     method_config.method_name,
1978                                     method_config.trait_name,
1979                                     method_config.method_name
1980                                 ),
1981                                 None,
1982                                 &format!(
1983                                     "consider implementing the trait `{}` or choosing a less ambiguous method name",
1984                                     method_config.trait_name
1985                                 )
1986                             );
1987                         }
1988                     }
1989                 }
1990 
1991                 if sig.decl.implicit_self.has_implicit_self()
1992                     && !(self.avoid_breaking_exported_api
1993                         && cx.access_levels.is_exported(impl_item.def_id))
1994                 {
1995                     wrong_self_convention::check(
1996                         cx,
1997                         &name,
1998                         self_ty,
1999                         first_arg_ty,
2000                         first_arg.pat.span,
2001                         implements_trait,
2002                         false
2003                     );
2004                 }
2005             }
2006         }
2007 
2008         // if this impl block implements a trait, lint in trait definition instead
2009         if implements_trait {
2010             return;
2011         }
2012 
2013         if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2014             let ret_ty = return_ty(cx, impl_item.hir_id());
2015 
2016             // walk the return type and check for Self (this does not check associated types)
2017             if let Some(self_adt) = self_ty.ty_adt_def() {
2018                 if contains_adt_constructor(cx.tcx, ret_ty, self_adt) {
2019                     return;
2020                 }
2021             } else if contains_ty(cx.tcx, ret_ty, self_ty) {
2022                 return;
2023             }
2024 
2025             // if return type is impl trait, check the associated types
2026             if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2027                 // one of the associated types must be Self
2028                 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2029                     if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2030                         // walk the associated type and check for Self
2031                         if let Some(self_adt) = self_ty.ty_adt_def() {
2032                             if contains_adt_constructor(cx.tcx, projection_predicate.ty, self_adt) {
2033                                 return;
2034                             }
2035                         } else if contains_ty(cx.tcx, projection_predicate.ty, self_ty) {
2036                             return;
2037                         }
2038                     }
2039                 }
2040             }
2041 
2042             if name == "new" && !TyS::same_type(ret_ty, self_ty) {
2043                 span_lint(
2044                     cx,
2045                     NEW_RET_NO_SELF,
2046                     impl_item.span,
2047                     "methods called `new` usually return `Self`",
2048                 );
2049             }
2050         }
2051     }
2052 
check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>)2053     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2054         if in_external_macro(cx.tcx.sess, item.span) {
2055             return;
2056         }
2057 
2058         if_chain! {
2059             if let TraitItemKind::Fn(ref sig, _) = item.kind;
2060             if sig.decl.implicit_self.has_implicit_self();
2061             if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2062 
2063             then {
2064                 let first_arg_span = first_arg_ty.span;
2065                 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2066                 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2067                 wrong_self_convention::check(
2068                     cx,
2069                     &item.ident.name.as_str(),
2070                     self_ty,
2071                     first_arg_ty,
2072                     first_arg_span,
2073                     false,
2074                     true
2075                 );
2076             }
2077         }
2078 
2079         if_chain! {
2080             if item.ident.name == sym::new;
2081             if let TraitItemKind::Fn(_, _) = item.kind;
2082             let ret_ty = return_ty(cx, item.hir_id());
2083             let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2084             if !contains_ty(cx.tcx, ret_ty, self_ty);
2085 
2086             then {
2087                 span_lint(
2088                     cx,
2089                     NEW_RET_NO_SELF,
2090                     item.span,
2091                     "methods called `new` usually return `Self`",
2092                 );
2093             }
2094         }
2095     }
2096 
2097     extract_msrv_attr!(LateContext);
2098 }
2099 
2100 #[allow(clippy::too_many_lines)]
check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Option<&RustcVersion>)2101 fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Option<&RustcVersion>) {
2102     if let Some((name, [recv, args @ ..], span)) = method_call!(expr) {
2103         match (name, args) {
2104             ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2105                 zst_offset::check(cx, expr, recv);
2106             },
2107             ("and_then", [arg]) => {
2108                 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2109                 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2110                 if !biom_option_linted && !biom_result_linted {
2111                     unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2112                 }
2113             },
2114             ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2115             ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2116             ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2117             ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, msrv),
2118             ("collect", []) => match method_call!(recv) {
2119                 Some(("cloned", [recv2], _)) => iter_cloned_collect::check(cx, expr, recv2),
2120                 Some(("map", [m_recv, m_arg], _)) => {
2121                     map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2122                 },
2123                 Some(("take", [take_self_arg, take_arg], _)) => {
2124                     if meets_msrv(msrv, &msrvs::STR_REPEAT) {
2125                         manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2126                     }
2127                 },
2128                 _ => {},
2129             },
2130             ("count", []) => match method_call!(recv) {
2131                 Some((name @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2132                     iter_count::check(cx, expr, recv2, name);
2133                 },
2134                 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2135                 _ => {},
2136             },
2137             ("expect", [_]) => match method_call!(recv) {
2138                 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2139                 _ => expect_used::check(cx, expr, recv),
2140             },
2141             ("extend", [arg]) => {
2142                 string_extend_chars::check(cx, expr, recv, arg);
2143                 extend_with_drain::check(cx, expr, recv, arg);
2144             },
2145             ("filter_map", [arg]) => {
2146                 unnecessary_filter_map::check(cx, expr, arg);
2147                 filter_map_identity::check(cx, expr, arg, span);
2148             },
2149             ("flat_map", [arg]) => {
2150                 flat_map_identity::check(cx, expr, arg, span);
2151                 flat_map_option::check(cx, expr, arg, span);
2152             },
2153             ("flatten", []) => {
2154                 if let Some(("map", [recv, map_arg], _)) = method_call!(recv) {
2155                     map_flatten::check(cx, expr, recv, map_arg);
2156                 }
2157             },
2158             ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2159             ("for_each", [_]) => {
2160                 if let Some(("inspect", [_, _], span2)) = method_call!(recv) {
2161                     inspect_for_each::check(cx, expr, span2);
2162                 }
2163             },
2164             ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2165             ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2166             ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2167             ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2168             ("map", [m_arg]) => {
2169                 if let Some((name, [recv2, args @ ..], span2)) = method_call!(recv) {
2170                     match (name, args) {
2171                         ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, msrv),
2172                         ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, msrv),
2173                         ("filter", [f_arg]) => {
2174                             filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2175                         },
2176                         ("find", [f_arg]) => filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true),
2177                         _ => {},
2178                     }
2179                 }
2180                 map_identity::check(cx, expr, recv, m_arg, span);
2181             },
2182             ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2183             ("next", []) => {
2184                 if let Some((name, [recv, args @ ..], _)) = method_call!(recv) {
2185                     match (name, args) {
2186                         ("filter", [arg]) => filter_next::check(cx, expr, recv, arg),
2187                         ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv, arg, msrv),
2188                         ("iter", []) => iter_next_slice::check(cx, expr, recv),
2189                         ("skip", [arg]) => iter_skip_next::check(cx, expr, recv, arg),
2190                         ("skip_while", [_]) => skip_while_next::check(cx, expr),
2191                         _ => {},
2192                     }
2193                 }
2194             },
2195             ("nth", [n_arg]) => match method_call!(recv) {
2196                 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2197                 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2198                 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2199                 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2200             },
2201             ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2202             ("or_else", [arg]) => {
2203                 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2204                     unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2205                 }
2206             },
2207             ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2208                 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2209                     suspicious_splitn::check(cx, name, expr, recv, count);
2210                     if count == 2 && meets_msrv(msrv, &msrvs::STR_SPLIT_ONCE) {
2211                         manual_split_once::check(cx, name, expr, recv, pat_arg);
2212                     }
2213                 }
2214             },
2215             ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2216                 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2217                     suspicious_splitn::check(cx, name, expr, recv, count);
2218                 }
2219             },
2220             ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2221             ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2222                 implicit_clone::check(cx, name, expr, recv, span);
2223             },
2224             ("unwrap", []) => match method_call!(recv) {
2225                 Some(("get", [recv, get_arg], _)) => get_unwrap::check(cx, expr, recv, get_arg, false),
2226                 Some(("get_mut", [recv, get_arg], _)) => get_unwrap::check(cx, expr, recv, get_arg, true),
2227                 _ => unwrap_used::check(cx, expr, recv),
2228             },
2229             ("unwrap_or", [u_arg]) => match method_call!(recv) {
2230                 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2231                     manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2232                 },
2233                 Some(("map", [m_recv, m_arg], span)) => {
2234                     option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2235                 },
2236                 _ => {},
2237             },
2238             ("unwrap_or_else", [u_arg]) => match method_call!(recv) {
2239                 Some(("map", [recv, map_arg], _)) if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, msrv) => {},
2240                 _ => {
2241                     unwrap_or_else_default::check(cx, expr, recv, u_arg);
2242                     unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2243                 },
2244             },
2245             _ => {},
2246         }
2247     }
2248 }
2249 
check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool)2250 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2251     if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call!(recv) {
2252         search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2253     }
2254 }
2255 
2256 /// Used for `lint_binary_expr_with_method_call`.
2257 #[derive(Copy, Clone)]
2258 struct BinaryExprInfo<'a> {
2259     expr: &'a hir::Expr<'a>,
2260     chain: &'a hir::Expr<'a>,
2261     other: &'a hir::Expr<'a>,
2262     eq: bool,
2263 }
2264 
2265 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>)2266 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2267     macro_rules! lint_with_both_lhs_and_rhs {
2268         ($func:expr, $cx:expr, $info:ident) => {
2269             if !$func($cx, $info) {
2270                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2271                 if $func($cx, $info) {
2272                     return;
2273                 }
2274             }
2275         };
2276     }
2277 
2278     lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2279     lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2280     lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2281     lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2282 }
2283 
2284 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2285     unsafety: hir::Unsafety::Normal,
2286     constness: hir::Constness::NotConst,
2287     asyncness: hir::IsAsync::NotAsync,
2288     abi: rustc_target::spec::abi::Abi::Rust,
2289 };
2290 
2291 struct ShouldImplTraitCase {
2292     trait_name: &'static str,
2293     method_name: &'static str,
2294     param_count: usize,
2295     fn_header: hir::FnHeader,
2296     // implicit self kind expected (none, self, &self, ...)
2297     self_kind: SelfKind,
2298     // checks against the output type
2299     output_type: OutType,
2300     // certain methods with explicit lifetimes can't implement the equivalent trait method
2301     lint_explicit_lifetime: bool,
2302 }
2303 impl ShouldImplTraitCase {
new( trait_name: &'static str, method_name: &'static str, param_count: usize, fn_header: hir::FnHeader, self_kind: SelfKind, output_type: OutType, lint_explicit_lifetime: bool, ) -> ShouldImplTraitCase2304     const fn new(
2305         trait_name: &'static str,
2306         method_name: &'static str,
2307         param_count: usize,
2308         fn_header: hir::FnHeader,
2309         self_kind: SelfKind,
2310         output_type: OutType,
2311         lint_explicit_lifetime: bool,
2312     ) -> ShouldImplTraitCase {
2313         ShouldImplTraitCase {
2314             trait_name,
2315             method_name,
2316             param_count,
2317             fn_header,
2318             self_kind,
2319             output_type,
2320             lint_explicit_lifetime,
2321         }
2322     }
2323 
lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool2324     fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2325         self.lint_explicit_lifetime
2326             || !impl_item.generics.params.iter().any(|p| {
2327                 matches!(
2328                     p.kind,
2329                     hir::GenericParamKind::Lifetime {
2330                         kind: hir::LifetimeParamKind::Explicit
2331                     }
2332                 )
2333             })
2334     }
2335 }
2336 
2337 #[rustfmt::skip]
2338 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2339     ShouldImplTraitCase::new("std::ops::Add", "add",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2340     ShouldImplTraitCase::new("std::convert::AsMut", "as_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2341     ShouldImplTraitCase::new("std::convert::AsRef", "as_ref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2342     ShouldImplTraitCase::new("std::ops::BitAnd", "bitand",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2343     ShouldImplTraitCase::new("std::ops::BitOr", "bitor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2344     ShouldImplTraitCase::new("std::ops::BitXor", "bitxor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2345     ShouldImplTraitCase::new("std::borrow::Borrow", "borrow",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2346     ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2347     ShouldImplTraitCase::new("std::clone::Clone", "clone",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
2348     ShouldImplTraitCase::new("std::cmp::Ord", "cmp",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
2349     // FIXME: default doesn't work
2350     ShouldImplTraitCase::new("std::default::Default", "default",  0,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2351     ShouldImplTraitCase::new("std::ops::Deref", "deref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2352     ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2353     ShouldImplTraitCase::new("std::ops::Div", "div",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2354     ShouldImplTraitCase::new("std::ops::Drop", "drop",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Unit, true),
2355     ShouldImplTraitCase::new("std::cmp::PartialEq", "eq",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Bool, true),
2356     ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2357     ShouldImplTraitCase::new("std::str::FromStr", "from_str",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2358     ShouldImplTraitCase::new("std::hash::Hash", "hash",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Unit, true),
2359     ShouldImplTraitCase::new("std::ops::Index", "index",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2360     ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut",  2,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2361     ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2362     ShouldImplTraitCase::new("std::ops::Mul", "mul",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2363     ShouldImplTraitCase::new("std::ops::Neg", "neg",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2364     ShouldImplTraitCase::new("std::iter::Iterator", "next",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Any, false),
2365     ShouldImplTraitCase::new("std::ops::Not", "not",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2366     ShouldImplTraitCase::new("std::ops::Rem", "rem",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2367     ShouldImplTraitCase::new("std::ops::Shl", "shl",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2368     ShouldImplTraitCase::new("std::ops::Shr", "shr",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2369     ShouldImplTraitCase::new("std::ops::Sub", "sub",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2370 ];
2371 
2372 #[derive(Clone, Copy, PartialEq, Debug)]
2373 enum SelfKind {
2374     Value,
2375     Ref,
2376     RefMut,
2377     No,
2378 }
2379 
2380 impl SelfKind {
matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool2381     fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2382         fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2383             if ty == parent_ty {
2384                 true
2385             } else if ty.is_box() {
2386                 ty.boxed_ty() == parent_ty
2387             } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2388                 if let ty::Adt(_, substs) = ty.kind() {
2389                     substs.types().next().map_or(false, |t| t == parent_ty)
2390                 } else {
2391                     false
2392                 }
2393             } else {
2394                 false
2395             }
2396         }
2397 
2398         fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2399             if let ty::Ref(_, t, m) = *ty.kind() {
2400                 return m == mutability && t == parent_ty;
2401             }
2402 
2403             let trait_path = match mutability {
2404                 hir::Mutability::Not => &paths::ASREF_TRAIT,
2405                 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2406             };
2407 
2408             let trait_def_id = match get_trait_def_id(cx, trait_path) {
2409                 Some(did) => did,
2410                 None => return false,
2411             };
2412             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2413         }
2414 
2415         match self {
2416             Self::Value => matches_value(cx, parent_ty, ty),
2417             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2418             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2419             Self::No => ty != parent_ty,
2420         }
2421     }
2422 
2423     #[must_use]
description(self) -> &'static str2424     fn description(self) -> &'static str {
2425         match self {
2426             Self::Value => "`self` by value",
2427             Self::Ref => "`self` by reference",
2428             Self::RefMut => "`self` by mutable reference",
2429             Self::No => "no `self`",
2430         }
2431     }
2432 }
2433 
2434 #[derive(Clone, Copy)]
2435 enum OutType {
2436     Unit,
2437     Bool,
2438     Any,
2439     Ref,
2440 }
2441 
2442 impl OutType {
matches(self, ty: &hir::FnRetTy<'_>) -> bool2443     fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2444         let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2445         match (self, ty) {
2446             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2447             (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2448             (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2449             (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2450             (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2451             _ => false,
2452         }
2453     }
2454 }
2455 
is_bool(ty: &hir::Ty<'_>) -> bool2456 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2457     if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2458         matches!(path.res, Res::PrimTy(PrimTy::Bool))
2459     } else {
2460         false
2461     }
2462 }
2463 
fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool2464 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2465     expected.constness == actual.constness
2466         && expected.unsafety == actual.unsafety
2467         && expected.asyncness == actual.asyncness
2468 }
2469