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