]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
move map_unwrap_or to its own module
[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_used;
6 mod filetype_is_file;
7 mod filter_flat_map;
8 mod filter_map;
9 mod filter_map_flat_map;
10 mod filter_map_identity;
11 mod filter_map_map;
12 mod filter_map_next;
13 mod filter_next;
14 mod flat_map_identity;
15 mod from_iter_instead_of_collect;
16 mod get_unwrap;
17 mod implicit_clone;
18 mod inefficient_to_string;
19 mod inspect_for_each;
20 mod into_iter_on_ref;
21 mod iter_cloned_collect;
22 mod iter_count;
23 mod iter_next_slice;
24 mod iter_nth;
25 mod iter_nth_zero;
26 mod iter_skip_next;
27 mod iterator_step_by_zero;
28 mod manual_saturating_arithmetic;
29 mod map_collect_result_unit;
30 mod map_flatten;
31 mod map_unwrap_or;
32 mod ok_expect;
33 mod option_as_ref_deref;
34 mod option_map_or_none;
35 mod option_map_unwrap_or;
36 mod search_is_some;
37 mod single_char_insert_string;
38 mod single_char_pattern;
39 mod single_char_push_string;
40 mod skip_while_next;
41 mod string_extend_chars;
42 mod suspicious_map;
43 mod uninit_assumed_init;
44 mod unnecessary_filter_map;
45 mod unnecessary_fold;
46 mod unnecessary_lazy_eval;
47 mod unwrap_used;
48 mod useless_asref;
49 mod wrong_self_convention;
50 mod zst_offset;
51
52 use std::borrow::Cow;
53
54 use bind_instead_of_map::BindInsteadOfMap;
55 use if_chain::if_chain;
56 use rustc_ast::ast;
57 use rustc_errors::Applicability;
58 use rustc_hir as hir;
59 use rustc_hir::{TraitItem, TraitItemKind};
60 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
61 use rustc_middle::lint::in_external_macro;
62 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
63 use rustc_semver::RustcVersion;
64 use rustc_session::{declare_tool_lint, impl_lint_pass};
65 use rustc_span::source_map::Span;
66 use rustc_span::symbol::{sym, Symbol, SymbolStr};
67 use rustc_typeck::hir_ty_to_ty;
68
69 use crate::utils::eager_or_lazy::is_lazyness_candidate;
70 use crate::utils::{
71     contains_return, contains_ty, get_trait_def_id, implements_trait, in_macro, is_copy, is_expn_of,
72     is_type_diagnostic_item, iter_input_pats, last_path_segment, match_def_path, match_qpath, match_type, method_calls,
73     method_chain_args, paths, return_ty, single_segment_path, snippet, snippet_with_applicability,
74     snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, SpanlessEq,
75 };
76
77 declare_clippy_lint! {
78     /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
79     ///
80     /// **Why is this bad?** It is better to handle the `None` or `Err` case,
81     /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
82     /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
83     /// `Allow` by default.
84     ///
85     /// `result.unwrap()` will let the thread panic on `Err` values.
86     /// Normally, you want to implement more sophisticated error handling,
87     /// and propagate errors upwards with `?` operator.
88     ///
89     /// Even if you want to panic on errors, not all `Error`s implement good
90     /// messages on display. Therefore, it may be beneficial to look at the places
91     /// where they may get displayed. Activate this lint to do just that.
92     ///
93     /// **Known problems:** None.
94     ///
95     /// **Examples:**
96     /// ```rust
97     /// # let opt = Some(1);
98     ///
99     /// // Bad
100     /// opt.unwrap();
101     ///
102     /// // Good
103     /// opt.expect("more helpful message");
104     /// ```
105     ///
106     /// // or
107     ///
108     /// ```rust
109     /// # let res: Result<usize, ()> = Ok(1);
110     ///
111     /// // Bad
112     /// res.unwrap();
113     ///
114     /// // Good
115     /// res.expect("more helpful message");
116     /// ```
117     pub UNWRAP_USED,
118     restriction,
119     "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
120 }
121
122 declare_clippy_lint! {
123     /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
124     ///
125     /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
126     /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
127     /// this lint is `Allow` by default.
128     ///
129     /// `result.expect()` will let the thread panic on `Err`
130     /// values. Normally, you want to implement more sophisticated error handling,
131     /// and propagate errors upwards with `?` operator.
132     ///
133     /// **Known problems:** None.
134     ///
135     /// **Examples:**
136     /// ```rust,ignore
137     /// # let opt = Some(1);
138     ///
139     /// // Bad
140     /// opt.expect("one");
141     ///
142     /// // Good
143     /// let opt = Some(1);
144     /// opt?;
145     /// ```
146     ///
147     /// // or
148     ///
149     /// ```rust
150     /// # let res: Result<usize, ()> = Ok(1);
151     ///
152     /// // Bad
153     /// res.expect("one");
154     ///
155     /// // Good
156     /// res?;
157     /// # Ok::<(), ()>(())
158     /// ```
159     pub EXPECT_USED,
160     restriction,
161     "using `.expect()` on `Result` or `Option`, which might be better handled"
162 }
163
164 declare_clippy_lint! {
165     /// **What it does:** Checks for methods that should live in a trait
166     /// implementation of a `std` trait (see [llogiq's blog
167     /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
168     /// information) instead of an inherent implementation.
169     ///
170     /// **Why is this bad?** Implementing the traits improve ergonomics for users of
171     /// the code, often with very little cost. Also people seeing a `mul(...)`
172     /// method
173     /// may expect `*` to work equally, so you should have good reason to disappoint
174     /// them.
175     ///
176     /// **Known problems:** None.
177     ///
178     /// **Example:**
179     /// ```rust
180     /// struct X;
181     /// impl X {
182     ///     fn add(&self, other: &X) -> X {
183     ///         // ..
184     /// # X
185     ///     }
186     /// }
187     /// ```
188     pub SHOULD_IMPLEMENT_TRAIT,
189     style,
190     "defining a method that should be implementing a std trait"
191 }
192
193 declare_clippy_lint! {
194     /// **What it does:** Checks for methods with certain name prefixes and which
195     /// doesn't match how self is taken. The actual rules are:
196     ///
197     /// |Prefix |`self` taken          |
198     /// |-------|----------------------|
199     /// |`as_`  |`&self` or `&mut self`|
200     /// |`from_`| none                 |
201     /// |`into_`|`self`                |
202     /// |`is_`  |`&self` or none       |
203     /// |`to_`  |`&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),
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                 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1782                 lint_expect_fun_call(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 /// Checks for the `OR_FUN_CALL` lint.
1977 #[allow(clippy::too_many_lines)]
1978 fn lint_or_fun_call<'tcx>(
1979     cx: &LateContext<'tcx>,
1980     expr: &hir::Expr<'_>,
1981     method_span: Span,
1982     name: &str,
1983     args: &'tcx [hir::Expr<'_>],
1984 ) {
1985     /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1986     fn check_unwrap_or_default(
1987         cx: &LateContext<'_>,
1988         name: &str,
1989         fun: &hir::Expr<'_>,
1990         self_expr: &hir::Expr<'_>,
1991         arg: &hir::Expr<'_>,
1992         or_has_args: bool,
1993         span: Span,
1994     ) -> bool {
1995         if_chain! {
1996             if !or_has_args;
1997             if name == "unwrap_or";
1998             if let hir::ExprKind::Path(ref qpath) = fun.kind;
1999             let path = &*last_path_segment(qpath).ident.as_str();
2000             if ["default", "new"].contains(&path);
2001             let arg_ty = cx.typeck_results().expr_ty(arg);
2002             if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
2003             if implements_trait(cx, arg_ty, default_trait_id, &[]);
2004
2005             then {
2006                 let mut applicability = Applicability::MachineApplicable;
2007                 span_lint_and_sugg(
2008                     cx,
2009                     OR_FUN_CALL,
2010                     span,
2011                     &format!("use of `{}` followed by a call to `{}`", name, path),
2012                     "try this",
2013                     format!(
2014                         "{}.unwrap_or_default()",
2015                         snippet_with_applicability(cx, self_expr.span, "..", &mut applicability)
2016                     ),
2017                     applicability,
2018                 );
2019
2020                 true
2021             } else {
2022                 false
2023             }
2024         }
2025     }
2026
2027     /// Checks for `*or(foo())`.
2028     #[allow(clippy::too_many_arguments)]
2029     fn check_general_case<'tcx>(
2030         cx: &LateContext<'tcx>,
2031         name: &str,
2032         method_span: Span,
2033         self_expr: &hir::Expr<'_>,
2034         arg: &'tcx hir::Expr<'_>,
2035         span: Span,
2036         // None if lambda is required
2037         fun_span: Option<Span>,
2038     ) {
2039         // (path, fn_has_argument, methods, suffix)
2040         static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [
2041             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
2042             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
2043             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
2044             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
2045         ];
2046
2047         if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
2048             if path.ident.as_str() == "len" {
2049                 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
2050
2051                 match ty.kind() {
2052                     ty::Slice(_) | ty::Array(_, _) => return,
2053                     _ => (),
2054                 }
2055
2056                 if is_type_diagnostic_item(cx, ty, sym::vec_type) {
2057                     return;
2058                 }
2059             }
2060         }
2061
2062         if_chain! {
2063             if KNOW_TYPES.iter().any(|k| k.2.contains(&name));
2064
2065             if is_lazyness_candidate(cx, arg);
2066             if !contains_return(&arg);
2067
2068             let self_ty = cx.typeck_results().expr_ty(self_expr);
2069
2070             if let Some(&(_, fn_has_arguments, poss, suffix)) =
2071                 KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0));
2072
2073             if poss.contains(&name);
2074
2075             then {
2076                 let macro_expanded_snipped;
2077                 let sugg: Cow<'_, str> = {
2078                     let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) {
2079                         (false, Some(fun_span)) => (fun_span, false),
2080                         _ => (arg.span, true),
2081                     };
2082                     let snippet = {
2083                         let not_macro_argument_snippet = snippet_with_macro_callsite(cx, snippet_span, "..");
2084                         if not_macro_argument_snippet == "vec![]" {
2085                             macro_expanded_snipped = snippet(cx, snippet_span, "..");
2086                             match macro_expanded_snipped.strip_prefix("$crate::vec::") {
2087                                 Some(stripped) => Cow::from(stripped),
2088                                 None => macro_expanded_snipped
2089                             }
2090                         }
2091                         else {
2092                             not_macro_argument_snippet
2093                         }
2094                     };
2095
2096                     if use_lambda {
2097                         let l_arg = if fn_has_arguments { "_" } else { "" };
2098                         format!("|{}| {}", l_arg, snippet).into()
2099                     } else {
2100                         snippet
2101                     }
2102                 };
2103                 let span_replace_word = method_span.with_hi(span.hi());
2104                 span_lint_and_sugg(
2105                     cx,
2106                     OR_FUN_CALL,
2107                     span_replace_word,
2108                     &format!("use of `{}` followed by a function call", name),
2109                     "try this",
2110                     format!("{}_{}({})", name, suffix, sugg),
2111                     Applicability::HasPlaceholders,
2112                 );
2113             }
2114         }
2115     }
2116
2117     if args.len() == 2 {
2118         match args[1].kind {
2119             hir::ExprKind::Call(ref fun, ref or_args) => {
2120                 let or_has_args = !or_args.is_empty();
2121                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
2122                     let fun_span = if or_has_args { None } else { Some(fun.span) };
2123                     check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, fun_span);
2124                 }
2125             },
2126             hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => {
2127                 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, None);
2128             },
2129             _ => {},
2130         }
2131     }
2132 }
2133
2134 /// Checks for the `EXPECT_FUN_CALL` lint.
2135 #[allow(clippy::too_many_lines)]
2136 fn lint_expect_fun_call(
2137     cx: &LateContext<'_>,
2138     expr: &hir::Expr<'_>,
2139     method_span: Span,
2140     name: &str,
2141     args: &[hir::Expr<'_>],
2142 ) {
2143     // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
2144     // `&str`
2145     fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
2146         let mut arg_root = arg;
2147         loop {
2148             arg_root = match &arg_root.kind {
2149                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
2150                 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
2151                     if call_args.len() == 1
2152                         && (method_name.ident.name == sym::as_str || method_name.ident.name == sym!(as_ref))
2153                         && {
2154                             let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
2155                             let base_type = arg_type.peel_refs();
2156                             *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym::string_type)
2157                         }
2158                     {
2159                         &call_args[0]
2160                     } else {
2161                         break;
2162                     }
2163                 },
2164                 _ => break,
2165             };
2166         }
2167         arg_root
2168     }
2169
2170     // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
2171     // converted to string.
2172     fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2173         let arg_ty = cx.typeck_results().expr_ty(arg);
2174         if is_type_diagnostic_item(cx, arg_ty, sym::string_type) {
2175             return false;
2176         }
2177         if let ty::Ref(_, ty, ..) = arg_ty.kind() {
2178             if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
2179                 return false;
2180             }
2181         };
2182         true
2183     }
2184
2185     // Check if an expression could have type `&'static str`, knowing that it
2186     // has type `&str` for some lifetime.
2187     fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2188         match arg.kind {
2189             hir::ExprKind::Lit(_) => true,
2190             hir::ExprKind::Call(fun, _) => {
2191                 if let hir::ExprKind::Path(ref p) = fun.kind {
2192                     match cx.qpath_res(p, fun.hir_id) {
2193                         hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
2194                             cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
2195                             ty::Ref(ty::ReStatic, ..)
2196                         ),
2197                         _ => false,
2198                     }
2199                 } else {
2200                     false
2201                 }
2202             },
2203             hir::ExprKind::MethodCall(..) => {
2204                 cx.typeck_results()
2205                     .type_dependent_def_id(arg.hir_id)
2206                     .map_or(false, |method_id| {
2207                         matches!(
2208                             cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
2209                             ty::Ref(ty::ReStatic, ..)
2210                         )
2211                     })
2212             },
2213             hir::ExprKind::Path(ref p) => matches!(
2214                 cx.qpath_res(p, arg.hir_id),
2215                 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
2216             ),
2217             _ => false,
2218         }
2219     }
2220
2221     fn generate_format_arg_snippet(
2222         cx: &LateContext<'_>,
2223         a: &hir::Expr<'_>,
2224         applicability: &mut Applicability,
2225     ) -> Vec<String> {
2226         if_chain! {
2227             if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
2228             if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
2229             if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
2230
2231             then {
2232                 format_arg_expr_tup
2233                     .iter()
2234                     .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
2235                     .collect()
2236             } else {
2237                 unreachable!()
2238             }
2239         }
2240     }
2241
2242     fn is_call(node: &hir::ExprKind<'_>) -> bool {
2243         match node {
2244             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
2245                 is_call(&expr.kind)
2246             },
2247             hir::ExprKind::Call(..)
2248             | hir::ExprKind::MethodCall(..)
2249             // These variants are debatable or require further examination
2250             | hir::ExprKind::If(..)
2251             | hir::ExprKind::Match(..)
2252             | hir::ExprKind::Block{ .. } => true,
2253             _ => false,
2254         }
2255     }
2256
2257     if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
2258         return;
2259     }
2260
2261     let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
2262     let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::option_type) {
2263         "||"
2264     } else if is_type_diagnostic_item(cx, receiver_type, sym::result_type) {
2265         "|_|"
2266     } else {
2267         return;
2268     };
2269
2270     let arg_root = get_arg_root(cx, &args[1]);
2271
2272     let span_replace_word = method_span.with_hi(expr.span.hi());
2273
2274     let mut applicability = Applicability::MachineApplicable;
2275
2276     //Special handling for `format!` as arg_root
2277     if_chain! {
2278         if let hir::ExprKind::Block(block, None) = &arg_root.kind;
2279         if block.stmts.len() == 1;
2280         if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
2281         if let Some(arg_root) = &local.init;
2282         if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
2283         if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
2284         if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
2285         then {
2286             let fmt_spec = &format_args[0];
2287             let fmt_args = &format_args[1];
2288
2289             let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
2290
2291             args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
2292
2293             let sugg = args.join(", ");
2294
2295             span_lint_and_sugg(
2296                 cx,
2297                 EXPECT_FUN_CALL,
2298                 span_replace_word,
2299                 &format!("use of `{}` followed by a function call", name),
2300                 "try this",
2301                 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
2302                 applicability,
2303             );
2304
2305             return;
2306         }
2307     }
2308
2309     let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
2310     if requires_to_string(cx, arg_root) {
2311         arg_root_snippet.to_mut().push_str(".to_string()");
2312     }
2313
2314     span_lint_and_sugg(
2315         cx,
2316         EXPECT_FUN_CALL,
2317         span_replace_word,
2318         &format!("use of `{}` followed by a function call", name),
2319         "try this",
2320         format!(
2321             "unwrap_or_else({} {{ panic!(\"{{}}\", {}) }})",
2322             closure_args, arg_root_snippet
2323         ),
2324         applicability,
2325     );
2326 }
2327
2328 fn derefs_to_slice<'tcx>(
2329     cx: &LateContext<'tcx>,
2330     expr: &'tcx hir::Expr<'tcx>,
2331     ty: Ty<'tcx>,
2332 ) -> Option<&'tcx hir::Expr<'tcx>> {
2333     fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
2334         match ty.kind() {
2335             ty::Slice(_) => true,
2336             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2337             ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
2338             ty::Array(_, size) => size
2339                 .try_eval_usize(cx.tcx, cx.param_env)
2340                 .map_or(false, |size| size < 32),
2341             ty::Ref(_, inner, _) => may_slice(cx, inner),
2342             _ => false,
2343         }
2344     }
2345
2346     if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
2347         if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2348             Some(&args[0])
2349         } else {
2350             None
2351         }
2352     } else {
2353         match ty.kind() {
2354             ty::Slice(_) => Some(expr),
2355             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2356             ty::Ref(_, inner, _) => {
2357                 if may_slice(cx, inner) {
2358                     Some(expr)
2359                 } else {
2360                     None
2361                 }
2362             },
2363             _ => None,
2364         }
2365     }
2366 }
2367
2368 /// Used for `lint_binary_expr_with_method_call`.
2369 #[derive(Copy, Clone)]
2370 struct BinaryExprInfo<'a> {
2371     expr: &'a hir::Expr<'a>,
2372     chain: &'a hir::Expr<'a>,
2373     other: &'a hir::Expr<'a>,
2374     eq: bool,
2375 }
2376
2377 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2378 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2379     macro_rules! lint_with_both_lhs_and_rhs {
2380         ($func:ident, $cx:expr, $info:ident) => {
2381             if !$func($cx, $info) {
2382                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2383                 if $func($cx, $info) {
2384                     return;
2385                 }
2386             }
2387         };
2388     }
2389
2390     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2391     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2392     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2393     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2394 }
2395
2396 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2397 fn lint_chars_cmp(
2398     cx: &LateContext<'_>,
2399     info: &BinaryExprInfo<'_>,
2400     chain_methods: &[&str],
2401     lint: &'static Lint,
2402     suggest: &str,
2403 ) -> bool {
2404     if_chain! {
2405         if let Some(args) = method_chain_args(info.chain, chain_methods);
2406         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2407         if arg_char.len() == 1;
2408         if let hir::ExprKind::Path(ref qpath) = fun.kind;
2409         if let Some(segment) = single_segment_path(qpath);
2410         if segment.ident.name == sym::Some;
2411         then {
2412             let mut applicability = Applicability::MachineApplicable;
2413             let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
2414
2415             if *self_ty.kind() != ty::Str {
2416                 return false;
2417             }
2418
2419             span_lint_and_sugg(
2420                 cx,
2421                 lint,
2422                 info.expr.span,
2423                 &format!("you should use the `{}` method", suggest),
2424                 "like this",
2425                 format!("{}{}.{}({})",
2426                         if info.eq { "" } else { "!" },
2427                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
2428                         suggest,
2429                         snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
2430                 applicability,
2431             );
2432
2433             return true;
2434         }
2435     }
2436
2437     false
2438 }
2439
2440 /// Checks for the `CHARS_NEXT_CMP` lint.
2441 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2442     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2443 }
2444
2445 /// Checks for the `CHARS_LAST_CMP` lint.
2446 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2447     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2448         true
2449     } else {
2450         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2451     }
2452 }
2453
2454 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2455 fn lint_chars_cmp_with_unwrap<'tcx>(
2456     cx: &LateContext<'tcx>,
2457     info: &BinaryExprInfo<'_>,
2458     chain_methods: &[&str],
2459     lint: &'static Lint,
2460     suggest: &str,
2461 ) -> bool {
2462     if_chain! {
2463         if let Some(args) = method_chain_args(info.chain, chain_methods);
2464         if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2465         if let ast::LitKind::Char(c) = lit.node;
2466         then {
2467             let mut applicability = Applicability::MachineApplicable;
2468             span_lint_and_sugg(
2469                 cx,
2470                 lint,
2471                 info.expr.span,
2472                 &format!("you should use the `{}` method", suggest),
2473                 "like this",
2474                 format!("{}{}.{}('{}')",
2475                         if info.eq { "" } else { "!" },
2476                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
2477                         suggest,
2478                         c),
2479                 applicability,
2480             );
2481
2482             true
2483         } else {
2484             false
2485         }
2486     }
2487 }
2488
2489 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2490 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2491     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2492 }
2493
2494 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2495 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2496     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2497         true
2498     } else {
2499         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
2500     }
2501 }
2502
2503 fn get_hint_if_single_char_arg(
2504     cx: &LateContext<'_>,
2505     arg: &hir::Expr<'_>,
2506     applicability: &mut Applicability,
2507 ) -> Option<String> {
2508     if_chain! {
2509         if let hir::ExprKind::Lit(lit) = &arg.kind;
2510         if let ast::LitKind::Str(r, style) = lit.node;
2511         let string = r.as_str();
2512         if string.chars().count() == 1;
2513         then {
2514             let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
2515             let ch = if let ast::StrStyle::Raw(nhash) = style {
2516                 let nhash = nhash as usize;
2517                 // for raw string: r##"a"##
2518                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
2519             } else {
2520                 // for regular string: "a"
2521                 &snip[1..(snip.len() - 1)]
2522             };
2523             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
2524             Some(hint)
2525         } else {
2526             None
2527         }
2528     }
2529 }
2530
2531 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2532     unsafety: hir::Unsafety::Normal,
2533     constness: hir::Constness::NotConst,
2534     asyncness: hir::IsAsync::NotAsync,
2535     abi: rustc_target::spec::abi::Abi::Rust,
2536 };
2537
2538 struct ShouldImplTraitCase {
2539     trait_name: &'static str,
2540     method_name: &'static str,
2541     param_count: usize,
2542     fn_header: hir::FnHeader,
2543     // implicit self kind expected (none, self, &self, ...)
2544     self_kind: SelfKind,
2545     // checks against the output type
2546     output_type: OutType,
2547     // certain methods with explicit lifetimes can't implement the equivalent trait method
2548     lint_explicit_lifetime: bool,
2549 }
2550 impl ShouldImplTraitCase {
2551     const fn new(
2552         trait_name: &'static str,
2553         method_name: &'static str,
2554         param_count: usize,
2555         fn_header: hir::FnHeader,
2556         self_kind: SelfKind,
2557         output_type: OutType,
2558         lint_explicit_lifetime: bool,
2559     ) -> ShouldImplTraitCase {
2560         ShouldImplTraitCase {
2561             trait_name,
2562             method_name,
2563             param_count,
2564             fn_header,
2565             self_kind,
2566             output_type,
2567             lint_explicit_lifetime,
2568         }
2569     }
2570
2571     fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2572         self.lint_explicit_lifetime
2573             || !impl_item.generics.params.iter().any(|p| {
2574                 matches!(
2575                     p.kind,
2576                     hir::GenericParamKind::Lifetime {
2577                         kind: hir::LifetimeParamKind::Explicit
2578                     }
2579                 )
2580             })
2581     }
2582 }
2583
2584 #[rustfmt::skip]
2585 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2586     ShouldImplTraitCase::new("std::ops::Add", "add",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2587     ShouldImplTraitCase::new("std::convert::AsMut", "as_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2588     ShouldImplTraitCase::new("std::convert::AsRef", "as_ref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2589     ShouldImplTraitCase::new("std::ops::BitAnd", "bitand",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2590     ShouldImplTraitCase::new("std::ops::BitOr", "bitor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2591     ShouldImplTraitCase::new("std::ops::BitXor", "bitxor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2592     ShouldImplTraitCase::new("std::borrow::Borrow", "borrow",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2593     ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2594     ShouldImplTraitCase::new("std::clone::Clone", "clone",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
2595     ShouldImplTraitCase::new("std::cmp::Ord", "cmp",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
2596     // FIXME: default doesn't work
2597     ShouldImplTraitCase::new("std::default::Default", "default",  0,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2598     ShouldImplTraitCase::new("std::ops::Deref", "deref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2599     ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2600     ShouldImplTraitCase::new("std::ops::Div", "div",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2601     ShouldImplTraitCase::new("std::ops::Drop", "drop",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Unit, true),
2602     ShouldImplTraitCase::new("std::cmp::PartialEq", "eq",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Bool, true),
2603     ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2604     ShouldImplTraitCase::new("std::str::FromStr", "from_str",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2605     ShouldImplTraitCase::new("std::hash::Hash", "hash",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Unit, true),
2606     ShouldImplTraitCase::new("std::ops::Index", "index",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2607     ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut",  2,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2608     ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2609     ShouldImplTraitCase::new("std::ops::Mul", "mul",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2610     ShouldImplTraitCase::new("std::ops::Neg", "neg",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2611     ShouldImplTraitCase::new("std::iter::Iterator", "next",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Any, false),
2612     ShouldImplTraitCase::new("std::ops::Not", "not",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2613     ShouldImplTraitCase::new("std::ops::Rem", "rem",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2614     ShouldImplTraitCase::new("std::ops::Shl", "shl",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2615     ShouldImplTraitCase::new("std::ops::Shr", "shr",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2616     ShouldImplTraitCase::new("std::ops::Sub", "sub",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2617 ];
2618
2619 #[rustfmt::skip]
2620 const PATTERN_METHODS: [(&str, usize); 17] = [
2621     ("contains", 1),
2622     ("starts_with", 1),
2623     ("ends_with", 1),
2624     ("find", 1),
2625     ("rfind", 1),
2626     ("split", 1),
2627     ("rsplit", 1),
2628     ("split_terminator", 1),
2629     ("rsplit_terminator", 1),
2630     ("splitn", 2),
2631     ("rsplitn", 2),
2632     ("matches", 1),
2633     ("rmatches", 1),
2634     ("match_indices", 1),
2635     ("rmatch_indices", 1),
2636     ("trim_start_matches", 1),
2637     ("trim_end_matches", 1),
2638 ];
2639
2640 #[derive(Clone, Copy, PartialEq, Debug)]
2641 enum SelfKind {
2642     Value,
2643     Ref,
2644     RefMut,
2645     No,
2646 }
2647
2648 impl SelfKind {
2649     fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2650         fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2651             if ty == parent_ty {
2652                 true
2653             } else if ty.is_box() {
2654                 ty.boxed_ty() == parent_ty
2655             } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2656                 if let ty::Adt(_, substs) = ty.kind() {
2657                     substs.types().next().map_or(false, |t| t == parent_ty)
2658                 } else {
2659                     false
2660                 }
2661             } else {
2662                 false
2663             }
2664         }
2665
2666         fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2667             if let ty::Ref(_, t, m) = *ty.kind() {
2668                 return m == mutability && t == parent_ty;
2669             }
2670
2671             let trait_path = match mutability {
2672                 hir::Mutability::Not => &paths::ASREF_TRAIT,
2673                 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2674             };
2675
2676             let trait_def_id = match get_trait_def_id(cx, trait_path) {
2677                 Some(did) => did,
2678                 None => return false,
2679             };
2680             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2681         }
2682
2683         match self {
2684             Self::Value => matches_value(cx, parent_ty, ty),
2685             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2686             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2687             Self::No => ty != parent_ty,
2688         }
2689     }
2690
2691     #[must_use]
2692     fn description(self) -> &'static str {
2693         match self {
2694             Self::Value => "self by value",
2695             Self::Ref => "self by reference",
2696             Self::RefMut => "self by mutable reference",
2697             Self::No => "no self",
2698         }
2699     }
2700 }
2701
2702 #[derive(Clone, Copy)]
2703 enum OutType {
2704     Unit,
2705     Bool,
2706     Any,
2707     Ref,
2708 }
2709
2710 impl OutType {
2711     fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
2712         let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
2713         match (self, ty) {
2714             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2715             (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
2716             (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
2717             (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
2718             (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2719             _ => false,
2720         }
2721     }
2722 }
2723
2724 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2725     if let hir::TyKind::Path(ref p) = ty.kind {
2726         match_qpath(p, &["bool"])
2727     } else {
2728         false
2729     }
2730 }
2731
2732 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2733     expected.constness == actual.constness
2734         && expected.unsafety == actual.unsafety
2735         && expected.asyncness == actual.asyncness
2736 }