]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
68a152270e05e31cc7e74c61a3c56a7188f2d7ea
[rust.git] / clippy_lints / src / methods / mod.rs
1 mod bind_instead_of_map;
2 mod inefficient_to_string;
3 mod manual_saturating_arithmetic;
4 mod option_map_unwrap_or;
5 mod unnecessary_filter_map;
6 mod unnecessary_lazy_eval;
7
8 use std::borrow::Cow;
9 use std::fmt;
10 use std::iter;
11
12 use bind_instead_of_map::BindInsteadOfMap;
13 use if_chain::if_chain;
14 use rustc_ast::ast;
15 use rustc_errors::Applicability;
16 use rustc_hir as hir;
17 use rustc_hir::intravisit::{self, Visitor};
18 use rustc_hir::{TraitItem, TraitItemKind};
19 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::lint::in_external_macro;
22 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
23 use rustc_session::{declare_lint_pass, declare_tool_lint};
24 use rustc_span::source_map::Span;
25 use rustc_span::symbol::{sym, SymbolStr};
26
27 use crate::consts::{constant, Constant};
28 use crate::utils::eager_or_lazy::is_lazyness_candidate;
29 use crate::utils::usage::mutated_variables;
30 use crate::utils::{
31     contains_ty, get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait, in_macro,
32     is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment, match_def_path, match_qpath,
33     match_trait_method, match_type, match_var, method_calls, method_chain_args, paths, remove_blocks, return_ty,
34     single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite, span_lint,
35     span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg, walk_ptrs_ty_depth, SpanlessEq,
36 };
37
38 declare_clippy_lint! {
39     /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
40     ///
41     /// **Why is this bad?** It is better to handle the `None` or `Err` case,
42     /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
43     /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
44     /// `Allow` by default.
45     ///
46     /// `result.unwrap()` will let the thread panic on `Err` values.
47     /// Normally, you want to implement more sophisticated error handling,
48     /// and propagate errors upwards with `?` operator.
49     ///
50     /// Even if you want to panic on errors, not all `Error`s implement good
51     /// messages on display. Therefore, it may be beneficial to look at the places
52     /// where they may get displayed. Activate this lint to do just that.
53     ///
54     /// **Known problems:** None.
55     ///
56     /// **Examples:**
57     /// ```rust
58     /// # let opt = Some(1);
59     ///
60     /// // Bad
61     /// opt.unwrap();
62     ///
63     /// // Good
64     /// opt.expect("more helpful message");
65     /// ```
66     ///
67     /// // or
68     ///
69     /// ```rust
70     /// # let res: Result<usize, ()> = Ok(1);
71     ///
72     /// // Bad
73     /// res.unwrap();
74     ///
75     /// // Good
76     /// res.expect("more helpful message");
77     /// ```
78     pub UNWRAP_USED,
79     restriction,
80     "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
81 }
82
83 declare_clippy_lint! {
84     /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
85     ///
86     /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
87     /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
88     /// this lint is `Allow` by default.
89     ///
90     /// `result.expect()` will let the thread panic on `Err`
91     /// values. Normally, you want to implement more sophisticated error handling,
92     /// and propagate errors upwards with `?` operator.
93     ///
94     /// **Known problems:** None.
95     ///
96     /// **Examples:**
97     /// ```rust,ignore
98     /// # let opt = Some(1);
99     ///
100     /// // Bad
101     /// opt.expect("one");
102     ///
103     /// // Good
104     /// let opt = Some(1);
105     /// opt?;
106     /// ```
107     ///
108     /// // or
109     ///
110     /// ```rust
111     /// # let res: Result<usize, ()> = Ok(1);
112     ///
113     /// // Bad
114     /// res.expect("one");
115     ///
116     /// // Good
117     /// res?;
118     /// # Ok::<(), ()>(())
119     /// ```
120     pub EXPECT_USED,
121     restriction,
122     "using `.expect()` on `Result` or `Option`, which might be better handled"
123 }
124
125 declare_clippy_lint! {
126     /// **What it does:** Checks for methods that should live in a trait
127     /// implementation of a `std` trait (see [llogiq's blog
128     /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
129     /// information) instead of an inherent implementation.
130     ///
131     /// **Why is this bad?** Implementing the traits improve ergonomics for users of
132     /// the code, often with very little cost. Also people seeing a `mul(...)`
133     /// method
134     /// may expect `*` to work equally, so you should have good reason to disappoint
135     /// them.
136     ///
137     /// **Known problems:** None.
138     ///
139     /// **Example:**
140     /// ```rust
141     /// struct X;
142     /// impl X {
143     ///     fn add(&self, other: &X) -> X {
144     ///         // ..
145     /// # X
146     ///     }
147     /// }
148     /// ```
149     pub SHOULD_IMPLEMENT_TRAIT,
150     style,
151     "defining a method that should be implementing a std trait"
152 }
153
154 declare_clippy_lint! {
155     /// **What it does:** Checks for methods with certain name prefixes and which
156     /// doesn't match how self is taken. The actual rules are:
157     ///
158     /// |Prefix |`self` taken          |
159     /// |-------|----------------------|
160     /// |`as_`  |`&self` or `&mut self`|
161     /// |`from_`| none                 |
162     /// |`into_`|`self`                |
163     /// |`is_`  |`&self` or none       |
164     /// |`to_`  |`&self`               |
165     ///
166     /// **Why is this bad?** Consistency breeds readability. If you follow the
167     /// conventions, your users won't be surprised that they, e.g., need to supply a
168     /// mutable reference to a `as_..` function.
169     ///
170     /// **Known problems:** None.
171     ///
172     /// **Example:**
173     /// ```rust
174     /// # struct X;
175     /// impl X {
176     ///     fn as_str(self) -> &'static str {
177     ///         // ..
178     /// # ""
179     ///     }
180     /// }
181     /// ```
182     pub WRONG_SELF_CONVENTION,
183     style,
184     "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
185 }
186
187 declare_clippy_lint! {
188     /// **What it does:** This is the same as
189     /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
190     ///
191     /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
192     ///
193     /// **Known problems:** Actually *renaming* the function may break clients if
194     /// the function is part of the public interface. In that case, be mindful of
195     /// the stability guarantees you've given your users.
196     ///
197     /// **Example:**
198     /// ```rust
199     /// # struct X;
200     /// impl<'a> X {
201     ///     pub fn as_str(self) -> &'a str {
202     ///         "foo"
203     ///     }
204     /// }
205     /// ```
206     pub WRONG_PUB_SELF_CONVENTION,
207     restriction,
208     "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
209 }
210
211 declare_clippy_lint! {
212     /// **What it does:** Checks for usage of `ok().expect(..)`.
213     ///
214     /// **Why is this bad?** Because you usually call `expect()` on the `Result`
215     /// directly to get a better error message.
216     ///
217     /// **Known problems:** The error type needs to implement `Debug`
218     ///
219     /// **Example:**
220     /// ```rust
221     /// # let x = Ok::<_, ()>(());
222     ///
223     /// // Bad
224     /// x.ok().expect("why did I do this again?");
225     ///
226     /// // Good
227     /// x.expect("why did I do this again?");
228     /// ```
229     pub OK_EXPECT,
230     style,
231     "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
232 }
233
234 declare_clippy_lint! {
235     /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
236     /// `result.map(_).unwrap_or_else(_)`.
237     ///
238     /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
239     /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
240     ///
241     /// **Known problems:** The order of the arguments is not in execution order
242     ///
243     /// **Examples:**
244     /// ```rust
245     /// # let x = Some(1);
246     ///
247     /// // Bad
248     /// x.map(|a| a + 1).unwrap_or(0);
249     ///
250     /// // Good
251     /// x.map_or(0, |a| a + 1);
252     /// ```
253     ///
254     /// // or
255     ///
256     /// ```rust
257     /// # let x: Result<usize, ()> = Ok(1);
258     /// # fn some_function(foo: ()) -> usize { 1 }
259     ///
260     /// // Bad
261     /// x.map(|a| a + 1).unwrap_or_else(some_function);
262     ///
263     /// // Good
264     /// x.map_or_else(some_function, |a| a + 1);
265     /// ```
266     pub MAP_UNWRAP_OR,
267     pedantic,
268     "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)`"
269 }
270
271 declare_clippy_lint! {
272     /// **What it does:** Checks for usage of `_.map_or(None, _)`.
273     ///
274     /// **Why is this bad?** Readability, this can be written more concisely as
275     /// `_.and_then(_)`.
276     ///
277     /// **Known problems:** The order of the arguments is not in execution order.
278     ///
279     /// **Example:**
280     /// ```rust
281     /// # let opt = Some(1);
282     ///
283     /// // Bad
284     /// opt.map_or(None, |a| Some(a + 1));
285     ///
286     /// // Good
287     /// opt.and_then(|a| Some(a + 1));
288     /// ```
289     pub OPTION_MAP_OR_NONE,
290     style,
291     "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
292 }
293
294 declare_clippy_lint! {
295     /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
296     ///
297     /// **Why is this bad?** Readability, this can be written more concisely as
298     /// `_.ok()`.
299     ///
300     /// **Known problems:** None.
301     ///
302     /// **Example:**
303     ///
304     /// Bad:
305     /// ```rust
306     /// # let r: Result<u32, &str> = Ok(1);
307     /// assert_eq!(Some(1), r.map_or(None, Some));
308     /// ```
309     ///
310     /// Good:
311     /// ```rust
312     /// # let r: Result<u32, &str> = Ok(1);
313     /// assert_eq!(Some(1), r.ok());
314     /// ```
315     pub RESULT_MAP_OR_INTO_OPTION,
316     style,
317     "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
318 }
319
320 declare_clippy_lint! {
321     /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
322     /// `_.or_else(|x| Err(y))`.
323     ///
324     /// **Why is this bad?** Readability, this can be written more concisely as
325     /// `_.map(|x| y)` or `_.map_err(|x| y)`.
326     ///
327     /// **Known problems:** None
328     ///
329     /// **Example:**
330     ///
331     /// ```rust
332     /// # fn opt() -> Option<&'static str> { Some("42") }
333     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
334     /// let _ = opt().and_then(|s| Some(s.len()));
335     /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
336     /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
337     /// ```
338     ///
339     /// The correct use would be:
340     ///
341     /// ```rust
342     /// # fn opt() -> Option<&'static str> { Some("42") }
343     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
344     /// let _ = opt().map(|s| s.len());
345     /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
346     /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
347     /// ```
348     pub BIND_INSTEAD_OF_MAP,
349     complexity,
350     "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
351 }
352
353 declare_clippy_lint! {
354     /// **What it does:** Checks for usage of `_.filter(_).next()`.
355     ///
356     /// **Why is this bad?** Readability, this can be written more concisely as
357     /// `_.find(_)`.
358     ///
359     /// **Known problems:** None.
360     ///
361     /// **Example:**
362     /// ```rust
363     /// # let vec = vec![1];
364     /// vec.iter().filter(|x| **x == 0).next();
365     /// ```
366     /// Could be written as
367     /// ```rust
368     /// # let vec = vec![1];
369     /// vec.iter().find(|x| **x == 0);
370     /// ```
371     pub FILTER_NEXT,
372     complexity,
373     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
374 }
375
376 declare_clippy_lint! {
377     /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
378     ///
379     /// **Why is this bad?** Readability, this can be written more concisely as
380     /// `_.find(!condition)`.
381     ///
382     /// **Known problems:** None.
383     ///
384     /// **Example:**
385     /// ```rust
386     /// # let vec = vec![1];
387     /// vec.iter().skip_while(|x| **x == 0).next();
388     /// ```
389     /// Could be written as
390     /// ```rust
391     /// # let vec = vec![1];
392     /// vec.iter().find(|x| **x != 0);
393     /// ```
394     pub SKIP_WHILE_NEXT,
395     complexity,
396     "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
397 }
398
399 declare_clippy_lint! {
400     /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
401     ///
402     /// **Why is this bad?** Readability, this can be written more concisely as
403     /// `_.flat_map(_)`
404     ///
405     /// **Known problems:**
406     ///
407     /// **Example:**
408     /// ```rust
409     /// let vec = vec![vec![1]];
410     ///
411     /// // Bad
412     /// vec.iter().map(|x| x.iter()).flatten();
413     ///
414     /// // Good
415     /// vec.iter().flat_map(|x| x.iter());
416     /// ```
417     pub MAP_FLATTEN,
418     pedantic,
419     "using combinations of `flatten` and `map` which can usually be written as a single method call"
420 }
421
422 declare_clippy_lint! {
423     /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
424     /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
425     ///
426     /// **Why is this bad?** Readability, this can be written more concisely as
427     /// `_.filter_map(_)`.
428     ///
429     /// **Known problems:** Often requires a condition + Option/Iterator creation
430     /// inside the closure.
431     ///
432     /// **Example:**
433     /// ```rust
434     /// let vec = vec![1];
435     ///
436     /// // Bad
437     /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
438     ///
439     /// // Good
440     /// vec.iter().filter_map(|x| if *x == 0 {
441     ///     Some(*x * 2)
442     /// } else {
443     ///     None
444     /// });
445     /// ```
446     pub FILTER_MAP,
447     pedantic,
448     "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
449 }
450
451 declare_clippy_lint! {
452     /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
453     ///
454     /// **Why is this bad?** Readability, this can be written more concisely as
455     /// `_.find_map(_)`.
456     ///
457     /// **Known problems:** None
458     ///
459     /// **Example:**
460     /// ```rust
461     ///  (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
462     /// ```
463     /// Can be written as
464     ///
465     /// ```rust
466     ///  (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
467     /// ```
468     pub FILTER_MAP_NEXT,
469     pedantic,
470     "using combination of `filter_map` and `next` which can usually be written as a single method call"
471 }
472
473 declare_clippy_lint! {
474     /// **What it does:** Checks for usage of `flat_map(|x| x)`.
475     ///
476     /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
477     ///
478     /// **Known problems:** None
479     ///
480     /// **Example:**
481     /// ```rust
482     /// # let iter = vec![vec![0]].into_iter();
483     /// iter.flat_map(|x| x);
484     /// ```
485     /// Can be written as
486     /// ```rust
487     /// # let iter = vec![vec![0]].into_iter();
488     /// iter.flatten();
489     /// ```
490     pub FLAT_MAP_IDENTITY,
491     complexity,
492     "call to `flat_map` where `flatten` is sufficient"
493 }
494
495 declare_clippy_lint! {
496     /// **What it does:** Checks for usage of `_.find(_).map(_)`.
497     ///
498     /// **Why is this bad?** Readability, this can be written more concisely as
499     /// `_.find_map(_)`.
500     ///
501     /// **Known problems:** Often requires a condition + Option/Iterator creation
502     /// inside the closure.
503     ///
504     /// **Example:**
505     /// ```rust
506     ///  (0..3).find(|x| *x == 2).map(|x| x * 2);
507     /// ```
508     /// Can be written as
509     /// ```rust
510     ///  (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
511     /// ```
512     pub FIND_MAP,
513     pedantic,
514     "using a combination of `find` and `map` can usually be written as a single method call"
515 }
516
517 declare_clippy_lint! {
518     /// **What it does:** Checks for an iterator search (such as `find()`,
519     /// `position()`, or `rposition()`) followed by a call to `is_some()`.
520     ///
521     /// **Why is this bad?** Readability, this can be written more concisely as
522     /// `_.any(_)`.
523     ///
524     /// **Known problems:** None.
525     ///
526     /// **Example:**
527     /// ```rust
528     /// # let vec = vec![1];
529     /// vec.iter().find(|x| **x == 0).is_some();
530     /// ```
531     /// Could be written as
532     /// ```rust
533     /// # let vec = vec![1];
534     /// vec.iter().any(|x| *x == 0);
535     /// ```
536     pub SEARCH_IS_SOME,
537     complexity,
538     "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
539 }
540
541 declare_clippy_lint! {
542     /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
543     /// if it starts with a given char.
544     ///
545     /// **Why is this bad?** Readability, this can be written more concisely as
546     /// `_.starts_with(_)`.
547     ///
548     /// **Known problems:** None.
549     ///
550     /// **Example:**
551     /// ```rust
552     /// let name = "foo";
553     /// if name.chars().next() == Some('_') {};
554     /// ```
555     /// Could be written as
556     /// ```rust
557     /// let name = "foo";
558     /// if name.starts_with('_') {};
559     /// ```
560     pub CHARS_NEXT_CMP,
561     style,
562     "using `.chars().next()` to check if a string starts with a char"
563 }
564
565 declare_clippy_lint! {
566     /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
567     /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
568     /// `unwrap_or_default` instead.
569     ///
570     /// **Why is this bad?** The function will always be called and potentially
571     /// allocate an object acting as the default.
572     ///
573     /// **Known problems:** If the function has side-effects, not calling it will
574     /// change the semantic of the program, but you shouldn't rely on that anyway.
575     ///
576     /// **Example:**
577     /// ```rust
578     /// # let foo = Some(String::new());
579     /// foo.unwrap_or(String::new());
580     /// ```
581     /// this can instead be written:
582     /// ```rust
583     /// # let foo = Some(String::new());
584     /// foo.unwrap_or_else(String::new);
585     /// ```
586     /// or
587     /// ```rust
588     /// # let foo = Some(String::new());
589     /// foo.unwrap_or_default();
590     /// ```
591     pub OR_FUN_CALL,
592     perf,
593     "using any `*or` method with a function call, which suggests `*or_else`"
594 }
595
596 declare_clippy_lint! {
597     /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
598     /// etc., and suggests to use `unwrap_or_else` instead
599     ///
600     /// **Why is this bad?** The function will always be called.
601     ///
602     /// **Known problems:** If the function has side-effects, not calling it will
603     /// change the semantics of the program, but you shouldn't rely on that anyway.
604     ///
605     /// **Example:**
606     /// ```rust
607     /// # let foo = Some(String::new());
608     /// # let err_code = "418";
609     /// # let err_msg = "I'm a teapot";
610     /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
611     /// ```
612     /// or
613     /// ```rust
614     /// # let foo = Some(String::new());
615     /// # let err_code = "418";
616     /// # let err_msg = "I'm a teapot";
617     /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
618     /// ```
619     /// this can instead be written:
620     /// ```rust
621     /// # let foo = Some(String::new());
622     /// # let err_code = "418";
623     /// # let err_msg = "I'm a teapot";
624     /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
625     /// ```
626     pub EXPECT_FUN_CALL,
627     perf,
628     "using any `expect` method with a function call"
629 }
630
631 declare_clippy_lint! {
632     /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
633     ///
634     /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
635     /// generics, not for using the `clone` method on a concrete type.
636     ///
637     /// **Known problems:** None.
638     ///
639     /// **Example:**
640     /// ```rust
641     /// 42u64.clone();
642     /// ```
643     pub CLONE_ON_COPY,
644     complexity,
645     "using `clone` on a `Copy` type"
646 }
647
648 declare_clippy_lint! {
649     /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
650     /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
651     /// function syntax instead (e.g., `Rc::clone(foo)`).
652     ///
653     /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
654     /// can obscure the fact that only the pointer is being cloned, not the underlying
655     /// data.
656     ///
657     /// **Example:**
658     /// ```rust
659     /// # use std::rc::Rc;
660     /// let x = Rc::new(1);
661     ///
662     /// // Bad
663     /// x.clone();
664     ///
665     /// // Good
666     /// Rc::clone(&x);
667     /// ```
668     pub CLONE_ON_REF_PTR,
669     restriction,
670     "using 'clone' on a ref-counted pointer"
671 }
672
673 declare_clippy_lint! {
674     /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
675     ///
676     /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
677     /// cloning the underlying `T`.
678     ///
679     /// **Known problems:** None.
680     ///
681     /// **Example:**
682     /// ```rust
683     /// fn main() {
684     ///     let x = vec![1];
685     ///     let y = &&x;
686     ///     let z = y.clone();
687     ///     println!("{:p} {:p}", *y, z); // prints out the same pointer
688     /// }
689     /// ```
690     pub CLONE_DOUBLE_REF,
691     correctness,
692     "using `clone` on `&&T`"
693 }
694
695 declare_clippy_lint! {
696     /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
697     /// `T` implements `ToString` directly (like `&&str` or `&&String`).
698     ///
699     /// **Why is this bad?** This bypasses the specialized implementation of
700     /// `ToString` and instead goes through the more expensive string formatting
701     /// facilities.
702     ///
703     /// **Known problems:** None.
704     ///
705     /// **Example:**
706     /// ```rust
707     /// // Generic implementation for `T: Display` is used (slow)
708     /// ["foo", "bar"].iter().map(|s| s.to_string());
709     ///
710     /// // OK, the specialized impl is used
711     /// ["foo", "bar"].iter().map(|&s| s.to_string());
712     /// ```
713     pub INEFFICIENT_TO_STRING,
714     pedantic,
715     "using `to_string` on `&&T` where `T: ToString`"
716 }
717
718 declare_clippy_lint! {
719     /// **What it does:** Checks for `new` not returning a type that contains `Self`.
720     ///
721     /// **Why is this bad?** As a convention, `new` methods are used to make a new
722     /// instance of a type.
723     ///
724     /// **Known problems:** None.
725     ///
726     /// **Example:**
727     /// In an impl block:
728     /// ```rust
729     /// # struct Foo;
730     /// # struct NotAFoo;
731     /// impl Foo {
732     ///     fn new() -> NotAFoo {
733     /// # NotAFoo
734     ///     }
735     /// }
736     /// ```
737     ///
738     /// ```rust
739     /// # struct Foo;
740     /// struct Bar(Foo);
741     /// impl Foo {
742     ///     // Bad. The type name must contain `Self`
743     ///     fn new() -> Bar {
744     /// # Bar(Foo)
745     ///     }
746     /// }
747     /// ```
748     ///
749     /// ```rust
750     /// # struct Foo;
751     /// # struct FooError;
752     /// impl Foo {
753     ///     // Good. Return type contains `Self`
754     ///     fn new() -> Result<Foo, FooError> {
755     /// # Ok(Foo)
756     ///     }
757     /// }
758     /// ```
759     ///
760     /// Or in a trait definition:
761     /// ```rust
762     /// pub trait Trait {
763     ///     // Bad. The type name must contain `Self`
764     ///     fn new();
765     /// }
766     /// ```
767     ///
768     /// ```rust
769     /// pub trait Trait {
770     ///     // Good. Return type contains `Self`
771     ///     fn new() -> Self;
772     /// }
773     /// ```
774     pub NEW_RET_NO_SELF,
775     style,
776     "not returning type containing `Self` in a `new` method"
777 }
778
779 declare_clippy_lint! {
780     /// **What it does:** Checks for string methods that receive a single-character
781     /// `str` as an argument, e.g., `_.split("x")`.
782     ///
783     /// **Why is this bad?** Performing these methods using a `char` is faster than
784     /// using a `str`.
785     ///
786     /// **Known problems:** Does not catch multi-byte unicode characters.
787     ///
788     /// **Example:**
789     /// ```rust,ignore
790     /// // Bad
791     /// _.split("x");
792     ///
793     /// // Good
794     /// _.split('x');
795     pub SINGLE_CHAR_PATTERN,
796     perf,
797     "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
798 }
799
800 declare_clippy_lint! {
801     /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
802     ///
803     /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
804     /// actually intend to panic.
805     ///
806     /// **Known problems:** None.
807     ///
808     /// **Example:**
809     /// ```rust,should_panic
810     /// for x in (0..100).step_by(0) {
811     ///     //..
812     /// }
813     /// ```
814     pub ITERATOR_STEP_BY_ZERO,
815     correctness,
816     "using `Iterator::step_by(0)`, which will panic at runtime"
817 }
818
819 declare_clippy_lint! {
820     /// **What it does:** Checks for the use of `iter.nth(0)`.
821     ///
822     /// **Why is this bad?** `iter.next()` is equivalent to
823     /// `iter.nth(0)`, as they both consume the next element,
824     ///  but is more readable.
825     ///
826     /// **Known problems:** None.
827     ///
828     /// **Example:**
829     ///
830     /// ```rust
831     /// # use std::collections::HashSet;
832     /// // Bad
833     /// # let mut s = HashSet::new();
834     /// # s.insert(1);
835     /// let x = s.iter().nth(0);
836     ///
837     /// // Good
838     /// # let mut s = HashSet::new();
839     /// # s.insert(1);
840     /// let x = s.iter().next();
841     /// ```
842     pub ITER_NTH_ZERO,
843     style,
844     "replace `iter.nth(0)` with `iter.next()`"
845 }
846
847 declare_clippy_lint! {
848     /// **What it does:** Checks for use of `.iter().nth()` (and the related
849     /// `.iter_mut().nth()`) on standard library types with O(1) element access.
850     ///
851     /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
852     /// readable.
853     ///
854     /// **Known problems:** None.
855     ///
856     /// **Example:**
857     /// ```rust
858     /// let some_vec = vec![0, 1, 2, 3];
859     /// let bad_vec = some_vec.iter().nth(3);
860     /// let bad_slice = &some_vec[..].iter().nth(3);
861     /// ```
862     /// The correct use would be:
863     /// ```rust
864     /// let some_vec = vec![0, 1, 2, 3];
865     /// let bad_vec = some_vec.get(3);
866     /// let bad_slice = &some_vec[..].get(3);
867     /// ```
868     pub ITER_NTH,
869     perf,
870     "using `.iter().nth()` on a standard library type with O(1) element access"
871 }
872
873 declare_clippy_lint! {
874     /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
875     ///
876     /// **Why is this bad?** `.nth(x)` is cleaner
877     ///
878     /// **Known problems:** None.
879     ///
880     /// **Example:**
881     /// ```rust
882     /// let some_vec = vec![0, 1, 2, 3];
883     /// let bad_vec = some_vec.iter().skip(3).next();
884     /// let bad_slice = &some_vec[..].iter().skip(3).next();
885     /// ```
886     /// The correct use would be:
887     /// ```rust
888     /// let some_vec = vec![0, 1, 2, 3];
889     /// let bad_vec = some_vec.iter().nth(3);
890     /// let bad_slice = &some_vec[..].iter().nth(3);
891     /// ```
892     pub ITER_SKIP_NEXT,
893     style,
894     "using `.skip(x).next()` on an iterator"
895 }
896
897 declare_clippy_lint! {
898     /// **What it does:** Checks for use of `.get().unwrap()` (or
899     /// `.get_mut().unwrap`) on a standard library type which implements `Index`
900     ///
901     /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
902     /// concise.
903     ///
904     /// **Known problems:** Not a replacement for error handling: Using either
905     /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
906     /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
907     /// temporary placeholder for dealing with the `Option` type, then this does
908     /// not mitigate the need for error handling. If there is a chance that `.get()`
909     /// will be `None` in your program, then it is advisable that the `None` case
910     /// is handled in a future refactor instead of using `.unwrap()` or the Index
911     /// trait.
912     ///
913     /// **Example:**
914     /// ```rust
915     /// let mut some_vec = vec![0, 1, 2, 3];
916     /// let last = some_vec.get(3).unwrap();
917     /// *some_vec.get_mut(0).unwrap() = 1;
918     /// ```
919     /// The correct use would be:
920     /// ```rust
921     /// let mut some_vec = vec![0, 1, 2, 3];
922     /// let last = some_vec[3];
923     /// some_vec[0] = 1;
924     /// ```
925     pub GET_UNWRAP,
926     restriction,
927     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
928 }
929
930 declare_clippy_lint! {
931     /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
932     /// `&str` or `String`.
933     ///
934     /// **Why is this bad?** `.push_str(s)` is clearer
935     ///
936     /// **Known problems:** None.
937     ///
938     /// **Example:**
939     /// ```rust
940     /// let abc = "abc";
941     /// let def = String::from("def");
942     /// let mut s = String::new();
943     /// s.extend(abc.chars());
944     /// s.extend(def.chars());
945     /// ```
946     /// The correct use would be:
947     /// ```rust
948     /// let abc = "abc";
949     /// let def = String::from("def");
950     /// let mut s = String::new();
951     /// s.push_str(abc);
952     /// s.push_str(&def);
953     /// ```
954     pub STRING_EXTEND_CHARS,
955     style,
956     "using `x.extend(s.chars())` where s is a `&str` or `String`"
957 }
958
959 declare_clippy_lint! {
960     /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
961     /// create a `Vec`.
962     ///
963     /// **Why is this bad?** `.to_vec()` is clearer
964     ///
965     /// **Known problems:** None.
966     ///
967     /// **Example:**
968     /// ```rust
969     /// let s = [1, 2, 3, 4, 5];
970     /// let s2: Vec<isize> = s[..].iter().cloned().collect();
971     /// ```
972     /// The better use would be:
973     /// ```rust
974     /// let s = [1, 2, 3, 4, 5];
975     /// let s2: Vec<isize> = s.to_vec();
976     /// ```
977     pub ITER_CLONED_COLLECT,
978     style,
979     "using `.cloned().collect()` on slice to create a `Vec`"
980 }
981
982 declare_clippy_lint! {
983     /// **What it does:** Checks for usage of `_.chars().last()` or
984     /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
985     ///
986     /// **Why is this bad?** Readability, this can be written more concisely as
987     /// `_.ends_with(_)`.
988     ///
989     /// **Known problems:** None.
990     ///
991     /// **Example:**
992     /// ```rust
993     /// # let name = "_";
994     ///
995     /// // Bad
996     /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
997     ///
998     /// // Good
999     /// name.ends_with('_') || name.ends_with('-');
1000     /// ```
1001     pub CHARS_LAST_CMP,
1002     style,
1003     "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1004 }
1005
1006 declare_clippy_lint! {
1007     /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1008     /// types before and after the call are the same.
1009     ///
1010     /// **Why is this bad?** The call is unnecessary.
1011     ///
1012     /// **Known problems:** None.
1013     ///
1014     /// **Example:**
1015     /// ```rust
1016     /// # fn do_stuff(x: &[i32]) {}
1017     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1018     /// do_stuff(x.as_ref());
1019     /// ```
1020     /// The correct use would be:
1021     /// ```rust
1022     /// # fn do_stuff(x: &[i32]) {}
1023     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1024     /// do_stuff(x);
1025     /// ```
1026     pub USELESS_ASREF,
1027     complexity,
1028     "using `as_ref` where the types before and after the call are the same"
1029 }
1030
1031 declare_clippy_lint! {
1032     /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1033     /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1034     /// `sum` or `product`.
1035     ///
1036     /// **Why is this bad?** Readability.
1037     ///
1038     /// **Known problems:** None.
1039     ///
1040     /// **Example:**
1041     /// ```rust
1042     /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1043     /// ```
1044     /// This could be written as:
1045     /// ```rust
1046     /// let _ = (0..3).any(|x| x > 2);
1047     /// ```
1048     pub UNNECESSARY_FOLD,
1049     style,
1050     "using `fold` when a more succinct alternative exists"
1051 }
1052
1053 declare_clippy_lint! {
1054     /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1055     /// More specifically it checks if the closure provided is only performing one of the
1056     /// filter or map operations and suggests the appropriate option.
1057     ///
1058     /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1059     /// operation is being performed.
1060     ///
1061     /// **Known problems:** None
1062     ///
1063     /// **Example:**
1064     /// ```rust
1065     /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1066     ///
1067     /// // As there is no transformation of the argument this could be written as:
1068     /// let _ = (0..3).filter(|&x| x > 2);
1069     /// ```
1070     ///
1071     /// ```rust
1072     /// let _ = (0..4).filter_map(|x| Some(x + 1));
1073     ///
1074     /// // As there is no conditional check on the argument this could be written as:
1075     /// let _ = (0..4).map(|x| x + 1);
1076     /// ```
1077     pub UNNECESSARY_FILTER_MAP,
1078     complexity,
1079     "using `filter_map` when a more succinct alternative exists"
1080 }
1081
1082 declare_clippy_lint! {
1083     /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1084     /// or `iter_mut`.
1085     ///
1086     /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1087     /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1088     /// `iter_mut` directly.
1089     ///
1090     /// **Known problems:** None
1091     ///
1092     /// **Example:**
1093     ///
1094     /// ```rust
1095     /// // Bad
1096     /// let _ = (&vec![3, 4, 5]).into_iter();
1097     ///
1098     /// // Good
1099     /// let _ = (&vec![3, 4, 5]).iter();
1100     /// ```
1101     pub INTO_ITER_ON_REF,
1102     style,
1103     "using `.into_iter()` on a reference"
1104 }
1105
1106 declare_clippy_lint! {
1107     /// **What it does:** Checks for calls to `map` followed by a `count`.
1108     ///
1109     /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1110     /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1111     /// drive the iterator to completion, you can just use `for_each` instead.
1112     ///
1113     /// **Known problems:** None
1114     ///
1115     /// **Example:**
1116     ///
1117     /// ```rust
1118     /// let _ = (0..3).map(|x| x + 2).count();
1119     /// ```
1120     pub SUSPICIOUS_MAP,
1121     complexity,
1122     "suspicious usage of map"
1123 }
1124
1125 declare_clippy_lint! {
1126     /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1127     ///
1128     /// **Why is this bad?** For most types, this is undefined behavior.
1129     ///
1130     /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1131     /// of `MaybeUninit`. There may be other types that allow uninitialized
1132     /// data, but those are not yet rigorously defined.
1133     ///
1134     /// **Example:**
1135     ///
1136     /// ```rust
1137     /// // Beware the UB
1138     /// use std::mem::MaybeUninit;
1139     ///
1140     /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1141     /// ```
1142     ///
1143     /// Note that the following is OK:
1144     ///
1145     /// ```rust
1146     /// use std::mem::MaybeUninit;
1147     ///
1148     /// let _: [MaybeUninit<bool>; 5] = unsafe {
1149     ///     MaybeUninit::uninit().assume_init()
1150     /// };
1151     /// ```
1152     pub UNINIT_ASSUMED_INIT,
1153     correctness,
1154     "`MaybeUninit::uninit().assume_init()`"
1155 }
1156
1157 declare_clippy_lint! {
1158     /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1159     ///
1160     /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1161     ///
1162     /// **Example:**
1163     ///
1164     /// ```rust
1165     /// # let y: u32 = 0;
1166     /// # let x: u32 = 100;
1167     /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1168     /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1169     /// ```
1170     ///
1171     /// can be written using dedicated methods for saturating addition/subtraction as:
1172     ///
1173     /// ```rust
1174     /// # let y: u32 = 0;
1175     /// # let x: u32 = 100;
1176     /// let add = x.saturating_add(y);
1177     /// let sub = x.saturating_sub(y);
1178     /// ```
1179     pub MANUAL_SATURATING_ARITHMETIC,
1180     style,
1181     "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1182 }
1183
1184 declare_clippy_lint! {
1185     /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1186     /// zero-sized types
1187     ///
1188     /// **Why is this bad?** This is a no-op, and likely unintended
1189     ///
1190     /// **Known problems:** None
1191     ///
1192     /// **Example:**
1193     /// ```rust
1194     /// unsafe { (&() as *const ()).offset(1) };
1195     /// ```
1196     pub ZST_OFFSET,
1197     correctness,
1198     "Check for offset calculations on raw pointers to zero-sized types"
1199 }
1200
1201 declare_clippy_lint! {
1202     /// **What it does:** Checks for `FileType::is_file()`.
1203     ///
1204     /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1205     /// they are testing whether a path is something they can get bytes from. But
1206     /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1207     /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1208     ///
1209     /// **Example:**
1210     ///
1211     /// ```rust
1212     /// # || {
1213     /// let metadata = std::fs::metadata("foo.txt")?;
1214     /// let filetype = metadata.file_type();
1215     ///
1216     /// if filetype.is_file() {
1217     ///     // read file
1218     /// }
1219     /// # Ok::<_, std::io::Error>(())
1220     /// # };
1221     /// ```
1222     ///
1223     /// should be written as:
1224     ///
1225     /// ```rust
1226     /// # || {
1227     /// let metadata = std::fs::metadata("foo.txt")?;
1228     /// let filetype = metadata.file_type();
1229     ///
1230     /// if !filetype.is_dir() {
1231     ///     // read file
1232     /// }
1233     /// # Ok::<_, std::io::Error>(())
1234     /// # };
1235     /// ```
1236     pub FILETYPE_IS_FILE,
1237     restriction,
1238     "`FileType::is_file` is not recommended to test for readable file type"
1239 }
1240
1241 declare_clippy_lint! {
1242     /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1243     ///
1244     /// **Why is this bad?** Readability, this can be written more concisely as
1245     /// `_.as_deref()`.
1246     ///
1247     /// **Known problems:** None.
1248     ///
1249     /// **Example:**
1250     /// ```rust
1251     /// # let opt = Some("".to_string());
1252     /// opt.as_ref().map(String::as_str)
1253     /// # ;
1254     /// ```
1255     /// Can be written as
1256     /// ```rust
1257     /// # let opt = Some("".to_string());
1258     /// opt.as_deref()
1259     /// # ;
1260     /// ```
1261     pub OPTION_AS_REF_DEREF,
1262     complexity,
1263     "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1264 }
1265
1266 declare_clippy_lint! {
1267     /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1268     ///
1269     /// **Why is this bad?** These can be shortened into `.get()`
1270     ///
1271     /// **Known problems:** None.
1272     ///
1273     /// **Example:**
1274     /// ```rust
1275     /// # let a = [1, 2, 3];
1276     /// # let b = vec![1, 2, 3];
1277     /// a[2..].iter().next();
1278     /// b.iter().next();
1279     /// ```
1280     /// should be written as:
1281     /// ```rust
1282     /// # let a = [1, 2, 3];
1283     /// # let b = vec![1, 2, 3];
1284     /// a.get(2);
1285     /// b.get(0);
1286     /// ```
1287     pub ITER_NEXT_SLICE,
1288     style,
1289     "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1290 }
1291
1292 declare_clippy_lint! {
1293     /// **What it does:** Warns when using `push_str` with a single-character string literal
1294     /// where `push` with a `char` would work fine.
1295     ///
1296     /// **Why is this bad?** It's less clear that we are pushing a single character.
1297     ///
1298     /// **Known problems:** None
1299     ///
1300     /// **Example:**
1301     /// ```rust
1302     /// let mut string = String::new();
1303     /// string.push_str("R");
1304     /// ```
1305     /// Could be written as
1306     /// ```rust
1307     /// let mut string = String::new();
1308     /// string.push('R');
1309     /// ```
1310     pub SINGLE_CHAR_PUSH_STR,
1311     style,
1312     "`push_str()` used with a single-character string literal as parameter"
1313 }
1314
1315 declare_clippy_lint! {
1316     /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1317     /// lazily evaluated closures on `Option` and `Result`.
1318     ///
1319     /// This lint suggests changing the following functions, when eager evaluation results in
1320     /// simpler code:
1321     ///  - `unwrap_or_else` to `unwrap_or`
1322     ///  - `and_then` to `and`
1323     ///  - `or_else` to `or`
1324     ///  - `get_or_insert_with` to `get_or_insert`
1325     ///  - `ok_or_else` to `ok_or`
1326     ///
1327     /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1328     ///
1329     /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1330     /// side effects. Eagerly evaluating them can change the semantics of the program.
1331     ///
1332     /// **Example:**
1333     ///
1334     /// ```rust
1335     /// // example code where clippy issues a warning
1336     /// let opt: Option<u32> = None;
1337     ///
1338     /// opt.unwrap_or_else(|| 42);
1339     /// ```
1340     /// Use instead:
1341     /// ```rust
1342     /// let opt: Option<u32> = None;
1343     ///
1344     /// opt.unwrap_or(42);
1345     /// ```
1346     pub UNNECESSARY_LAZY_EVALUATIONS,
1347     style,
1348     "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1349 }
1350
1351 declare_clippy_lint! {
1352     /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(),_>()`.
1353     ///
1354     /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1355     ///
1356     /// **Known problems:** None
1357     ///
1358     /// **Example:**
1359     ///
1360     /// ```rust
1361     /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1362     /// ```
1363     /// Use instead:
1364     /// ```rust
1365     /// (0..3).try_for_each(|t| Err(t));
1366     /// ```
1367     pub MAP_COLLECT_RESULT_UNIT,
1368     style,
1369     "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1370 }
1371
1372 declare_lint_pass!(Methods => [
1373     UNWRAP_USED,
1374     EXPECT_USED,
1375     SHOULD_IMPLEMENT_TRAIT,
1376     WRONG_SELF_CONVENTION,
1377     WRONG_PUB_SELF_CONVENTION,
1378     OK_EXPECT,
1379     MAP_UNWRAP_OR,
1380     RESULT_MAP_OR_INTO_OPTION,
1381     OPTION_MAP_OR_NONE,
1382     BIND_INSTEAD_OF_MAP,
1383     OR_FUN_CALL,
1384     EXPECT_FUN_CALL,
1385     CHARS_NEXT_CMP,
1386     CHARS_LAST_CMP,
1387     CLONE_ON_COPY,
1388     CLONE_ON_REF_PTR,
1389     CLONE_DOUBLE_REF,
1390     INEFFICIENT_TO_STRING,
1391     NEW_RET_NO_SELF,
1392     SINGLE_CHAR_PATTERN,
1393     SINGLE_CHAR_PUSH_STR,
1394     SEARCH_IS_SOME,
1395     FILTER_NEXT,
1396     SKIP_WHILE_NEXT,
1397     FILTER_MAP,
1398     FILTER_MAP_NEXT,
1399     FLAT_MAP_IDENTITY,
1400     FIND_MAP,
1401     MAP_FLATTEN,
1402     ITERATOR_STEP_BY_ZERO,
1403     ITER_NEXT_SLICE,
1404     ITER_NTH,
1405     ITER_NTH_ZERO,
1406     ITER_SKIP_NEXT,
1407     GET_UNWRAP,
1408     STRING_EXTEND_CHARS,
1409     ITER_CLONED_COLLECT,
1410     USELESS_ASREF,
1411     UNNECESSARY_FOLD,
1412     UNNECESSARY_FILTER_MAP,
1413     INTO_ITER_ON_REF,
1414     SUSPICIOUS_MAP,
1415     UNINIT_ASSUMED_INIT,
1416     MANUAL_SATURATING_ARITHMETIC,
1417     ZST_OFFSET,
1418     FILETYPE_IS_FILE,
1419     OPTION_AS_REF_DEREF,
1420     UNNECESSARY_LAZY_EVALUATIONS,
1421     MAP_COLLECT_RESULT_UNIT,
1422 ]);
1423
1424 impl<'tcx> LateLintPass<'tcx> for Methods {
1425     #[allow(clippy::too_many_lines)]
1426     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1427         if in_macro(expr.span) {
1428             return;
1429         }
1430
1431         let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1432         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1433         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1434
1435         match method_names.as_slice() {
1436             ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1437             ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1438             ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1439             ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1440             ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1441             ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1442             ["unwrap_or_else", "map"] => {
1443                 if !lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]) {
1444                     unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or");
1445                 }
1446             },
1447             ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1448             ["and_then", ..] => {
1449                 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
1450                 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
1451                 if !biom_option_linted && !biom_result_linted {
1452                     unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "and");
1453                 }
1454             },
1455             ["or_else", ..] => {
1456                 if !bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]) {
1457                     unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "or");
1458                 }
1459             },
1460             ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1461             ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1462             ["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
1463             ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1464             ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1465             ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
1466             ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
1467             ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1468             ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1469             ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1470             ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1471             ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1472             ["is_some", "position"] => {
1473                 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1474             },
1475             ["is_some", "rposition"] => {
1476                 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1477             },
1478             ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1479             ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1480             ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1481             ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1482             ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1483             ["next", "skip"] => lint_iter_skip_next(cx, expr, arg_lists[1]),
1484             ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1485             ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1486             ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1487             ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1488             ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1489             ["count", "map"] => lint_suspicious_map(cx, expr),
1490             ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1491             ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1492                 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1493             },
1494             ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1495                 check_pointer_offset(cx, expr, arg_lists[0])
1496             },
1497             ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1498             ["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1499             ["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1500             ["unwrap_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or"),
1501             ["get_or_insert_with", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "get_or_insert"),
1502             ["ok_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "ok_or"),
1503             ["collect", "map"] => lint_map_collect(cx, expr, arg_lists[1], arg_lists[0]),
1504             _ => {},
1505         }
1506
1507         match expr.kind {
1508             hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1509                 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1510                 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1511
1512                 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1513                 if args.len() == 1 && method_call.ident.name == sym!(clone) {
1514                     lint_clone_on_copy(cx, expr, &args[0], self_ty);
1515                     lint_clone_on_ref_ptr(cx, expr, &args[0]);
1516                 }
1517                 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1518                     inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1519                 }
1520
1521                 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
1522                     if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
1523                         lint_single_char_push_string(cx, expr, args);
1524                     } else if match_def_path(cx, fn_def_id, &paths::INSERT_STR) {
1525                         lint_single_char_insert_string(cx, expr, args);
1526                     }
1527                 }
1528
1529                 match self_ty.kind() {
1530                     ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
1531                         for &(method, pos) in &PATTERN_METHODS {
1532                             if method_call.ident.name.as_str() == method && args.len() > pos {
1533                                 lint_single_char_pattern(cx, expr, &args[pos]);
1534                             }
1535                         }
1536                     },
1537                     ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
1538                         lint_into_iter(cx, expr, self_ty, *method_span);
1539                     },
1540                     _ => (),
1541                 }
1542             },
1543             hir::ExprKind::Binary(op, ref lhs, ref rhs)
1544                 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1545             {
1546                 let mut info = BinaryExprInfo {
1547                     expr,
1548                     chain: lhs,
1549                     other: rhs,
1550                     eq: op.node == hir::BinOpKind::Eq,
1551                 };
1552                 lint_binary_expr_with_method_call(cx, &mut info);
1553             }
1554             _ => (),
1555         }
1556     }
1557
1558     #[allow(clippy::too_many_lines)]
1559     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1560         if in_external_macro(cx.sess(), impl_item.span) {
1561             return;
1562         }
1563         let name = impl_item.ident.name.as_str();
1564         let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1565         let item = cx.tcx.hir().expect_item(parent);
1566         let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1567         let self_ty = cx.tcx.type_of(def_id);
1568         if_chain! {
1569             if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1570             if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1571             if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
1572
1573             let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1574             let method_sig = cx.tcx.fn_sig(method_def_id);
1575             let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
1576
1577             let first_arg_ty = &method_sig.inputs().iter().next();
1578
1579             // check conventions w.r.t. conversion method names and predicates
1580             if let Some(first_arg_ty) = first_arg_ty;
1581
1582             then {
1583                 if cx.access_levels.is_exported(impl_item.hir_id) {
1584                     // check missing trait implementations
1585                     for method_config in &TRAIT_METHODS {
1586                         if name == method_config.method_name &&
1587                             sig.decl.inputs.len() == method_config.param_count &&
1588                             method_config.output_type.matches(cx, &sig.decl.output) &&
1589                             method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1590                             fn_header_equals(method_config.fn_header, sig.header) &&
1591                             method_config.lifetime_param_cond(&impl_item)
1592                         {
1593                             span_lint_and_help(
1594                                 cx,
1595                                 SHOULD_IMPLEMENT_TRAIT,
1596                                 impl_item.span,
1597                                 &format!(
1598                                     "method `{}` can be confused for the standard trait method `{}::{}`",
1599                                     method_config.method_name,
1600                                     method_config.trait_name,
1601                                     method_config.method_name
1602                                 ),
1603                                 None,
1604                                 &format!(
1605                                     "consider implementing the trait `{}` or choosing a less ambiguous method name",
1606                                     method_config.trait_name
1607                                 )
1608                             );
1609                         }
1610                     }
1611                 }
1612
1613                 if let Some((ref conv, self_kinds)) = &CONVENTIONS
1614                     .iter()
1615                     .find(|(ref conv, _)| conv.check(&name))
1616                 {
1617                     if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1618                         let lint = if item.vis.node.is_pub() {
1619                             WRONG_PUB_SELF_CONVENTION
1620                         } else {
1621                             WRONG_SELF_CONVENTION
1622                         };
1623
1624                         span_lint(
1625                             cx,
1626                             lint,
1627                             first_arg.pat.span,
1628                             &format!("methods called `{}` usually take {}; consider choosing a less ambiguous name",
1629                                 conv,
1630                                 &self_kinds
1631                                     .iter()
1632                                     .map(|k| k.description())
1633                                     .collect::<Vec<_>>()
1634                                     .join(" or ")
1635                             ),
1636                         );
1637                     }
1638                 }
1639             }
1640         }
1641
1642         // if this impl block implements a trait, lint in trait definition instead
1643         if let hir::ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
1644             return;
1645         }
1646
1647         if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1648             let ret_ty = return_ty(cx, impl_item.hir_id);
1649
1650             // walk the return type and check for Self (this does not check associated types)
1651             if contains_ty(ret_ty, self_ty) {
1652                 return;
1653             }
1654
1655             // if return type is impl trait, check the associated types
1656             if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1657                 // one of the associated types must be Self
1658                 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1659                     if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() {
1660                         // walk the associated type and check for Self
1661                         if contains_ty(projection_predicate.ty, self_ty) {
1662                             return;
1663                         }
1664                     }
1665                 }
1666             }
1667
1668             if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1669                 span_lint(
1670                     cx,
1671                     NEW_RET_NO_SELF,
1672                     impl_item.span,
1673                     "methods called `new` usually return `Self`",
1674                 );
1675             }
1676         }
1677     }
1678
1679     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1680         if_chain! {
1681             if !in_external_macro(cx.tcx.sess, item.span);
1682             if item.ident.name == sym!(new);
1683             if let TraitItemKind::Fn(_, _) = item.kind;
1684             let ret_ty = return_ty(cx, item.hir_id);
1685             let self_ty = TraitRef::identity(cx.tcx, item.hir_id.owner.to_def_id()).self_ty();
1686             if !contains_ty(ret_ty, self_ty);
1687
1688             then {
1689                 span_lint(
1690                     cx,
1691                     NEW_RET_NO_SELF,
1692                     item.span,
1693                     "methods called `new` usually return `Self`",
1694                 );
1695             }
1696         }
1697     }
1698 }
1699
1700 /// Checks for the `OR_FUN_CALL` lint.
1701 #[allow(clippy::too_many_lines)]
1702 fn lint_or_fun_call<'tcx>(
1703     cx: &LateContext<'tcx>,
1704     expr: &hir::Expr<'_>,
1705     method_span: Span,
1706     name: &str,
1707     args: &'tcx [hir::Expr<'_>],
1708 ) {
1709     /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1710     fn check_unwrap_or_default(
1711         cx: &LateContext<'_>,
1712         name: &str,
1713         fun: &hir::Expr<'_>,
1714         self_expr: &hir::Expr<'_>,
1715         arg: &hir::Expr<'_>,
1716         or_has_args: bool,
1717         span: Span,
1718     ) -> bool {
1719         if_chain! {
1720             if !or_has_args;
1721             if name == "unwrap_or";
1722             if let hir::ExprKind::Path(ref qpath) = fun.kind;
1723             let path = &*last_path_segment(qpath).ident.as_str();
1724             if ["default", "new"].contains(&path);
1725             let arg_ty = cx.typeck_results().expr_ty(arg);
1726             if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1727             if implements_trait(cx, arg_ty, default_trait_id, &[]);
1728
1729             then {
1730                 let mut applicability = Applicability::MachineApplicable;
1731                 span_lint_and_sugg(
1732                     cx,
1733                     OR_FUN_CALL,
1734                     span,
1735                     &format!("use of `{}` followed by a call to `{}`", name, path),
1736                     "try this",
1737                     format!(
1738                         "{}.unwrap_or_default()",
1739                         snippet_with_applicability(cx, self_expr.span, "..", &mut applicability)
1740                     ),
1741                     applicability,
1742                 );
1743
1744                 true
1745             } else {
1746                 false
1747             }
1748         }
1749     }
1750
1751     /// Checks for `*or(foo())`.
1752     #[allow(clippy::too_many_arguments)]
1753     fn check_general_case<'tcx>(
1754         cx: &LateContext<'tcx>,
1755         name: &str,
1756         method_span: Span,
1757         fun_span: Span,
1758         self_expr: &hir::Expr<'_>,
1759         arg: &'tcx hir::Expr<'_>,
1760         or_has_args: bool,
1761         span: Span,
1762     ) {
1763         if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
1764             if path.ident.as_str() == "len" {
1765                 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
1766
1767                 match ty.kind() {
1768                     ty::Slice(_) | ty::Array(_, _) => return,
1769                     _ => (),
1770                 }
1771
1772                 if is_type_diagnostic_item(cx, ty, sym!(vec_type)) {
1773                     return;
1774                 }
1775             }
1776         }
1777
1778         // (path, fn_has_argument, methods, suffix)
1779         let know_types: &[(&[_], _, &[_], _)] = &[
1780             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1781             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1782             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1783             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1784         ];
1785
1786         if_chain! {
1787             if know_types.iter().any(|k| k.2.contains(&name));
1788
1789             if is_lazyness_candidate(cx, arg);
1790             if !contains_return(&arg);
1791
1792             let self_ty = cx.typeck_results().expr_ty(self_expr);
1793
1794             if let Some(&(_, fn_has_arguments, poss, suffix)) =
1795                 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1796
1797             if poss.contains(&name);
1798
1799             then {
1800                 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1801                     (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1802                     (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1803                     (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1804                 };
1805                 let span_replace_word = method_span.with_hi(span.hi());
1806                 span_lint_and_sugg(
1807                     cx,
1808                     OR_FUN_CALL,
1809                     span_replace_word,
1810                     &format!("use of `{}` followed by a function call", name),
1811                     "try this",
1812                     format!("{}_{}({})", name, suffix, sugg),
1813                     Applicability::HasPlaceholders,
1814                 );
1815             }
1816         }
1817     }
1818
1819     if args.len() == 2 {
1820         match args[1].kind {
1821             hir::ExprKind::Call(ref fun, ref or_args) => {
1822                 let or_has_args = !or_args.is_empty();
1823                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1824                     check_general_case(
1825                         cx,
1826                         name,
1827                         method_span,
1828                         fun.span,
1829                         &args[0],
1830                         &args[1],
1831                         or_has_args,
1832                         expr.span,
1833                     );
1834                 }
1835             },
1836             hir::ExprKind::MethodCall(_, span, ref or_args, _) => check_general_case(
1837                 cx,
1838                 name,
1839                 method_span,
1840                 span,
1841                 &args[0],
1842                 &args[1],
1843                 !or_args.is_empty(),
1844                 expr.span,
1845             ),
1846             _ => {},
1847         }
1848     }
1849 }
1850
1851 /// Checks for the `EXPECT_FUN_CALL` lint.
1852 #[allow(clippy::too_many_lines)]
1853 fn lint_expect_fun_call(
1854     cx: &LateContext<'_>,
1855     expr: &hir::Expr<'_>,
1856     method_span: Span,
1857     name: &str,
1858     args: &[hir::Expr<'_>],
1859 ) {
1860     // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1861     // `&str`
1862     fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1863         let mut arg_root = arg;
1864         loop {
1865             arg_root = match &arg_root.kind {
1866                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1867                 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
1868                     if call_args.len() == 1
1869                         && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1870                         && {
1871                             let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
1872                             let base_type = arg_type.peel_refs();
1873                             *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym!(string_type))
1874                         }
1875                     {
1876                         &call_args[0]
1877                     } else {
1878                         break;
1879                     }
1880                 },
1881                 _ => break,
1882             };
1883         }
1884         arg_root
1885     }
1886
1887     // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1888     // converted to string.
1889     fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
1890         let arg_ty = cx.typeck_results().expr_ty(arg);
1891         if is_type_diagnostic_item(cx, arg_ty, sym!(string_type)) {
1892             return false;
1893         }
1894         if let ty::Ref(_, ty, ..) = arg_ty.kind() {
1895             if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
1896                 return false;
1897             }
1898         };
1899         true
1900     }
1901
1902     // Check if an expression could have type `&'static str`, knowing that it
1903     // has type `&str` for some lifetime.
1904     fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
1905         match arg.kind {
1906             hir::ExprKind::Lit(_) => true,
1907             hir::ExprKind::Call(fun, _) => {
1908                 if let hir::ExprKind::Path(ref p) = fun.kind {
1909                     match cx.qpath_res(p, fun.hir_id) {
1910                         hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
1911                             cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
1912                             ty::Ref(ty::ReStatic, ..)
1913                         ),
1914                         _ => false,
1915                     }
1916                 } else {
1917                     false
1918                 }
1919             },
1920             hir::ExprKind::MethodCall(..) => {
1921                 cx.typeck_results()
1922                     .type_dependent_def_id(arg.hir_id)
1923                     .map_or(false, |method_id| {
1924                         matches!(
1925                             cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
1926                             ty::Ref(ty::ReStatic, ..)
1927                         )
1928                     })
1929             },
1930             hir::ExprKind::Path(ref p) => matches!(
1931                 cx.qpath_res(p, arg.hir_id),
1932                 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
1933             ),
1934             _ => false,
1935         }
1936     }
1937
1938     fn generate_format_arg_snippet(
1939         cx: &LateContext<'_>,
1940         a: &hir::Expr<'_>,
1941         applicability: &mut Applicability,
1942     ) -> Vec<String> {
1943         if_chain! {
1944             if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1945             if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1946             if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1947
1948             then {
1949                 format_arg_expr_tup
1950                     .iter()
1951                     .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1952                     .collect()
1953             } else {
1954                 unreachable!()
1955             }
1956         }
1957     }
1958
1959     fn is_call(node: &hir::ExprKind<'_>) -> bool {
1960         match node {
1961             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1962                 is_call(&expr.kind)
1963             },
1964             hir::ExprKind::Call(..)
1965             | hir::ExprKind::MethodCall(..)
1966             // These variants are debatable or require further examination
1967             | hir::ExprKind::Match(..)
1968             | hir::ExprKind::Block{ .. } => true,
1969             _ => false,
1970         }
1971     }
1972
1973     if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1974         return;
1975     }
1976
1977     let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
1978     let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym!(option_type)) {
1979         "||"
1980     } else if is_type_diagnostic_item(cx, receiver_type, sym!(result_type)) {
1981         "|_|"
1982     } else {
1983         return;
1984     };
1985
1986     let arg_root = get_arg_root(cx, &args[1]);
1987
1988     let span_replace_word = method_span.with_hi(expr.span.hi());
1989
1990     let mut applicability = Applicability::MachineApplicable;
1991
1992     //Special handling for `format!` as arg_root
1993     if_chain! {
1994         if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1995         if block.stmts.len() == 1;
1996         if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1997         if let Some(arg_root) = &local.init;
1998         if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1999         if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
2000         if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
2001         then {
2002             let fmt_spec = &format_args[0];
2003             let fmt_args = &format_args[1];
2004
2005             let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
2006
2007             args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
2008
2009             let sugg = args.join(", ");
2010
2011             span_lint_and_sugg(
2012                 cx,
2013                 EXPECT_FUN_CALL,
2014                 span_replace_word,
2015                 &format!("use of `{}` followed by a function call", name),
2016                 "try this",
2017                 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
2018                 applicability,
2019             );
2020
2021             return;
2022         }
2023     }
2024
2025     let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
2026     if requires_to_string(cx, arg_root) {
2027         arg_root_snippet.to_mut().push_str(".to_string()");
2028     }
2029
2030     span_lint_and_sugg(
2031         cx,
2032         EXPECT_FUN_CALL,
2033         span_replace_word,
2034         &format!("use of `{}` followed by a function call", name),
2035         "try this",
2036         format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
2037         applicability,
2038     );
2039 }
2040
2041 /// Checks for the `CLONE_ON_COPY` lint.
2042 fn lint_clone_on_copy(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
2043     let ty = cx.typeck_results().expr_ty(expr);
2044     if let ty::Ref(_, inner, _) = arg_ty.kind() {
2045         if let ty::Ref(_, innermost, _) = inner.kind() {
2046             span_lint_and_then(
2047                 cx,
2048                 CLONE_DOUBLE_REF,
2049                 expr.span,
2050                 "using `clone` on a double-reference; \
2051                 this will copy the reference instead of cloning the inner type",
2052                 |diag| {
2053                     if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
2054                         let mut ty = innermost;
2055                         let mut n = 0;
2056                         while let ty::Ref(_, inner, _) = ty.kind() {
2057                             ty = inner;
2058                             n += 1;
2059                         }
2060                         let refs: String = iter::repeat('&').take(n + 1).collect();
2061                         let derefs: String = iter::repeat('*').take(n).collect();
2062                         let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
2063                         diag.span_suggestion(
2064                             expr.span,
2065                             "try dereferencing it",
2066                             format!("{}({}{}).clone()", refs, derefs, snip.deref()),
2067                             Applicability::MaybeIncorrect,
2068                         );
2069                         diag.span_suggestion(
2070                             expr.span,
2071                             "or try being explicit if you are sure, that you want to clone a reference",
2072                             explicit,
2073                             Applicability::MaybeIncorrect,
2074                         );
2075                     }
2076                 },
2077             );
2078             return; // don't report clone_on_copy
2079         }
2080     }
2081
2082     if is_copy(cx, ty) {
2083         let snip;
2084         if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
2085             let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
2086             match &cx.tcx.hir().get(parent) {
2087                 hir::Node::Expr(parent) => match parent.kind {
2088                     // &*x is a nop, &x.clone() is not
2089                     hir::ExprKind::AddrOf(..) => return,
2090                     // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
2091                     hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
2092                         return;
2093                     },
2094
2095                     _ => {},
2096                 },
2097                 hir::Node::Stmt(stmt) => {
2098                     if let hir::StmtKind::Local(ref loc) = stmt.kind {
2099                         if let hir::PatKind::Ref(..) = loc.pat.kind {
2100                             // let ref y = *x borrows x, let ref y = x.clone() does not
2101                             return;
2102                         }
2103                     }
2104                 },
2105                 _ => {},
2106             }
2107
2108             // x.clone() might have dereferenced x, possibly through Deref impls
2109             if cx.typeck_results().expr_ty(arg) == ty {
2110                 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
2111             } else {
2112                 let deref_count = cx
2113                     .typeck_results()
2114                     .expr_adjustments(arg)
2115                     .iter()
2116                     .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
2117                     .count();
2118                 let derefs: String = iter::repeat('*').take(deref_count).collect();
2119                 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
2120             }
2121         } else {
2122             snip = None;
2123         }
2124         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |diag| {
2125             if let Some((text, snip)) = snip {
2126                 diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);
2127             }
2128         });
2129     }
2130 }
2131
2132 fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
2133     let obj_ty = cx.typeck_results().expr_ty(arg).peel_refs();
2134
2135     if let ty::Adt(_, subst) = obj_ty.kind() {
2136         let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
2137             "Rc"
2138         } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
2139             "Arc"
2140         } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
2141             "Weak"
2142         } else {
2143             return;
2144         };
2145
2146         let snippet = snippet_with_macro_callsite(cx, arg.span, "..");
2147
2148         span_lint_and_sugg(
2149             cx,
2150             CLONE_ON_REF_PTR,
2151             expr.span,
2152             "using `.clone()` on a ref-counted pointer",
2153             "try this",
2154             format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
2155             Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2156         );
2157     }
2158 }
2159
2160 fn lint_string_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2161     let arg = &args[1];
2162     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2163         let target = &arglists[0][0];
2164         let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
2165         let ref_str = if *self_ty.kind() == ty::Str {
2166             ""
2167         } else if is_type_diagnostic_item(cx, self_ty, sym!(string_type)) {
2168             "&"
2169         } else {
2170             return;
2171         };
2172
2173         let mut applicability = Applicability::MachineApplicable;
2174         span_lint_and_sugg(
2175             cx,
2176             STRING_EXTEND_CHARS,
2177             expr.span,
2178             "calling `.extend(_.chars())`",
2179             "try this",
2180             format!(
2181                 "{}.push_str({}{})",
2182                 snippet_with_applicability(cx, args[0].span, "..", &mut applicability),
2183                 ref_str,
2184                 snippet_with_applicability(cx, target.span, "..", &mut applicability)
2185             ),
2186             applicability,
2187         );
2188     }
2189 }
2190
2191 fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2192     let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
2193     if is_type_diagnostic_item(cx, obj_ty, sym!(string_type)) {
2194         lint_string_extend(cx, expr, args);
2195     }
2196 }
2197
2198 fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2199     if_chain! {
2200         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym!(vec_type));
2201         if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0]));
2202         if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2203
2204         then {
2205             span_lint_and_sugg(
2206                 cx,
2207                 ITER_CLONED_COLLECT,
2208                 to_replace,
2209                 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2210                 more readable",
2211                 "try",
2212                 ".to_vec()".to_string(),
2213                 Applicability::MachineApplicable,
2214             );
2215         }
2216     }
2217 }
2218
2219 fn lint_unnecessary_fold(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2220     fn check_fold_with_op(
2221         cx: &LateContext<'_>,
2222         expr: &hir::Expr<'_>,
2223         fold_args: &[hir::Expr<'_>],
2224         fold_span: Span,
2225         op: hir::BinOpKind,
2226         replacement_method_name: &str,
2227         replacement_has_args: bool,
2228     ) {
2229         if_chain! {
2230             // Extract the body of the closure passed to fold
2231             if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2232             let closure_body = cx.tcx.hir().body(body_id);
2233             let closure_expr = remove_blocks(&closure_body.value);
2234
2235             // Check if the closure body is of the form `acc <op> some_expr(x)`
2236             if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2237             if bin_op.node == op;
2238
2239             // Extract the names of the two arguments to the closure
2240             if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2241             if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2242
2243             if match_var(&*left_expr, first_arg_ident);
2244             if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2245
2246             then {
2247                 let mut applicability = Applicability::MachineApplicable;
2248                 let sugg = if replacement_has_args {
2249                     format!(
2250                         "{replacement}(|{s}| {r})",
2251                         replacement = replacement_method_name,
2252                         s = second_arg_ident,
2253                         r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2254                     )
2255                 } else {
2256                     format!(
2257                         "{replacement}()",
2258                         replacement = replacement_method_name,
2259                     )
2260                 };
2261
2262                 span_lint_and_sugg(
2263                     cx,
2264                     UNNECESSARY_FOLD,
2265                     fold_span.with_hi(expr.span.hi()),
2266                     // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2267                     "this `.fold` can be written more succinctly using another method",
2268                     "try",
2269                     sugg,
2270                     applicability,
2271                 );
2272             }
2273         }
2274     }
2275
2276     // Check that this is a call to Iterator::fold rather than just some function called fold
2277     if !match_trait_method(cx, expr, &paths::ITERATOR) {
2278         return;
2279     }
2280
2281     assert!(
2282         fold_args.len() == 3,
2283         "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2284     );
2285
2286     // Check if the first argument to .fold is a suitable literal
2287     if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2288         match lit.node {
2289             ast::LitKind::Bool(false) => {
2290                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2291             },
2292             ast::LitKind::Bool(true) => {
2293                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2294             },
2295             ast::LitKind::Int(0, _) => {
2296                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2297             },
2298             ast::LitKind::Int(1, _) => {
2299                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2300             },
2301             _ => (),
2302         }
2303     }
2304 }
2305
2306 fn lint_step_by<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2307     if match_trait_method(cx, expr, &paths::ITERATOR) {
2308         if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) {
2309             span_lint(
2310                 cx,
2311                 ITERATOR_STEP_BY_ZERO,
2312                 expr.span,
2313                 "Iterator::step_by(0) will panic at runtime",
2314             );
2315         }
2316     }
2317 }
2318
2319 fn lint_iter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2320     let caller_expr = &iter_args[0];
2321
2322     // Skip lint if the `iter().next()` expression is a for loop argument,
2323     // since it is already covered by `&loops::ITER_NEXT_LOOP`
2324     let mut parent_expr_opt = get_parent_expr(cx, expr);
2325     while let Some(parent_expr) = parent_expr_opt {
2326         if higher::for_loop(parent_expr).is_some() {
2327             return;
2328         }
2329         parent_expr_opt = get_parent_expr(cx, parent_expr);
2330     }
2331
2332     if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() {
2333         // caller is a Slice
2334         if_chain! {
2335             if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind;
2336             if let Some(higher::Range { start: Some(start_expr), end: None, limits: ast::RangeLimits::HalfOpen })
2337                 = higher::range(index_expr);
2338             if let hir::ExprKind::Lit(ref start_lit) = &start_expr.kind;
2339             if let ast::LitKind::Int(start_idx, _) = start_lit.node;
2340             then {
2341                 let mut applicability = Applicability::MachineApplicable;
2342                 span_lint_and_sugg(
2343                     cx,
2344                     ITER_NEXT_SLICE,
2345                     expr.span,
2346                     "using `.iter().next()` on a Slice without end index",
2347                     "try calling",
2348                     format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx),
2349                     applicability,
2350                 );
2351             }
2352         }
2353     } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym!(vec_type))
2354         || matches!(
2355             &cx.typeck_results().expr_ty(caller_expr).peel_refs().kind(),
2356             ty::Array(_, _)
2357         )
2358     {
2359         // caller is a Vec or an Array
2360         let mut applicability = Applicability::MachineApplicable;
2361         span_lint_and_sugg(
2362             cx,
2363             ITER_NEXT_SLICE,
2364             expr.span,
2365             "using `.iter().next()` on an array",
2366             "try calling",
2367             format!(
2368                 "{}.get(0)",
2369                 snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability)
2370             ),
2371             applicability,
2372         );
2373     }
2374 }
2375
2376 fn lint_iter_nth<'tcx>(
2377     cx: &LateContext<'tcx>,
2378     expr: &hir::Expr<'_>,
2379     nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2380     is_mut: bool,
2381 ) {
2382     let iter_args = nth_and_iter_args[1];
2383     let mut_str = if is_mut { "_mut" } else { "" };
2384     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() {
2385         "slice"
2386     } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vec_type)) {
2387         "Vec"
2388     } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
2389         "VecDeque"
2390     } else {
2391         let nth_args = nth_and_iter_args[0];
2392         lint_iter_nth_zero(cx, expr, &nth_args);
2393         return; // caller is not a type that we want to lint
2394     };
2395
2396     span_lint_and_help(
2397         cx,
2398         ITER_NTH,
2399         expr.span,
2400         &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2401         None,
2402         &format!("calling `.get{}()` is both faster and more readable", mut_str),
2403     );
2404 }
2405
2406 fn lint_iter_nth_zero<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2407     if_chain! {
2408         if match_trait_method(cx, expr, &paths::ITERATOR);
2409         if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]);
2410         then {
2411             let mut applicability = Applicability::MachineApplicable;
2412             span_lint_and_sugg(
2413                 cx,
2414                 ITER_NTH_ZERO,
2415                 expr.span,
2416                 "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent",
2417                 "try calling `.next()` instead of `.nth(0)`",
2418                 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2419                 applicability,
2420             );
2421         }
2422     }
2423 }
2424
2425 fn lint_get_unwrap<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args: &'tcx [hir::Expr<'_>], is_mut: bool) {
2426     // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2427     // because they do not implement `IndexMut`
2428     let mut applicability = Applicability::MachineApplicable;
2429     let expr_ty = cx.typeck_results().expr_ty(&get_args[0]);
2430     let get_args_str = if get_args.len() > 1 {
2431         snippet_with_applicability(cx, get_args[1].span, "..", &mut applicability)
2432     } else {
2433         return; // not linting on a .get().unwrap() chain or variant
2434     };
2435     let mut needs_ref;
2436     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2437         needs_ref = get_args_str.parse::<usize>().is_ok();
2438         "slice"
2439     } else if is_type_diagnostic_item(cx, expr_ty, sym!(vec_type)) {
2440         needs_ref = get_args_str.parse::<usize>().is_ok();
2441         "Vec"
2442     } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
2443         needs_ref = get_args_str.parse::<usize>().is_ok();
2444         "VecDeque"
2445     } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
2446         needs_ref = true;
2447         "HashMap"
2448     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2449         needs_ref = true;
2450         "BTreeMap"
2451     } else {
2452         return; // caller is not a type that we want to lint
2453     };
2454
2455     let mut span = expr.span;
2456
2457     // Handle the case where the result is immediately dereferenced
2458     // by not requiring ref and pulling the dereference into the
2459     // suggestion.
2460     if_chain! {
2461         if needs_ref;
2462         if let Some(parent) = get_parent_expr(cx, expr);
2463         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2464         then {
2465             needs_ref = false;
2466             span = parent.span;
2467         }
2468     }
2469
2470     let mut_str = if is_mut { "_mut" } else { "" };
2471     let borrow_str = if !needs_ref {
2472         ""
2473     } else if is_mut {
2474         "&mut "
2475     } else {
2476         "&"
2477     };
2478
2479     span_lint_and_sugg(
2480         cx,
2481         GET_UNWRAP,
2482         span,
2483         &format!(
2484             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2485             mut_str, caller_type
2486         ),
2487         "try this",
2488         format!(
2489             "{}{}[{}]",
2490             borrow_str,
2491             snippet_with_applicability(cx, get_args[0].span, "..", &mut applicability),
2492             get_args_str
2493         ),
2494         applicability,
2495     );
2496 }
2497
2498 fn lint_iter_skip_next(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir::Expr<'_>]) {
2499     // lint if caller of skip is an Iterator
2500     if match_trait_method(cx, expr, &paths::ITERATOR) {
2501         if let [caller, n] = skip_args {
2502             let hint = format!(".nth({})", snippet(cx, n.span, ".."));
2503             span_lint_and_sugg(
2504                 cx,
2505                 ITER_SKIP_NEXT,
2506                 expr.span.trim_start(caller.span).unwrap(),
2507                 "called `skip(..).next()` on an iterator",
2508                 "use `nth` instead",
2509                 hint,
2510                 Applicability::MachineApplicable,
2511             );
2512         }
2513     }
2514 }
2515
2516 fn derefs_to_slice<'tcx>(
2517     cx: &LateContext<'tcx>,
2518     expr: &'tcx hir::Expr<'tcx>,
2519     ty: Ty<'tcx>,
2520 ) -> Option<&'tcx hir::Expr<'tcx>> {
2521     fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
2522         match ty.kind() {
2523             ty::Slice(_) => true,
2524             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2525             ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym!(vec_type)),
2526             ty::Array(_, size) => size
2527                 .try_eval_usize(cx.tcx, cx.param_env)
2528                 .map_or(false, |size| size < 32),
2529             ty::Ref(_, inner, _) => may_slice(cx, inner),
2530             _ => false,
2531         }
2532     }
2533
2534     if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
2535         if path.ident.name == sym!(iter) && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2536             Some(&args[0])
2537         } else {
2538             None
2539         }
2540     } else {
2541         match ty.kind() {
2542             ty::Slice(_) => Some(expr),
2543             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2544             ty::Ref(_, inner, _) => {
2545                 if may_slice(cx, inner) {
2546                     Some(expr)
2547                 } else {
2548                     None
2549                 }
2550             },
2551             _ => None,
2552         }
2553     }
2554 }
2555
2556 /// lint use of `unwrap()` for `Option`s and `Result`s
2557 fn lint_unwrap(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2558     let obj_ty = cx.typeck_results().expr_ty(&unwrap_args[0]).peel_refs();
2559
2560     let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2561         Some((UNWRAP_USED, "an Option", "None"))
2562     } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2563         Some((UNWRAP_USED, "a Result", "Err"))
2564     } else {
2565         None
2566     };
2567
2568     if let Some((lint, kind, none_value)) = mess {
2569         span_lint_and_help(
2570             cx,
2571             lint,
2572             expr.span,
2573             &format!("used `unwrap()` on `{}` value", kind,),
2574             None,
2575             &format!(
2576                 "if you don't want to handle the `{}` case gracefully, consider \
2577                 using `expect()` to provide a better panic message",
2578                 none_value,
2579             ),
2580         );
2581     }
2582 }
2583
2584 /// lint use of `expect()` for `Option`s and `Result`s
2585 fn lint_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2586     let obj_ty = cx.typeck_results().expr_ty(&expect_args[0]).peel_refs();
2587
2588     let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2589         Some((EXPECT_USED, "an Option", "None"))
2590     } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2591         Some((EXPECT_USED, "a Result", "Err"))
2592     } else {
2593         None
2594     };
2595
2596     if let Some((lint, kind, none_value)) = mess {
2597         span_lint_and_help(
2598             cx,
2599             lint,
2600             expr.span,
2601             &format!("used `expect()` on `{}` value", kind,),
2602             None,
2603             &format!("if this value is an `{}`, it will panic", none_value,),
2604         );
2605     }
2606 }
2607
2608 /// lint use of `ok().expect()` for `Result`s
2609 fn lint_ok_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2610     if_chain! {
2611         // lint if the caller of `ok()` is a `Result`
2612         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym!(result_type));
2613         let result_type = cx.typeck_results().expr_ty(&ok_args[0]);
2614         if let Some(error_type) = get_error_type(cx, result_type);
2615         if has_debug_impl(error_type, cx);
2616
2617         then {
2618             span_lint_and_help(
2619                 cx,
2620                 OK_EXPECT,
2621                 expr.span,
2622                 "called `ok().expect()` on a `Result` value",
2623                 None,
2624                 "you can call `expect()` directly on the `Result`",
2625             );
2626         }
2627     }
2628 }
2629
2630 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2631 fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2632     // lint if caller of `.map().flatten()` is an Iterator
2633     if match_trait_method(cx, expr, &paths::ITERATOR) {
2634         let map_closure_ty = cx.typeck_results().expr_ty(&map_args[1]);
2635         let is_map_to_option = match map_closure_ty.kind() {
2636             ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
2637                 let map_closure_sig = match map_closure_ty.kind() {
2638                     ty::Closure(_, substs) => substs.as_closure().sig(),
2639                     _ => map_closure_ty.fn_sig(cx.tcx),
2640                 };
2641                 let map_closure_return_ty = cx.tcx.erase_late_bound_regions(&map_closure_sig.output());
2642                 is_type_diagnostic_item(cx, map_closure_return_ty, sym!(option_type))
2643             },
2644             _ => false,
2645         };
2646
2647         let method_to_use = if is_map_to_option {
2648             // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
2649             "filter_map"
2650         } else {
2651             // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
2652             "flat_map"
2653         };
2654         let func_snippet = snippet(cx, map_args[1].span, "..");
2655         let hint = format!(".{0}({1})", method_to_use, func_snippet);
2656         span_lint_and_sugg(
2657             cx,
2658             MAP_FLATTEN,
2659             expr.span.with_lo(map_args[0].span.hi()),
2660             "called `map(..).flatten()` on an `Iterator`",
2661             &format!("try using `{}` instead", method_to_use),
2662             hint,
2663             Applicability::MachineApplicable,
2664         );
2665     }
2666
2667     // lint if caller of `.map().flatten()` is an Option
2668     if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type)) {
2669         let func_snippet = snippet(cx, map_args[1].span, "..");
2670         let hint = format!(".and_then({})", func_snippet);
2671         span_lint_and_sugg(
2672             cx,
2673             MAP_FLATTEN,
2674             expr.span.with_lo(map_args[0].span.hi()),
2675             "called `map(..).flatten()` on an `Option`",
2676             "try using `and_then` instead",
2677             hint,
2678             Applicability::MachineApplicable,
2679         );
2680     }
2681 }
2682
2683 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2684 /// Return true if lint triggered
2685 fn lint_map_unwrap_or_else<'tcx>(
2686     cx: &LateContext<'tcx>,
2687     expr: &'tcx hir::Expr<'_>,
2688     map_args: &'tcx [hir::Expr<'_>],
2689     unwrap_args: &'tcx [hir::Expr<'_>],
2690 ) -> bool {
2691     // lint if the caller of `map()` is an `Option`
2692     let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type));
2693     let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(result_type));
2694
2695     if is_option || is_result {
2696         // Don't make a suggestion that may fail to compile due to mutably borrowing
2697         // the same variable twice.
2698         let map_mutated_vars = mutated_variables(&map_args[0], cx);
2699         let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2700         if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2701             if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2702                 return false;
2703             }
2704         } else {
2705             return false;
2706         }
2707
2708         // lint message
2709         let msg = if is_option {
2710             "called `map(<f>).unwrap_or_else(<g>)` on an `Option` value. This can be done more directly by calling \
2711             `map_or_else(<g>, <f>)` instead"
2712         } else {
2713             "called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling \
2714             `.map_or_else(<g>, <f>)` instead"
2715         };
2716         // get snippets for args to map() and unwrap_or_else()
2717         let map_snippet = snippet(cx, map_args[1].span, "..");
2718         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2719         // lint, with note if neither arg is > 1 line and both map() and
2720         // unwrap_or_else() have the same span
2721         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2722         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2723         if same_span && !multiline {
2724             let var_snippet = snippet(cx, map_args[0].span, "..");
2725             span_lint_and_sugg(
2726                 cx,
2727                 MAP_UNWRAP_OR,
2728                 expr.span,
2729                 msg,
2730                 "try this",
2731                 format!("{}.map_or_else({}, {})", var_snippet, unwrap_snippet, map_snippet),
2732                 Applicability::MachineApplicable,
2733             );
2734             return true;
2735         } else if same_span && multiline {
2736             span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2737             return true;
2738         }
2739     }
2740
2741     false
2742 }
2743
2744 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
2745 fn lint_map_or_none<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>]) {
2746     let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(option_type));
2747     let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(result_type));
2748
2749     // There are two variants of this `map_or` lint:
2750     // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
2751     // (2) using `map_or` as a combinator instead of `and_then`
2752     //
2753     // (For this lint) we don't care if any other type calls `map_or`
2754     if !is_option && !is_result {
2755         return;
2756     }
2757
2758     let (lint_name, msg, instead, hint) = {
2759         let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2760             match_qpath(qpath, &paths::OPTION_NONE)
2761         } else {
2762             return;
2763         };
2764
2765         if !default_arg_is_none {
2766             // nothing to lint!
2767             return;
2768         }
2769
2770         let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
2771             match_qpath(qpath, &paths::OPTION_SOME)
2772         } else {
2773             false
2774         };
2775
2776         if is_option {
2777             let self_snippet = snippet(cx, map_or_args[0].span, "..");
2778             let func_snippet = snippet(cx, map_or_args[2].span, "..");
2779             let msg = "called `map_or(None, ..)` on an `Option` value. This can be done more directly by calling \
2780                        `and_then(..)` instead";
2781             (
2782                 OPTION_MAP_OR_NONE,
2783                 msg,
2784                 "try using `and_then` instead",
2785                 format!("{0}.and_then({1})", self_snippet, func_snippet),
2786             )
2787         } else if f_arg_is_some {
2788             let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
2789                        `ok()` instead";
2790             let self_snippet = snippet(cx, map_or_args[0].span, "..");
2791             (
2792                 RESULT_MAP_OR_INTO_OPTION,
2793                 msg,
2794                 "try using `ok` instead",
2795                 format!("{0}.ok()", self_snippet),
2796             )
2797         } else {
2798             // nothing to lint!
2799             return;
2800         }
2801     };
2802
2803     span_lint_and_sugg(
2804         cx,
2805         lint_name,
2806         expr.span,
2807         msg,
2808         instead,
2809         hint,
2810         Applicability::MachineApplicable,
2811     );
2812 }
2813
2814 /// lint use of `filter().next()` for `Iterators`
2815 fn lint_filter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
2816     // lint if caller of `.filter().next()` is an Iterator
2817     if match_trait_method(cx, expr, &paths::ITERATOR) {
2818         let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
2819                    `.find(..)` instead.";
2820         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2821         if filter_snippet.lines().count() <= 1 {
2822             let iter_snippet = snippet(cx, filter_args[0].span, "..");
2823             // add note if not multi-line
2824             span_lint_and_sugg(
2825                 cx,
2826                 FILTER_NEXT,
2827                 expr.span,
2828                 msg,
2829                 "try this",
2830                 format!("{}.find({})", iter_snippet, filter_snippet),
2831                 Applicability::MachineApplicable,
2832             );
2833         } else {
2834             span_lint(cx, FILTER_NEXT, expr.span, msg);
2835         }
2836     }
2837 }
2838
2839 /// lint use of `skip_while().next()` for `Iterators`
2840 fn lint_skip_while_next<'tcx>(
2841     cx: &LateContext<'tcx>,
2842     expr: &'tcx hir::Expr<'_>,
2843     _skip_while_args: &'tcx [hir::Expr<'_>],
2844 ) {
2845     // lint if caller of `.skip_while().next()` is an Iterator
2846     if match_trait_method(cx, expr, &paths::ITERATOR) {
2847         span_lint_and_help(
2848             cx,
2849             SKIP_WHILE_NEXT,
2850             expr.span,
2851             "called `skip_while(<p>).next()` on an `Iterator`",
2852             None,
2853             "this is more succinctly expressed by calling `.find(!<p>)` instead",
2854         );
2855     }
2856 }
2857
2858 /// lint use of `filter().map()` for `Iterators`
2859 fn lint_filter_map<'tcx>(
2860     cx: &LateContext<'tcx>,
2861     expr: &'tcx hir::Expr<'_>,
2862     _filter_args: &'tcx [hir::Expr<'_>],
2863     _map_args: &'tcx [hir::Expr<'_>],
2864 ) {
2865     // lint if caller of `.filter().map()` is an Iterator
2866     if match_trait_method(cx, expr, &paths::ITERATOR) {
2867         let msg = "called `filter(..).map(..)` on an `Iterator`";
2868         let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2869         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2870     }
2871 }
2872
2873 /// lint use of `filter_map().next()` for `Iterators`
2874 fn lint_filter_map_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
2875     if match_trait_method(cx, expr, &paths::ITERATOR) {
2876         let msg = "called `filter_map(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
2877                    `.find_map(..)` instead.";
2878         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2879         if filter_snippet.lines().count() <= 1 {
2880             let iter_snippet = snippet(cx, filter_args[0].span, "..");
2881             span_lint_and_sugg(
2882                 cx,
2883                 FILTER_MAP_NEXT,
2884                 expr.span,
2885                 msg,
2886                 "try this",
2887                 format!("{}.find_map({})", iter_snippet, filter_snippet),
2888                 Applicability::MachineApplicable,
2889             );
2890         } else {
2891             span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2892         }
2893     }
2894 }
2895
2896 /// lint use of `find().map()` for `Iterators`
2897 fn lint_find_map<'tcx>(
2898     cx: &LateContext<'tcx>,
2899     expr: &'tcx hir::Expr<'_>,
2900     _find_args: &'tcx [hir::Expr<'_>],
2901     map_args: &'tcx [hir::Expr<'_>],
2902 ) {
2903     // lint if caller of `.filter().map()` is an Iterator
2904     if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2905         let msg = "called `find(..).map(..)` on an `Iterator`";
2906         let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2907         span_lint_and_help(cx, FIND_MAP, expr.span, msg, None, hint);
2908     }
2909 }
2910
2911 /// lint use of `filter_map().map()` for `Iterators`
2912 fn lint_filter_map_map<'tcx>(
2913     cx: &LateContext<'tcx>,
2914     expr: &'tcx hir::Expr<'_>,
2915     _filter_args: &'tcx [hir::Expr<'_>],
2916     _map_args: &'tcx [hir::Expr<'_>],
2917 ) {
2918     // lint if caller of `.filter().map()` is an Iterator
2919     if match_trait_method(cx, expr, &paths::ITERATOR) {
2920         let msg = "called `filter_map(..).map(..)` on an `Iterator`";
2921         let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2922         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2923     }
2924 }
2925
2926 /// lint use of `filter().flat_map()` for `Iterators`
2927 fn lint_filter_flat_map<'tcx>(
2928     cx: &LateContext<'tcx>,
2929     expr: &'tcx hir::Expr<'_>,
2930     _filter_args: &'tcx [hir::Expr<'_>],
2931     _map_args: &'tcx [hir::Expr<'_>],
2932 ) {
2933     // lint if caller of `.filter().flat_map()` is an Iterator
2934     if match_trait_method(cx, expr, &paths::ITERATOR) {
2935         let msg = "called `filter(..).flat_map(..)` on an `Iterator`";
2936         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2937                     and filtering by returning `iter::empty()`";
2938         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2939     }
2940 }
2941
2942 /// lint use of `filter_map().flat_map()` for `Iterators`
2943 fn lint_filter_map_flat_map<'tcx>(
2944     cx: &LateContext<'tcx>,
2945     expr: &'tcx hir::Expr<'_>,
2946     _filter_args: &'tcx [hir::Expr<'_>],
2947     _map_args: &'tcx [hir::Expr<'_>],
2948 ) {
2949     // lint if caller of `.filter_map().flat_map()` is an Iterator
2950     if match_trait_method(cx, expr, &paths::ITERATOR) {
2951         let msg = "called `filter_map(..).flat_map(..)` on an `Iterator`";
2952         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2953                     and filtering by returning `iter::empty()`";
2954         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2955     }
2956 }
2957
2958 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2959 fn lint_flat_map_identity<'tcx>(
2960     cx: &LateContext<'tcx>,
2961     expr: &'tcx hir::Expr<'_>,
2962     flat_map_args: &'tcx [hir::Expr<'_>],
2963     flat_map_span: Span,
2964 ) {
2965     if match_trait_method(cx, expr, &paths::ITERATOR) {
2966         let arg_node = &flat_map_args[1].kind;
2967
2968         let apply_lint = |message: &str| {
2969             span_lint_and_sugg(
2970                 cx,
2971                 FLAT_MAP_IDENTITY,
2972                 flat_map_span.with_hi(expr.span.hi()),
2973                 message,
2974                 "try",
2975                 "flatten()".to_string(),
2976                 Applicability::MachineApplicable,
2977             );
2978         };
2979
2980         if_chain! {
2981             if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2982             let body = cx.tcx.hir().body(*body_id);
2983
2984             if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2985             if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2986
2987             if path.segments.len() == 1;
2988             if path.segments[0].ident.as_str() == binding_ident.as_str();
2989
2990             then {
2991                 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2992             }
2993         }
2994
2995         if_chain! {
2996             if let hir::ExprKind::Path(ref qpath) = arg_node;
2997
2998             if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2999
3000             then {
3001                 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
3002             }
3003         }
3004     }
3005 }
3006
3007 /// lint searching an Iterator followed by `is_some()`
3008 fn lint_search_is_some<'tcx>(
3009     cx: &LateContext<'tcx>,
3010     expr: &'tcx hir::Expr<'_>,
3011     search_method: &str,
3012     search_args: &'tcx [hir::Expr<'_>],
3013     is_some_args: &'tcx [hir::Expr<'_>],
3014     method_span: Span,
3015 ) {
3016     // lint if caller of search is an Iterator
3017     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
3018         let msg = format!(
3019             "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
3020              expressed by calling `any()`.",
3021             search_method
3022         );
3023         let search_snippet = snippet(cx, search_args[1].span, "..");
3024         if search_snippet.lines().count() <= 1 {
3025             // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
3026             // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
3027             let any_search_snippet = if_chain! {
3028                 if search_method == "find";
3029                 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
3030                 let closure_body = cx.tcx.hir().body(body_id);
3031                 if let Some(closure_arg) = closure_body.params.get(0);
3032                 then {
3033                     if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
3034                         Some(search_snippet.replacen('&', "", 1))
3035                     } else if let Some(name) = get_arg_name(&closure_arg.pat) {
3036                         Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
3037                     } else {
3038                         None
3039                     }
3040                 } else {
3041                     None
3042                 }
3043             };
3044             // add note if not multi-line
3045             span_lint_and_sugg(
3046                 cx,
3047                 SEARCH_IS_SOME,
3048                 method_span.with_hi(expr.span.hi()),
3049                 &msg,
3050                 "try this",
3051                 format!(
3052                     "any({})",
3053                     any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
3054                 ),
3055                 Applicability::MachineApplicable,
3056             );
3057         } else {
3058             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
3059         }
3060     }
3061 }
3062
3063 /// Used for `lint_binary_expr_with_method_call`.
3064 #[derive(Copy, Clone)]
3065 struct BinaryExprInfo<'a> {
3066     expr: &'a hir::Expr<'a>,
3067     chain: &'a hir::Expr<'a>,
3068     other: &'a hir::Expr<'a>,
3069     eq: bool,
3070 }
3071
3072 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3073 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3074     macro_rules! lint_with_both_lhs_and_rhs {
3075         ($func:ident, $cx:expr, $info:ident) => {
3076             if !$func($cx, $info) {
3077                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3078                 if $func($cx, $info) {
3079                     return;
3080                 }
3081             }
3082         };
3083     }
3084
3085     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
3086     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
3087     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
3088     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
3089 }
3090
3091 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3092 fn lint_chars_cmp(
3093     cx: &LateContext<'_>,
3094     info: &BinaryExprInfo<'_>,
3095     chain_methods: &[&str],
3096     lint: &'static Lint,
3097     suggest: &str,
3098 ) -> bool {
3099     if_chain! {
3100         if let Some(args) = method_chain_args(info.chain, chain_methods);
3101         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
3102         if arg_char.len() == 1;
3103         if let hir::ExprKind::Path(ref qpath) = fun.kind;
3104         if let Some(segment) = single_segment_path(qpath);
3105         if segment.ident.name == sym!(Some);
3106         then {
3107             let mut applicability = Applicability::MachineApplicable;
3108             let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
3109
3110             if *self_ty.kind() != ty::Str {
3111                 return false;
3112             }
3113
3114             span_lint_and_sugg(
3115                 cx,
3116                 lint,
3117                 info.expr.span,
3118                 &format!("you should use the `{}` method", suggest),
3119                 "like this",
3120                 format!("{}{}.{}({})",
3121                         if info.eq { "" } else { "!" },
3122                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3123                         suggest,
3124                         snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
3125                 applicability,
3126             );
3127
3128             return true;
3129         }
3130     }
3131
3132     false
3133 }
3134
3135 /// Checks for the `CHARS_NEXT_CMP` lint.
3136 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3137     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
3138 }
3139
3140 /// Checks for the `CHARS_LAST_CMP` lint.
3141 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3142     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
3143         true
3144     } else {
3145         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
3146     }
3147 }
3148
3149 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
3150 fn lint_chars_cmp_with_unwrap<'tcx>(
3151     cx: &LateContext<'tcx>,
3152     info: &BinaryExprInfo<'_>,
3153     chain_methods: &[&str],
3154     lint: &'static Lint,
3155     suggest: &str,
3156 ) -> bool {
3157     if_chain! {
3158         if let Some(args) = method_chain_args(info.chain, chain_methods);
3159         if let hir::ExprKind::Lit(ref lit) = info.other.kind;
3160         if let ast::LitKind::Char(c) = lit.node;
3161         then {
3162             let mut applicability = Applicability::MachineApplicable;
3163             span_lint_and_sugg(
3164                 cx,
3165                 lint,
3166                 info.expr.span,
3167                 &format!("you should use the `{}` method", suggest),
3168                 "like this",
3169                 format!("{}{}.{}('{}')",
3170                         if info.eq { "" } else { "!" },
3171                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3172                         suggest,
3173                         c),
3174                 applicability,
3175             );
3176
3177             true
3178         } else {
3179             false
3180         }
3181     }
3182 }
3183
3184 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3185 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3186     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3187 }
3188
3189 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3190 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3191     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3192         true
3193     } else {
3194         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3195     }
3196 }
3197
3198 fn get_hint_if_single_char_arg(
3199     cx: &LateContext<'_>,
3200     arg: &hir::Expr<'_>,
3201     applicability: &mut Applicability,
3202 ) -> Option<String> {
3203     if_chain! {
3204         if let hir::ExprKind::Lit(lit) = &arg.kind;
3205         if let ast::LitKind::Str(r, style) = lit.node;
3206         let string = r.as_str();
3207         if string.len() == 1;
3208         then {
3209             let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
3210             let ch = if let ast::StrStyle::Raw(nhash) = style {
3211                 let nhash = nhash as usize;
3212                 // for raw string: r##"a"##
3213                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3214             } else {
3215                 // for regular string: "a"
3216                 &snip[1..(snip.len() - 1)]
3217             };
3218             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3219             Some(hint)
3220         } else {
3221             None
3222         }
3223     }
3224 }
3225
3226 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3227 fn lint_single_char_pattern(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
3228     let mut applicability = Applicability::MachineApplicable;
3229     if let Some(hint) = get_hint_if_single_char_arg(cx, arg, &mut applicability) {
3230         span_lint_and_sugg(
3231             cx,
3232             SINGLE_CHAR_PATTERN,
3233             arg.span,
3234             "single-character string constant used as pattern",
3235             "try using a `char` instead",
3236             hint,
3237             applicability,
3238         );
3239     }
3240 }
3241
3242 /// lint for length-1 `str`s as argument for `push_str`
3243 fn lint_single_char_push_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3244     let mut applicability = Applicability::MachineApplicable;
3245     if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[1], &mut applicability) {
3246         let base_string_snippet =
3247             snippet_with_applicability(cx, args[0].span.source_callsite(), "..", &mut applicability);
3248         let sugg = format!("{}.push({})", base_string_snippet, extension_string);
3249         span_lint_and_sugg(
3250             cx,
3251             SINGLE_CHAR_PUSH_STR,
3252             expr.span,
3253             "calling `push_str()` using a single-character string literal",
3254             "consider using `push` with a character literal",
3255             sugg,
3256             applicability,
3257         );
3258     }
3259 }
3260
3261 /// lint for length-1 `str`s as argument for `insert_str`
3262 fn lint_single_char_insert_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3263     let mut applicability = Applicability::MachineApplicable;
3264     if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[2], &mut applicability) {
3265         let base_string_snippet =
3266             snippet_with_applicability(cx, args[0].span.source_callsite(), "_", &mut applicability);
3267         let pos_arg = snippet(cx, args[1].span, "..");
3268         let sugg = format!("{}.insert({}, {})", base_string_snippet, pos_arg, extension_string);
3269         span_lint_and_sugg(
3270             cx,
3271             SINGLE_CHAR_PUSH_STR,
3272             expr.span,
3273             "calling `insert_str()` using a single-character string literal",
3274             "consider using `insert` with a character literal",
3275             sugg,
3276             applicability,
3277         );
3278     }
3279 }
3280
3281 /// Checks for the `USELESS_ASREF` lint.
3282 fn lint_asref(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3283     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3284     // check if the call is to the actual `AsRef` or `AsMut` trait
3285     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3286         // check if the type after `as_ref` or `as_mut` is the same as before
3287         let recvr = &as_ref_args[0];
3288         let rcv_ty = cx.typeck_results().expr_ty(recvr);
3289         let res_ty = cx.typeck_results().expr_ty(expr);
3290         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3291         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3292         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3293             // allow the `as_ref` or `as_mut` if it is followed by another method call
3294             if_chain! {
3295                 if let Some(parent) = get_parent_expr(cx, expr);
3296                 if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
3297                 if span != &expr.span;
3298                 then {
3299                     return;
3300                 }
3301             }
3302
3303             let mut applicability = Applicability::MachineApplicable;
3304             span_lint_and_sugg(
3305                 cx,
3306                 USELESS_ASREF,
3307                 expr.span,
3308                 &format!("this call to `{}` does nothing", call_name),
3309                 "try this",
3310                 snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(),
3311                 applicability,
3312             );
3313         }
3314     }
3315 }
3316
3317 fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3318     has_iter_method(cx, self_ref_ty).map(|ty_name| {
3319         let mutbl = match self_ref_ty.kind() {
3320             ty::Ref(_, _, mutbl) => mutbl,
3321             _ => unreachable!(),
3322         };
3323         let method_name = match mutbl {
3324             hir::Mutability::Not => "iter",
3325             hir::Mutability::Mut => "iter_mut",
3326         };
3327         (ty_name, method_name)
3328     })
3329 }
3330
3331 fn lint_into_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3332     if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3333         return;
3334     }
3335     if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3336         span_lint_and_sugg(
3337             cx,
3338             INTO_ITER_ON_REF,
3339             method_span,
3340             &format!(
3341                 "this `.into_iter()` call is equivalent to `.{}()` and will not consume the `{}`",
3342                 method_name, kind,
3343             ),
3344             "call directly",
3345             method_name.to_string(),
3346             Applicability::MachineApplicable,
3347         );
3348     }
3349 }
3350
3351 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3352 fn lint_maybe_uninit(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3353     if_chain! {
3354         if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3355         if args.is_empty();
3356         if let hir::ExprKind::Path(ref path) = callee.kind;
3357         if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3358         if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer));
3359         then {
3360             span_lint(
3361                 cx,
3362                 UNINIT_ASSUMED_INIT,
3363                 outer.span,
3364                 "this call for this type may be undefined behavior"
3365             );
3366         }
3367     }
3368 }
3369
3370 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
3371     match ty.kind() {
3372         ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3373         ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3374         ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3375         _ => false,
3376     }
3377 }
3378
3379 fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
3380     span_lint_and_help(
3381         cx,
3382         SUSPICIOUS_MAP,
3383         expr.span,
3384         "this call to `map()` won't have an effect on the call to `count()`",
3385         None,
3386         "make sure you did not confuse `map` with `filter` or `for_each`",
3387     );
3388 }
3389
3390 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3391 fn lint_option_as_ref_deref<'tcx>(
3392     cx: &LateContext<'tcx>,
3393     expr: &hir::Expr<'_>,
3394     as_ref_args: &[hir::Expr<'_>],
3395     map_args: &[hir::Expr<'_>],
3396     is_mut: bool,
3397 ) {
3398     let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3399
3400     let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]);
3401     if !is_type_diagnostic_item(cx, option_ty, sym!(option_type)) {
3402         return;
3403     }
3404
3405     let deref_aliases: [&[&str]; 9] = [
3406         &paths::DEREF_TRAIT_METHOD,
3407         &paths::DEREF_MUT_TRAIT_METHOD,
3408         &paths::CSTRING_AS_C_STR,
3409         &paths::OS_STRING_AS_OS_STR,
3410         &paths::PATH_BUF_AS_PATH,
3411         &paths::STRING_AS_STR,
3412         &paths::STRING_AS_MUT_STR,
3413         &paths::VEC_AS_SLICE,
3414         &paths::VEC_AS_MUT_SLICE,
3415     ];
3416
3417     let is_deref = match map_args[1].kind {
3418         hir::ExprKind::Path(ref expr_qpath) => cx
3419             .qpath_res(expr_qpath, map_args[1].hir_id)
3420             .opt_def_id()
3421             .map_or(false, |fun_def_id| {
3422                 deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
3423             }),
3424         hir::ExprKind::Closure(_, _, body_id, _, _) => {
3425             let closure_body = cx.tcx.hir().body(body_id);
3426             let closure_expr = remove_blocks(&closure_body.value);
3427
3428             match &closure_expr.kind {
3429                 hir::ExprKind::MethodCall(_, _, args, _) => {
3430                     if_chain! {
3431                         if args.len() == 1;
3432                         if let hir::ExprKind::Path(qpath) = &args[0].kind;
3433                         if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, args[0].hir_id);
3434                         if closure_body.params[0].pat.hir_id == local_id;
3435                         let adj = cx
3436                             .typeck_results()
3437                             .expr_adjustments(&args[0])
3438                             .iter()
3439                             .map(|x| &x.kind)
3440                             .collect::<Box<[_]>>();
3441                         if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3442                         then {
3443                             let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
3444                             deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3445                         } else {
3446                             false
3447                         }
3448                     }
3449                 },
3450                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3451                     if_chain! {
3452                         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind;
3453                         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind;
3454                         if let hir::ExprKind::Path(ref qpath) = inner2.kind;
3455                         if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, inner2.hir_id);
3456                         then {
3457                             closure_body.params[0].pat.hir_id == local_id
3458                         } else {
3459                             false
3460                         }
3461                     }
3462                 },
3463                 _ => false,
3464             }
3465         },
3466         _ => false,
3467     };
3468
3469     if is_deref {
3470         let current_method = if is_mut {
3471             format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3472         } else {
3473             format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3474         };
3475         let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3476         let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3477         let suggestion = format!("try using {} instead", method_hint);
3478
3479         let msg = format!(
3480             "called `{0}` on an Option value. This can be done more directly \
3481             by calling `{1}` instead",
3482             current_method, hint
3483         );
3484         span_lint_and_sugg(
3485             cx,
3486             OPTION_AS_REF_DEREF,
3487             expr.span,
3488             &msg,
3489             &suggestion,
3490             hint,
3491             Applicability::MachineApplicable,
3492         );
3493     }
3494 }
3495
3496 fn lint_map_collect(
3497     cx: &LateContext<'_>,
3498     expr: &hir::Expr<'_>,
3499     map_args: &[hir::Expr<'_>],
3500     collect_args: &[hir::Expr<'_>],
3501 ) {
3502     if_chain! {
3503         // called on Iterator
3504         if let [map_expr] = collect_args;
3505         if match_trait_method(cx, map_expr, &paths::ITERATOR);
3506         // return of collect `Result<(),_>`
3507         let collect_ret_ty = cx.typeck_results().expr_ty(expr);
3508         if is_type_diagnostic_item(cx, collect_ret_ty, sym!(result_type));
3509         if let ty::Adt(_, substs) = collect_ret_ty.kind();
3510         if let Some(result_t) = substs.types().next();
3511         if result_t.is_unit();
3512         // get parts for snippet
3513         if let [iter, map_fn] = map_args;
3514         then {
3515             span_lint_and_sugg(
3516                 cx,
3517                 MAP_COLLECT_RESULT_UNIT,
3518                 expr.span,
3519                 "`.map().collect()` can be replaced with `.try_for_each()`",
3520                 "try this",
3521                 format!(
3522                     "{}.try_for_each({})",
3523                     snippet(cx, iter.span, ".."),
3524                     snippet(cx, map_fn.span, "..")
3525                 ),
3526                 Applicability::MachineApplicable,
3527             );
3528         }
3529     }
3530 }
3531
3532 /// Given a `Result<T, E>` type, return its error type (`E`).
3533 fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3534     match ty.kind() {
3535         ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym!(result_type)) => substs.types().nth(1),
3536         _ => None,
3537     }
3538 }
3539
3540 /// This checks whether a given type is known to implement Debug.
3541 fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
3542     cx.tcx
3543         .get_diagnostic_item(sym::debug_trait)
3544         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3545 }
3546
3547 enum Convention {
3548     Eq(&'static str),
3549     StartsWith(&'static str),
3550 }
3551
3552 #[rustfmt::skip]
3553 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3554     (Convention::Eq("new"), &[SelfKind::No]),
3555     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3556     (Convention::StartsWith("from_"), &[SelfKind::No]),
3557     (Convention::StartsWith("into_"), &[SelfKind::Value]),
3558     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3559     (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3560     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3561 ];
3562
3563 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3564     unsafety: hir::Unsafety::Normal,
3565     constness: hir::Constness::NotConst,
3566     asyncness: hir::IsAsync::NotAsync,
3567     abi: rustc_target::spec::abi::Abi::Rust,
3568 };
3569
3570 struct ShouldImplTraitCase {
3571     trait_name: &'static str,
3572     method_name: &'static str,
3573     param_count: usize,
3574     fn_header: hir::FnHeader,
3575     // implicit self kind expected (none, self, &self, ...)
3576     self_kind: SelfKind,
3577     // checks against the output type
3578     output_type: OutType,
3579     // certain methods with explicit lifetimes can't implement the equivalent trait method
3580     lint_explicit_lifetime: bool,
3581 }
3582 impl ShouldImplTraitCase {
3583     const fn new(
3584         trait_name: &'static str,
3585         method_name: &'static str,
3586         param_count: usize,
3587         fn_header: hir::FnHeader,
3588         self_kind: SelfKind,
3589         output_type: OutType,
3590         lint_explicit_lifetime: bool,
3591     ) -> ShouldImplTraitCase {
3592         ShouldImplTraitCase {
3593             trait_name,
3594             method_name,
3595             param_count,
3596             fn_header,
3597             self_kind,
3598             output_type,
3599             lint_explicit_lifetime,
3600         }
3601     }
3602
3603     fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3604         self.lint_explicit_lifetime
3605             || !impl_item.generics.params.iter().any(|p| {
3606                 matches!(
3607                     p.kind,
3608                     hir::GenericParamKind::Lifetime {
3609                         kind: hir::LifetimeParamKind::Explicit
3610                     }
3611                 )
3612             })
3613     }
3614 }
3615
3616 #[rustfmt::skip]
3617 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3618     ShouldImplTraitCase::new("std::ops::Add", "add",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3619     ShouldImplTraitCase::new("std::convert::AsMut", "as_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3620     ShouldImplTraitCase::new("std::convert::AsRef", "as_ref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3621     ShouldImplTraitCase::new("std::ops::BitAnd", "bitand",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3622     ShouldImplTraitCase::new("std::ops::BitOr", "bitor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3623     ShouldImplTraitCase::new("std::ops::BitXor", "bitxor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3624     ShouldImplTraitCase::new("std::borrow::Borrow", "borrow",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3625     ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3626     ShouldImplTraitCase::new("std::clone::Clone", "clone",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
3627     ShouldImplTraitCase::new("std::cmp::Ord", "cmp",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
3628     // FIXME: default doesn't work
3629     ShouldImplTraitCase::new("std::default::Default", "default",  0,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3630     ShouldImplTraitCase::new("std::ops::Deref", "deref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3631     ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3632     ShouldImplTraitCase::new("std::ops::Div", "div",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3633     ShouldImplTraitCase::new("std::ops::Drop", "drop",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Unit, true),
3634     ShouldImplTraitCase::new("std::cmp::PartialEq", "eq",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Bool, true),
3635     ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3636     ShouldImplTraitCase::new("std::str::FromStr", "from_str",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3637     ShouldImplTraitCase::new("std::hash::Hash", "hash",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Unit, true),
3638     ShouldImplTraitCase::new("std::ops::Index", "index",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3639     ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut",  2,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3640     ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3641     ShouldImplTraitCase::new("std::ops::Mul", "mul",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3642     ShouldImplTraitCase::new("std::ops::Neg", "neg",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3643     ShouldImplTraitCase::new("std::iter::Iterator", "next",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Any, false),
3644     ShouldImplTraitCase::new("std::ops::Not", "not",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3645     ShouldImplTraitCase::new("std::ops::Rem", "rem",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3646     ShouldImplTraitCase::new("std::ops::Shl", "shl",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3647     ShouldImplTraitCase::new("std::ops::Shr", "shr",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3648     ShouldImplTraitCase::new("std::ops::Sub", "sub",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3649 ];
3650
3651 #[rustfmt::skip]
3652 const PATTERN_METHODS: [(&str, usize); 17] = [
3653     ("contains", 1),
3654     ("starts_with", 1),
3655     ("ends_with", 1),
3656     ("find", 1),
3657     ("rfind", 1),
3658     ("split", 1),
3659     ("rsplit", 1),
3660     ("split_terminator", 1),
3661     ("rsplit_terminator", 1),
3662     ("splitn", 2),
3663     ("rsplitn", 2),
3664     ("matches", 1),
3665     ("rmatches", 1),
3666     ("match_indices", 1),
3667     ("rmatch_indices", 1),
3668     ("trim_start_matches", 1),
3669     ("trim_end_matches", 1),
3670 ];
3671
3672 #[derive(Clone, Copy, PartialEq, Debug)]
3673 enum SelfKind {
3674     Value,
3675     Ref,
3676     RefMut,
3677     No,
3678 }
3679
3680 impl SelfKind {
3681     fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3682         fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3683             if ty == parent_ty {
3684                 true
3685             } else if ty.is_box() {
3686                 ty.boxed_ty() == parent_ty
3687             } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3688                 if let ty::Adt(_, substs) = ty.kind() {
3689                     substs.types().next().map_or(false, |t| t == parent_ty)
3690                 } else {
3691                     false
3692                 }
3693             } else {
3694                 false
3695             }
3696         }
3697
3698         fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3699             if let ty::Ref(_, t, m) = *ty.kind() {
3700                 return m == mutability && t == parent_ty;
3701             }
3702
3703             let trait_path = match mutability {
3704                 hir::Mutability::Not => &paths::ASREF_TRAIT,
3705                 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3706             };
3707
3708             let trait_def_id = match get_trait_def_id(cx, trait_path) {
3709                 Some(did) => did,
3710                 None => return false,
3711             };
3712             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3713         }
3714
3715         match self {
3716             Self::Value => matches_value(cx, parent_ty, ty),
3717             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3718             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3719             Self::No => ty != parent_ty,
3720         }
3721     }
3722
3723     #[must_use]
3724     fn description(self) -> &'static str {
3725         match self {
3726             Self::Value => "self by value",
3727             Self::Ref => "self by reference",
3728             Self::RefMut => "self by mutable reference",
3729             Self::No => "no self",
3730         }
3731     }
3732 }
3733
3734 impl Convention {
3735     #[must_use]
3736     fn check(&self, other: &str) -> bool {
3737         match *self {
3738             Self::Eq(this) => this == other,
3739             Self::StartsWith(this) => other.starts_with(this) && this != other,
3740         }
3741     }
3742 }
3743
3744 impl fmt::Display for Convention {
3745     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3746         match *self {
3747             Self::Eq(this) => this.fmt(f),
3748             Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3749         }
3750     }
3751 }
3752
3753 #[derive(Clone, Copy)]
3754 enum OutType {
3755     Unit,
3756     Bool,
3757     Any,
3758     Ref,
3759 }
3760
3761 impl OutType {
3762     fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
3763         let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3764         match (self, ty) {
3765             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3766             (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3767             (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3768             (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3769             (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3770             _ => false,
3771         }
3772     }
3773 }
3774
3775 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3776     if let hir::TyKind::Path(ref p) = ty.kind {
3777         match_qpath(p, &["bool"])
3778     } else {
3779         false
3780     }
3781 }
3782
3783 // Returns `true` if `expr` contains a return expression
3784 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3785     struct RetCallFinder {
3786         found: bool,
3787     }
3788
3789     impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3790         type Map = Map<'tcx>;
3791
3792         fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3793             if self.found {
3794                 return;
3795             }
3796             if let hir::ExprKind::Ret(..) = &expr.kind {
3797                 self.found = true;
3798             } else {
3799                 intravisit::walk_expr(self, expr);
3800             }
3801         }
3802
3803         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3804             intravisit::NestedVisitorMap::None
3805         }
3806     }
3807
3808     let mut visitor = RetCallFinder { found: false };
3809     visitor.visit_expr(expr);
3810     visitor.found
3811 }
3812
3813 fn check_pointer_offset(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3814     if_chain! {
3815         if args.len() == 2;
3816         if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind();
3817         if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3818         if layout.is_zst();
3819         then {
3820             span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3821         }
3822     }
3823 }
3824
3825 fn lint_filetype_is_file(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3826     let ty = cx.typeck_results().expr_ty(&args[0]);
3827
3828     if !match_type(cx, ty, &paths::FILE_TYPE) {
3829         return;
3830     }
3831
3832     let span: Span;
3833     let verb: &str;
3834     let lint_unary: &str;
3835     let help_unary: &str;
3836     if_chain! {
3837         if let Some(parent) = get_parent_expr(cx, expr);
3838         if let hir::ExprKind::Unary(op, _) = parent.kind;
3839         if op == hir::UnOp::UnNot;
3840         then {
3841             lint_unary = "!";
3842             verb = "denies";
3843             help_unary = "";
3844             span = parent.span;
3845         } else {
3846             lint_unary = "";
3847             verb = "covers";
3848             help_unary = "!";
3849             span = expr.span;
3850         }
3851     }
3852     let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3853     let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3854     span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
3855 }
3856
3857 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3858     expected.constness == actual.constness
3859         && expected.unsafety == actual.unsafety
3860         && expected.asyncness == actual.asyncness
3861 }