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