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