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