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