]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
add MSRV to more lints specified in #6097
[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::{TraitItem, TraitItemKind};
18 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
19 use rustc_middle::lint::in_external_macro;
20 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
21 use rustc_semver::RustcVersion;
22 use rustc_session::{declare_tool_lint, impl_lint_pass};
23 use rustc_span::source_map::Span;
24 use rustc_span::symbol::{sym, SymbolStr};
25
26 use crate::consts::{constant, Constant};
27 use crate::utils::eager_or_lazy::is_lazyness_candidate;
28 use crate::utils::usage::mutated_variables;
29 use crate::utils::{
30     contains_return, contains_ty, get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, higher,
31     implements_trait, in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
32     match_def_path, match_qpath, match_trait_method, match_type, match_var, meets_msrv, method_calls,
33     method_chain_args, paths, remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability,
34     snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg,
35     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 or string 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(_)` or `_.contains(_)`.
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 or string search followed by `is_some()`, which is more succinctly expressed as a call to `any()` or `contains()`"
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`/`insert_str` with a single-character string literal
1294     /// where `push`/`insert` 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.insert_str(0, "R");
1304     /// string.push_str("R");
1305     /// ```
1306     /// Could be written as
1307     /// ```rust
1308     /// let mut string = String::new();
1309     /// string.insert(0, 'R');
1310     /// string.push('R');
1311     /// ```
1312     pub SINGLE_CHAR_ADD_STR,
1313     style,
1314     "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1315 }
1316
1317 declare_clippy_lint! {
1318     /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1319     /// lazily evaluated closures on `Option` and `Result`.
1320     ///
1321     /// This lint suggests changing the following functions, when eager evaluation results in
1322     /// simpler code:
1323     ///  - `unwrap_or_else` to `unwrap_or`
1324     ///  - `and_then` to `and`
1325     ///  - `or_else` to `or`
1326     ///  - `get_or_insert_with` to `get_or_insert`
1327     ///  - `ok_or_else` to `ok_or`
1328     ///
1329     /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1330     ///
1331     /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1332     /// side effects. Eagerly evaluating them can change the semantics of the program.
1333     ///
1334     /// **Example:**
1335     ///
1336     /// ```rust
1337     /// // example code where clippy issues a warning
1338     /// let opt: Option<u32> = None;
1339     ///
1340     /// opt.unwrap_or_else(|| 42);
1341     /// ```
1342     /// Use instead:
1343     /// ```rust
1344     /// let opt: Option<u32> = None;
1345     ///
1346     /// opt.unwrap_or(42);
1347     /// ```
1348     pub UNNECESSARY_LAZY_EVALUATIONS,
1349     style,
1350     "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1351 }
1352
1353 declare_clippy_lint! {
1354     /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1355     ///
1356     /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1357     ///
1358     /// **Known problems:** None
1359     ///
1360     /// **Example:**
1361     ///
1362     /// ```rust
1363     /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1364     /// ```
1365     /// Use instead:
1366     /// ```rust
1367     /// (0..3).try_for_each(|t| Err(t));
1368     /// ```
1369     pub MAP_COLLECT_RESULT_UNIT,
1370     style,
1371     "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1372 }
1373
1374 declare_clippy_lint! {
1375     /// **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator`
1376     /// trait.
1377     ///
1378     /// **Why is this bad?** It is recommended style to use collect. See
1379     /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1380     ///
1381     /// **Known problems:** None.
1382     ///
1383     /// **Example:**
1384     ///
1385     /// ```rust
1386     /// use std::iter::FromIterator;
1387     ///
1388     /// let five_fives = std::iter::repeat(5).take(5);
1389     ///
1390     /// let v = Vec::from_iter(five_fives);
1391     ///
1392     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1393     /// ```
1394     /// Use instead:
1395     /// ```rust
1396     /// let five_fives = std::iter::repeat(5).take(5);
1397     ///
1398     /// let v: Vec<i32> = five_fives.collect();
1399     ///
1400     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1401     /// ```
1402     pub FROM_ITER_INSTEAD_OF_COLLECT,
1403     style,
1404     "use `.collect()` instead of `::from_iter()`"
1405 }
1406
1407 pub struct Methods {
1408     msrv: Option<RustcVersion>,
1409 }
1410
1411 impl Methods {
1412     #[must_use]
1413     pub fn new(msrv: Option<RustcVersion>) -> Self {
1414         Self { msrv }
1415     }
1416 }
1417
1418 impl_lint_pass!(Methods => [
1419     UNWRAP_USED,
1420     EXPECT_USED,
1421     SHOULD_IMPLEMENT_TRAIT,
1422     WRONG_SELF_CONVENTION,
1423     WRONG_PUB_SELF_CONVENTION,
1424     OK_EXPECT,
1425     MAP_UNWRAP_OR,
1426     RESULT_MAP_OR_INTO_OPTION,
1427     OPTION_MAP_OR_NONE,
1428     BIND_INSTEAD_OF_MAP,
1429     OR_FUN_CALL,
1430     EXPECT_FUN_CALL,
1431     CHARS_NEXT_CMP,
1432     CHARS_LAST_CMP,
1433     CLONE_ON_COPY,
1434     CLONE_ON_REF_PTR,
1435     CLONE_DOUBLE_REF,
1436     INEFFICIENT_TO_STRING,
1437     NEW_RET_NO_SELF,
1438     SINGLE_CHAR_PATTERN,
1439     SINGLE_CHAR_ADD_STR,
1440     SEARCH_IS_SOME,
1441     FILTER_NEXT,
1442     SKIP_WHILE_NEXT,
1443     FILTER_MAP,
1444     FILTER_MAP_NEXT,
1445     FLAT_MAP_IDENTITY,
1446     FIND_MAP,
1447     MAP_FLATTEN,
1448     ITERATOR_STEP_BY_ZERO,
1449     ITER_NEXT_SLICE,
1450     ITER_NTH,
1451     ITER_NTH_ZERO,
1452     ITER_SKIP_NEXT,
1453     GET_UNWRAP,
1454     STRING_EXTEND_CHARS,
1455     ITER_CLONED_COLLECT,
1456     USELESS_ASREF,
1457     UNNECESSARY_FOLD,
1458     UNNECESSARY_FILTER_MAP,
1459     INTO_ITER_ON_REF,
1460     SUSPICIOUS_MAP,
1461     UNINIT_ASSUMED_INIT,
1462     MANUAL_SATURATING_ARITHMETIC,
1463     ZST_OFFSET,
1464     FILETYPE_IS_FILE,
1465     OPTION_AS_REF_DEREF,
1466     UNNECESSARY_LAZY_EVALUATIONS,
1467     MAP_COLLECT_RESULT_UNIT,
1468     FROM_ITER_INSTEAD_OF_COLLECT,
1469 ]);
1470
1471 impl<'tcx> LateLintPass<'tcx> for Methods {
1472     #[allow(clippy::too_many_lines)]
1473     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1474         if in_macro(expr.span) {
1475             return;
1476         }
1477
1478         let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1479         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1480         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1481
1482         match method_names.as_slice() {
1483             ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1484             ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1485             ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1486             ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1487             ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1488             ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1489             ["unwrap_or_else", "map"] => {
1490                 if !lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0], self.msrv.as_ref()) {
1491                     unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or");
1492                 }
1493             },
1494             ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1495             ["and_then", ..] => {
1496                 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
1497                 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
1498                 if !biom_option_linted && !biom_result_linted {
1499                     unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "and");
1500                 }
1501             },
1502             ["or_else", ..] => {
1503                 if !bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]) {
1504                     unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "or");
1505                 }
1506             },
1507             ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1508             ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1509             ["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
1510             ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1511             ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1512             ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1], self.msrv.as_ref()),
1513             ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
1514             ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1515             ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1516             ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1517             ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1518             ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1519             ["is_some", "position"] => {
1520                 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1521             },
1522             ["is_some", "rposition"] => {
1523                 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1524             },
1525             ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1526             ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1527             ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1528             ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1529             ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1530             ["next", "skip"] => lint_iter_skip_next(cx, expr, arg_lists[1]),
1531             ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1532             ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1533             ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1534             ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1535             ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1536             ["count", "map"] => lint_suspicious_map(cx, expr),
1537             ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1538             ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1539                 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1540             },
1541             ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1542                 check_pointer_offset(cx, expr, arg_lists[0])
1543             },
1544             ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1545             ["map", "as_ref"] => {
1546                 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false, self.msrv.as_ref())
1547             },
1548             ["map", "as_mut"] => {
1549                 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true, self.msrv.as_ref())
1550             },
1551             ["unwrap_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or"),
1552             ["get_or_insert_with", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "get_or_insert"),
1553             ["ok_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "ok_or"),
1554             ["collect", "map"] => lint_map_collect(cx, expr, arg_lists[1], arg_lists[0]),
1555             _ => {},
1556         }
1557
1558         match expr.kind {
1559             hir::ExprKind::Call(ref func, ref args) => {
1560                 if let hir::ExprKind::Path(path) = &func.kind {
1561                     if match_qpath(path, &["from_iter"]) {
1562                         lint_from_iter(cx, expr, args);
1563                     }
1564                 }
1565             },
1566             hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1567                 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1568                 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1569
1570                 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1571                 if args.len() == 1 && method_call.ident.name == sym!(clone) {
1572                     lint_clone_on_copy(cx, expr, &args[0], self_ty);
1573                     lint_clone_on_ref_ptr(cx, expr, &args[0]);
1574                 }
1575                 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1576                     inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1577                 }
1578
1579                 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
1580                     if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
1581                         lint_single_char_push_string(cx, expr, args);
1582                     } else if match_def_path(cx, fn_def_id, &paths::INSERT_STR) {
1583                         lint_single_char_insert_string(cx, expr, args);
1584                     }
1585                 }
1586
1587                 match self_ty.kind() {
1588                     ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
1589                         for &(method, pos) in &PATTERN_METHODS {
1590                             if method_call.ident.name.as_str() == method && args.len() > pos {
1591                                 lint_single_char_pattern(cx, expr, &args[pos]);
1592                             }
1593                         }
1594                     },
1595                     ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
1596                         lint_into_iter(cx, expr, self_ty, *method_span);
1597                     },
1598                     _ => (),
1599                 }
1600             },
1601             hir::ExprKind::Binary(op, ref lhs, ref rhs)
1602                 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1603             {
1604                 let mut info = BinaryExprInfo {
1605                     expr,
1606                     chain: lhs,
1607                     other: rhs,
1608                     eq: op.node == hir::BinOpKind::Eq,
1609                 };
1610                 lint_binary_expr_with_method_call(cx, &mut info);
1611             }
1612             _ => (),
1613         }
1614     }
1615
1616     #[allow(clippy::too_many_lines)]
1617     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1618         if in_external_macro(cx.sess(), impl_item.span) {
1619             return;
1620         }
1621         let name = impl_item.ident.name.as_str();
1622         let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1623         let item = cx.tcx.hir().expect_item(parent);
1624         let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1625         let self_ty = cx.tcx.type_of(def_id);
1626         if_chain! {
1627             if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1628             if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1629             if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
1630
1631             let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1632             let method_sig = cx.tcx.fn_sig(method_def_id);
1633             let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1634
1635             let first_arg_ty = &method_sig.inputs().iter().next();
1636
1637             // check conventions w.r.t. conversion method names and predicates
1638             if let Some(first_arg_ty) = first_arg_ty;
1639
1640             then {
1641                 if cx.access_levels.is_exported(impl_item.hir_id) {
1642                     // check missing trait implementations
1643                     for method_config in &TRAIT_METHODS {
1644                         if name == method_config.method_name &&
1645                             sig.decl.inputs.len() == method_config.param_count &&
1646                             method_config.output_type.matches(cx, &sig.decl.output) &&
1647                             method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1648                             fn_header_equals(method_config.fn_header, sig.header) &&
1649                             method_config.lifetime_param_cond(&impl_item)
1650                         {
1651                             span_lint_and_help(
1652                                 cx,
1653                                 SHOULD_IMPLEMENT_TRAIT,
1654                                 impl_item.span,
1655                                 &format!(
1656                                     "method `{}` can be confused for the standard trait method `{}::{}`",
1657                                     method_config.method_name,
1658                                     method_config.trait_name,
1659                                     method_config.method_name
1660                                 ),
1661                                 None,
1662                                 &format!(
1663                                     "consider implementing the trait `{}` or choosing a less ambiguous method name",
1664                                     method_config.trait_name
1665                                 )
1666                             );
1667                         }
1668                     }
1669                 }
1670
1671                 if let Some((ref conv, self_kinds)) = &CONVENTIONS
1672                     .iter()
1673                     .find(|(ref conv, _)| conv.check(&name))
1674                 {
1675                     if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1676                         let lint = if item.vis.node.is_pub() {
1677                             WRONG_PUB_SELF_CONVENTION
1678                         } else {
1679                             WRONG_SELF_CONVENTION
1680                         };
1681
1682                         span_lint(
1683                             cx,
1684                             lint,
1685                             first_arg.pat.span,
1686                             &format!("methods called `{}` usually take {}; consider choosing a less ambiguous name",
1687                                 conv,
1688                                 &self_kinds
1689                                     .iter()
1690                                     .map(|k| k.description())
1691                                     .collect::<Vec<_>>()
1692                                     .join(" or ")
1693                             ),
1694                         );
1695                     }
1696                 }
1697             }
1698         }
1699
1700         // if this impl block implements a trait, lint in trait definition instead
1701         if let hir::ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
1702             return;
1703         }
1704
1705         if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1706             let ret_ty = return_ty(cx, impl_item.hir_id);
1707
1708             // walk the return type and check for Self (this does not check associated types)
1709             if contains_ty(ret_ty, self_ty) {
1710                 return;
1711             }
1712
1713             // if return type is impl trait, check the associated types
1714             if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1715                 // one of the associated types must be Self
1716                 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1717                     if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() {
1718                         // walk the associated type and check for Self
1719                         if contains_ty(projection_predicate.ty, self_ty) {
1720                             return;
1721                         }
1722                     }
1723                 }
1724             }
1725
1726             if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1727                 span_lint(
1728                     cx,
1729                     NEW_RET_NO_SELF,
1730                     impl_item.span,
1731                     "methods called `new` usually return `Self`",
1732                 );
1733             }
1734         }
1735     }
1736
1737     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1738         if_chain! {
1739             if !in_external_macro(cx.tcx.sess, item.span);
1740             if item.ident.name == sym::new;
1741             if let TraitItemKind::Fn(_, _) = item.kind;
1742             let ret_ty = return_ty(cx, item.hir_id);
1743             let self_ty = TraitRef::identity(cx.tcx, item.hir_id.owner.to_def_id()).self_ty();
1744             if !contains_ty(ret_ty, self_ty);
1745
1746             then {
1747                 span_lint(
1748                     cx,
1749                     NEW_RET_NO_SELF,
1750                     item.span,
1751                     "methods called `new` usually return `Self`",
1752                 );
1753             }
1754         }
1755     }
1756
1757     extract_msrv_attr!(LateContext);
1758 }
1759
1760 /// Checks for the `OR_FUN_CALL` lint.
1761 #[allow(clippy::too_many_lines)]
1762 fn lint_or_fun_call<'tcx>(
1763     cx: &LateContext<'tcx>,
1764     expr: &hir::Expr<'_>,
1765     method_span: Span,
1766     name: &str,
1767     args: &'tcx [hir::Expr<'_>],
1768 ) {
1769     /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1770     fn check_unwrap_or_default(
1771         cx: &LateContext<'_>,
1772         name: &str,
1773         fun: &hir::Expr<'_>,
1774         self_expr: &hir::Expr<'_>,
1775         arg: &hir::Expr<'_>,
1776         or_has_args: bool,
1777         span: Span,
1778     ) -> bool {
1779         if_chain! {
1780             if !or_has_args;
1781             if name == "unwrap_or";
1782             if let hir::ExprKind::Path(ref qpath) = fun.kind;
1783             let path = &*last_path_segment(qpath).ident.as_str();
1784             if ["default", "new"].contains(&path);
1785             let arg_ty = cx.typeck_results().expr_ty(arg);
1786             if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1787             if implements_trait(cx, arg_ty, default_trait_id, &[]);
1788
1789             then {
1790                 let mut applicability = Applicability::MachineApplicable;
1791                 span_lint_and_sugg(
1792                     cx,
1793                     OR_FUN_CALL,
1794                     span,
1795                     &format!("use of `{}` followed by a call to `{}`", name, path),
1796                     "try this",
1797                     format!(
1798                         "{}.unwrap_or_default()",
1799                         snippet_with_applicability(cx, self_expr.span, "..", &mut applicability)
1800                     ),
1801                     applicability,
1802                 );
1803
1804                 true
1805             } else {
1806                 false
1807             }
1808         }
1809     }
1810
1811     /// Checks for `*or(foo())`.
1812     #[allow(clippy::too_many_arguments)]
1813     fn check_general_case<'tcx>(
1814         cx: &LateContext<'tcx>,
1815         name: &str,
1816         method_span: Span,
1817         self_expr: &hir::Expr<'_>,
1818         arg: &'tcx hir::Expr<'_>,
1819         span: Span,
1820         // None if lambda is required
1821         fun_span: Option<Span>,
1822     ) {
1823         // (path, fn_has_argument, methods, suffix)
1824         static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [
1825             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1826             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1827             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1828             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1829         ];
1830
1831         if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
1832             if path.ident.as_str() == "len" {
1833                 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
1834
1835                 match ty.kind() {
1836                     ty::Slice(_) | ty::Array(_, _) => return,
1837                     _ => (),
1838                 }
1839
1840                 if is_type_diagnostic_item(cx, ty, sym::vec_type) {
1841                     return;
1842                 }
1843             }
1844         }
1845
1846         if_chain! {
1847             if KNOW_TYPES.iter().any(|k| k.2.contains(&name));
1848
1849             if is_lazyness_candidate(cx, arg);
1850             if !contains_return(&arg);
1851
1852             let self_ty = cx.typeck_results().expr_ty(self_expr);
1853
1854             if let Some(&(_, fn_has_arguments, poss, suffix)) =
1855                 KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0));
1856
1857             if poss.contains(&name);
1858
1859             then {
1860                 let sugg: Cow<'_, str> = {
1861                     let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) {
1862                         (false, Some(fun_span)) => (fun_span, false),
1863                         _ => (arg.span, true),
1864                     };
1865                     let snippet = snippet_with_macro_callsite(cx, snippet_span, "..");
1866                     if use_lambda {
1867                         let l_arg = if fn_has_arguments { "_" } else { "" };
1868                         format!("|{}| {}", l_arg, snippet).into()
1869                     } else {
1870                         snippet
1871                     }
1872                 };
1873                 let span_replace_word = method_span.with_hi(span.hi());
1874                 span_lint_and_sugg(
1875                     cx,
1876                     OR_FUN_CALL,
1877                     span_replace_word,
1878                     &format!("use of `{}` followed by a function call", name),
1879                     "try this",
1880                     format!("{}_{}({})", name, suffix, sugg),
1881                     Applicability::HasPlaceholders,
1882                 );
1883             }
1884         }
1885     }
1886
1887     if args.len() == 2 {
1888         match args[1].kind {
1889             hir::ExprKind::Call(ref fun, ref or_args) => {
1890                 let or_has_args = !or_args.is_empty();
1891                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1892                     let fun_span = if or_has_args { None } else { Some(fun.span) };
1893                     check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, fun_span);
1894                 }
1895             },
1896             hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => {
1897                 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, None);
1898             },
1899             _ => {},
1900         }
1901     }
1902 }
1903
1904 /// Checks for the `EXPECT_FUN_CALL` lint.
1905 #[allow(clippy::too_many_lines)]
1906 fn lint_expect_fun_call(
1907     cx: &LateContext<'_>,
1908     expr: &hir::Expr<'_>,
1909     method_span: Span,
1910     name: &str,
1911     args: &[hir::Expr<'_>],
1912 ) {
1913     // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1914     // `&str`
1915     fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1916         let mut arg_root = arg;
1917         loop {
1918             arg_root = match &arg_root.kind {
1919                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1920                 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
1921                     if call_args.len() == 1
1922                         && (method_name.ident.name == sym::as_str || method_name.ident.name == sym!(as_ref))
1923                         && {
1924                             let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
1925                             let base_type = arg_type.peel_refs();
1926                             *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym::string_type)
1927                         }
1928                     {
1929                         &call_args[0]
1930                     } else {
1931                         break;
1932                     }
1933                 },
1934                 _ => break,
1935             };
1936         }
1937         arg_root
1938     }
1939
1940     // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1941     // converted to string.
1942     fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
1943         let arg_ty = cx.typeck_results().expr_ty(arg);
1944         if is_type_diagnostic_item(cx, arg_ty, sym::string_type) {
1945             return false;
1946         }
1947         if let ty::Ref(_, ty, ..) = arg_ty.kind() {
1948             if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
1949                 return false;
1950             }
1951         };
1952         true
1953     }
1954
1955     // Check if an expression could have type `&'static str`, knowing that it
1956     // has type `&str` for some lifetime.
1957     fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
1958         match arg.kind {
1959             hir::ExprKind::Lit(_) => true,
1960             hir::ExprKind::Call(fun, _) => {
1961                 if let hir::ExprKind::Path(ref p) = fun.kind {
1962                     match cx.qpath_res(p, fun.hir_id) {
1963                         hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
1964                             cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
1965                             ty::Ref(ty::ReStatic, ..)
1966                         ),
1967                         _ => false,
1968                     }
1969                 } else {
1970                     false
1971                 }
1972             },
1973             hir::ExprKind::MethodCall(..) => {
1974                 cx.typeck_results()
1975                     .type_dependent_def_id(arg.hir_id)
1976                     .map_or(false, |method_id| {
1977                         matches!(
1978                             cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
1979                             ty::Ref(ty::ReStatic, ..)
1980                         )
1981                     })
1982             },
1983             hir::ExprKind::Path(ref p) => matches!(
1984                 cx.qpath_res(p, arg.hir_id),
1985                 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
1986             ),
1987             _ => false,
1988         }
1989     }
1990
1991     fn generate_format_arg_snippet(
1992         cx: &LateContext<'_>,
1993         a: &hir::Expr<'_>,
1994         applicability: &mut Applicability,
1995     ) -> Vec<String> {
1996         if_chain! {
1997             if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1998             if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1999             if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
2000
2001             then {
2002                 format_arg_expr_tup
2003                     .iter()
2004                     .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
2005                     .collect()
2006             } else {
2007                 unreachable!()
2008             }
2009         }
2010     }
2011
2012     fn is_call(node: &hir::ExprKind<'_>) -> bool {
2013         match node {
2014             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
2015                 is_call(&expr.kind)
2016             },
2017             hir::ExprKind::Call(..)
2018             | hir::ExprKind::MethodCall(..)
2019             // These variants are debatable or require further examination
2020             | hir::ExprKind::Match(..)
2021             | hir::ExprKind::Block{ .. } => true,
2022             _ => false,
2023         }
2024     }
2025
2026     if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
2027         return;
2028     }
2029
2030     let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
2031     let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::option_type) {
2032         "||"
2033     } else if is_type_diagnostic_item(cx, receiver_type, sym::result_type) {
2034         "|_|"
2035     } else {
2036         return;
2037     };
2038
2039     let arg_root = get_arg_root(cx, &args[1]);
2040
2041     let span_replace_word = method_span.with_hi(expr.span.hi());
2042
2043     let mut applicability = Applicability::MachineApplicable;
2044
2045     //Special handling for `format!` as arg_root
2046     if_chain! {
2047         if let hir::ExprKind::Block(block, None) = &arg_root.kind;
2048         if block.stmts.len() == 1;
2049         if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
2050         if let Some(arg_root) = &local.init;
2051         if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
2052         if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
2053         if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
2054         then {
2055             let fmt_spec = &format_args[0];
2056             let fmt_args = &format_args[1];
2057
2058             let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
2059
2060             args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
2061
2062             let sugg = args.join(", ");
2063
2064             span_lint_and_sugg(
2065                 cx,
2066                 EXPECT_FUN_CALL,
2067                 span_replace_word,
2068                 &format!("use of `{}` followed by a function call", name),
2069                 "try this",
2070                 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
2071                 applicability,
2072             );
2073
2074             return;
2075         }
2076     }
2077
2078     let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
2079     if requires_to_string(cx, arg_root) {
2080         arg_root_snippet.to_mut().push_str(".to_string()");
2081     }
2082
2083     span_lint_and_sugg(
2084         cx,
2085         EXPECT_FUN_CALL,
2086         span_replace_word,
2087         &format!("use of `{}` followed by a function call", name),
2088         "try this",
2089         format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
2090         applicability,
2091     );
2092 }
2093
2094 /// Checks for the `CLONE_ON_COPY` lint.
2095 fn lint_clone_on_copy(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
2096     let ty = cx.typeck_results().expr_ty(expr);
2097     if let ty::Ref(_, inner, _) = arg_ty.kind() {
2098         if let ty::Ref(_, innermost, _) = inner.kind() {
2099             span_lint_and_then(
2100                 cx,
2101                 CLONE_DOUBLE_REF,
2102                 expr.span,
2103                 "using `clone` on a double-reference; \
2104                 this will copy the reference instead of cloning the inner type",
2105                 |diag| {
2106                     if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
2107                         let mut ty = innermost;
2108                         let mut n = 0;
2109                         while let ty::Ref(_, inner, _) = ty.kind() {
2110                             ty = inner;
2111                             n += 1;
2112                         }
2113                         let refs: String = iter::repeat('&').take(n + 1).collect();
2114                         let derefs: String = iter::repeat('*').take(n).collect();
2115                         let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
2116                         diag.span_suggestion(
2117                             expr.span,
2118                             "try dereferencing it",
2119                             format!("{}({}{}).clone()", refs, derefs, snip.deref()),
2120                             Applicability::MaybeIncorrect,
2121                         );
2122                         diag.span_suggestion(
2123                             expr.span,
2124                             "or try being explicit if you are sure, that you want to clone a reference",
2125                             explicit,
2126                             Applicability::MaybeIncorrect,
2127                         );
2128                     }
2129                 },
2130             );
2131             return; // don't report clone_on_copy
2132         }
2133     }
2134
2135     if is_copy(cx, ty) {
2136         let snip;
2137         if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
2138             let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
2139             match &cx.tcx.hir().get(parent) {
2140                 hir::Node::Expr(parent) => match parent.kind {
2141                     // &*x is a nop, &x.clone() is not
2142                     hir::ExprKind::AddrOf(..) => return,
2143                     // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
2144                     hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
2145                         return;
2146                     },
2147
2148                     _ => {},
2149                 },
2150                 hir::Node::Stmt(stmt) => {
2151                     if let hir::StmtKind::Local(ref loc) = stmt.kind {
2152                         if let hir::PatKind::Ref(..) = loc.pat.kind {
2153                             // let ref y = *x borrows x, let ref y = x.clone() does not
2154                             return;
2155                         }
2156                     }
2157                 },
2158                 _ => {},
2159             }
2160
2161             // x.clone() might have dereferenced x, possibly through Deref impls
2162             if cx.typeck_results().expr_ty(arg) == ty {
2163                 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
2164             } else {
2165                 let deref_count = cx
2166                     .typeck_results()
2167                     .expr_adjustments(arg)
2168                     .iter()
2169                     .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
2170                     .count();
2171                 let derefs: String = iter::repeat('*').take(deref_count).collect();
2172                 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
2173             }
2174         } else {
2175             snip = None;
2176         }
2177         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |diag| {
2178             if let Some((text, snip)) = snip {
2179                 diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);
2180             }
2181         });
2182     }
2183 }
2184
2185 fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
2186     let obj_ty = cx.typeck_results().expr_ty(arg).peel_refs();
2187
2188     if let ty::Adt(_, subst) = obj_ty.kind() {
2189         let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
2190             "Rc"
2191         } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
2192             "Arc"
2193         } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
2194             "Weak"
2195         } else {
2196             return;
2197         };
2198
2199         let snippet = snippet_with_macro_callsite(cx, arg.span, "..");
2200
2201         span_lint_and_sugg(
2202             cx,
2203             CLONE_ON_REF_PTR,
2204             expr.span,
2205             "using `.clone()` on a ref-counted pointer",
2206             "try this",
2207             format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
2208             Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2209         );
2210     }
2211 }
2212
2213 fn lint_string_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2214     let arg = &args[1];
2215     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2216         let target = &arglists[0][0];
2217         let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
2218         let ref_str = if *self_ty.kind() == ty::Str {
2219             ""
2220         } else if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
2221             "&"
2222         } else {
2223             return;
2224         };
2225
2226         let mut applicability = Applicability::MachineApplicable;
2227         span_lint_and_sugg(
2228             cx,
2229             STRING_EXTEND_CHARS,
2230             expr.span,
2231             "calling `.extend(_.chars())`",
2232             "try this",
2233             format!(
2234                 "{}.push_str({}{})",
2235                 snippet_with_applicability(cx, args[0].span, "..", &mut applicability),
2236                 ref_str,
2237                 snippet_with_applicability(cx, target.span, "..", &mut applicability)
2238             ),
2239             applicability,
2240         );
2241     }
2242 }
2243
2244 fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2245     let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
2246     if is_type_diagnostic_item(cx, obj_ty, sym::string_type) {
2247         lint_string_extend(cx, expr, args);
2248     }
2249 }
2250
2251 fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2252     if_chain! {
2253         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type);
2254         if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0]));
2255         if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2256
2257         then {
2258             span_lint_and_sugg(
2259                 cx,
2260                 ITER_CLONED_COLLECT,
2261                 to_replace,
2262                 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2263                 more readable",
2264                 "try",
2265                 ".to_vec()".to_string(),
2266                 Applicability::MachineApplicable,
2267             );
2268         }
2269     }
2270 }
2271
2272 fn lint_unnecessary_fold(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2273     fn check_fold_with_op(
2274         cx: &LateContext<'_>,
2275         expr: &hir::Expr<'_>,
2276         fold_args: &[hir::Expr<'_>],
2277         fold_span: Span,
2278         op: hir::BinOpKind,
2279         replacement_method_name: &str,
2280         replacement_has_args: bool,
2281     ) {
2282         if_chain! {
2283             // Extract the body of the closure passed to fold
2284             if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2285             let closure_body = cx.tcx.hir().body(body_id);
2286             let closure_expr = remove_blocks(&closure_body.value);
2287
2288             // Check if the closure body is of the form `acc <op> some_expr(x)`
2289             if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2290             if bin_op.node == op;
2291
2292             // Extract the names of the two arguments to the closure
2293             if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2294             if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2295
2296             if match_var(&*left_expr, first_arg_ident);
2297             if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2298
2299             then {
2300                 let mut applicability = Applicability::MachineApplicable;
2301                 let sugg = if replacement_has_args {
2302                     format!(
2303                         "{replacement}(|{s}| {r})",
2304                         replacement = replacement_method_name,
2305                         s = second_arg_ident,
2306                         r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2307                     )
2308                 } else {
2309                     format!(
2310                         "{replacement}()",
2311                         replacement = replacement_method_name,
2312                     )
2313                 };
2314
2315                 span_lint_and_sugg(
2316                     cx,
2317                     UNNECESSARY_FOLD,
2318                     fold_span.with_hi(expr.span.hi()),
2319                     // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2320                     "this `.fold` can be written more succinctly using another method",
2321                     "try",
2322                     sugg,
2323                     applicability,
2324                 );
2325             }
2326         }
2327     }
2328
2329     // Check that this is a call to Iterator::fold rather than just some function called fold
2330     if !match_trait_method(cx, expr, &paths::ITERATOR) {
2331         return;
2332     }
2333
2334     assert!(
2335         fold_args.len() == 3,
2336         "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2337     );
2338
2339     // Check if the first argument to .fold is a suitable literal
2340     if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2341         match lit.node {
2342             ast::LitKind::Bool(false) => {
2343                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2344             },
2345             ast::LitKind::Bool(true) => {
2346                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2347             },
2348             ast::LitKind::Int(0, _) => {
2349                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2350             },
2351             ast::LitKind::Int(1, _) => {
2352                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2353             },
2354             _ => (),
2355         }
2356     }
2357 }
2358
2359 fn lint_step_by<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2360     if match_trait_method(cx, expr, &paths::ITERATOR) {
2361         if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) {
2362             span_lint(
2363                 cx,
2364                 ITERATOR_STEP_BY_ZERO,
2365                 expr.span,
2366                 "Iterator::step_by(0) will panic at runtime",
2367             );
2368         }
2369     }
2370 }
2371
2372 fn lint_iter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2373     let caller_expr = &iter_args[0];
2374
2375     // Skip lint if the `iter().next()` expression is a for loop argument,
2376     // since it is already covered by `&loops::ITER_NEXT_LOOP`
2377     let mut parent_expr_opt = get_parent_expr(cx, expr);
2378     while let Some(parent_expr) = parent_expr_opt {
2379         if higher::for_loop(parent_expr).is_some() {
2380             return;
2381         }
2382         parent_expr_opt = get_parent_expr(cx, parent_expr);
2383     }
2384
2385     if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() {
2386         // caller is a Slice
2387         if_chain! {
2388             if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind;
2389             if let Some(higher::Range { start: Some(start_expr), end: None, limits: ast::RangeLimits::HalfOpen })
2390                 = higher::range(index_expr);
2391             if let hir::ExprKind::Lit(ref start_lit) = &start_expr.kind;
2392             if let ast::LitKind::Int(start_idx, _) = start_lit.node;
2393             then {
2394                 let mut applicability = Applicability::MachineApplicable;
2395                 span_lint_and_sugg(
2396                     cx,
2397                     ITER_NEXT_SLICE,
2398                     expr.span,
2399                     "using `.iter().next()` on a Slice without end index",
2400                     "try calling",
2401                     format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx),
2402                     applicability,
2403                 );
2404             }
2405         }
2406     } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym::vec_type)
2407         || matches!(
2408             &cx.typeck_results().expr_ty(caller_expr).peel_refs().kind(),
2409             ty::Array(_, _)
2410         )
2411     {
2412         // caller is a Vec or an Array
2413         let mut applicability = Applicability::MachineApplicable;
2414         span_lint_and_sugg(
2415             cx,
2416             ITER_NEXT_SLICE,
2417             expr.span,
2418             "using `.iter().next()` on an array",
2419             "try calling",
2420             format!(
2421                 "{}.get(0)",
2422                 snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability)
2423             ),
2424             applicability,
2425         );
2426     }
2427 }
2428
2429 fn lint_iter_nth<'tcx>(
2430     cx: &LateContext<'tcx>,
2431     expr: &hir::Expr<'_>,
2432     nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2433     is_mut: bool,
2434 ) {
2435     let iter_args = nth_and_iter_args[1];
2436     let mut_str = if is_mut { "_mut" } else { "" };
2437     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() {
2438         "slice"
2439     } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym::vec_type) {
2440         "Vec"
2441     } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
2442         "VecDeque"
2443     } else {
2444         let nth_args = nth_and_iter_args[0];
2445         lint_iter_nth_zero(cx, expr, &nth_args);
2446         return; // caller is not a type that we want to lint
2447     };
2448
2449     span_lint_and_help(
2450         cx,
2451         ITER_NTH,
2452         expr.span,
2453         &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2454         None,
2455         &format!("calling `.get{}()` is both faster and more readable", mut_str),
2456     );
2457 }
2458
2459 fn lint_iter_nth_zero<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2460     if_chain! {
2461         if match_trait_method(cx, expr, &paths::ITERATOR);
2462         if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]);
2463         then {
2464             let mut applicability = Applicability::MachineApplicable;
2465             span_lint_and_sugg(
2466                 cx,
2467                 ITER_NTH_ZERO,
2468                 expr.span,
2469                 "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent",
2470                 "try calling `.next()` instead of `.nth(0)`",
2471                 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2472                 applicability,
2473             );
2474         }
2475     }
2476 }
2477
2478 fn lint_get_unwrap<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args: &'tcx [hir::Expr<'_>], is_mut: bool) {
2479     // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2480     // because they do not implement `IndexMut`
2481     let mut applicability = Applicability::MachineApplicable;
2482     let expr_ty = cx.typeck_results().expr_ty(&get_args[0]);
2483     let get_args_str = if get_args.len() > 1 {
2484         snippet_with_applicability(cx, get_args[1].span, "..", &mut applicability)
2485     } else {
2486         return; // not linting on a .get().unwrap() chain or variant
2487     };
2488     let mut needs_ref;
2489     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2490         needs_ref = get_args_str.parse::<usize>().is_ok();
2491         "slice"
2492     } else if is_type_diagnostic_item(cx, expr_ty, sym::vec_type) {
2493         needs_ref = get_args_str.parse::<usize>().is_ok();
2494         "Vec"
2495     } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
2496         needs_ref = get_args_str.parse::<usize>().is_ok();
2497         "VecDeque"
2498     } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
2499         needs_ref = true;
2500         "HashMap"
2501     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2502         needs_ref = true;
2503         "BTreeMap"
2504     } else {
2505         return; // caller is not a type that we want to lint
2506     };
2507
2508     let mut span = expr.span;
2509
2510     // Handle the case where the result is immediately dereferenced
2511     // by not requiring ref and pulling the dereference into the
2512     // suggestion.
2513     if_chain! {
2514         if needs_ref;
2515         if let Some(parent) = get_parent_expr(cx, expr);
2516         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2517         then {
2518             needs_ref = false;
2519             span = parent.span;
2520         }
2521     }
2522
2523     let mut_str = if is_mut { "_mut" } else { "" };
2524     let borrow_str = if !needs_ref {
2525         ""
2526     } else if is_mut {
2527         "&mut "
2528     } else {
2529         "&"
2530     };
2531
2532     span_lint_and_sugg(
2533         cx,
2534         GET_UNWRAP,
2535         span,
2536         &format!(
2537             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2538             mut_str, caller_type
2539         ),
2540         "try this",
2541         format!(
2542             "{}{}[{}]",
2543             borrow_str,
2544             snippet_with_applicability(cx, get_args[0].span, "..", &mut applicability),
2545             get_args_str
2546         ),
2547         applicability,
2548     );
2549 }
2550
2551 fn lint_iter_skip_next(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir::Expr<'_>]) {
2552     // lint if caller of skip is an Iterator
2553     if match_trait_method(cx, expr, &paths::ITERATOR) {
2554         if let [caller, n] = skip_args {
2555             let hint = format!(".nth({})", snippet(cx, n.span, ".."));
2556             span_lint_and_sugg(
2557                 cx,
2558                 ITER_SKIP_NEXT,
2559                 expr.span.trim_start(caller.span).unwrap(),
2560                 "called `skip(..).next()` on an iterator",
2561                 "use `nth` instead",
2562                 hint,
2563                 Applicability::MachineApplicable,
2564             );
2565         }
2566     }
2567 }
2568
2569 fn derefs_to_slice<'tcx>(
2570     cx: &LateContext<'tcx>,
2571     expr: &'tcx hir::Expr<'tcx>,
2572     ty: Ty<'tcx>,
2573 ) -> Option<&'tcx hir::Expr<'tcx>> {
2574     fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
2575         match ty.kind() {
2576             ty::Slice(_) => true,
2577             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2578             ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
2579             ty::Array(_, size) => size
2580                 .try_eval_usize(cx.tcx, cx.param_env)
2581                 .map_or(false, |size| size < 32),
2582             ty::Ref(_, inner, _) => may_slice(cx, inner),
2583             _ => false,
2584         }
2585     }
2586
2587     if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
2588         if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2589             Some(&args[0])
2590         } else {
2591             None
2592         }
2593     } else {
2594         match ty.kind() {
2595             ty::Slice(_) => Some(expr),
2596             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2597             ty::Ref(_, inner, _) => {
2598                 if may_slice(cx, inner) {
2599                     Some(expr)
2600                 } else {
2601                     None
2602                 }
2603             },
2604             _ => None,
2605         }
2606     }
2607 }
2608
2609 /// lint use of `unwrap()` for `Option`s and `Result`s
2610 fn lint_unwrap(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2611     let obj_ty = cx.typeck_results().expr_ty(&unwrap_args[0]).peel_refs();
2612
2613     let mess = if is_type_diagnostic_item(cx, obj_ty, sym::option_type) {
2614         Some((UNWRAP_USED, "an Option", "None"))
2615     } else if is_type_diagnostic_item(cx, obj_ty, sym::result_type) {
2616         Some((UNWRAP_USED, "a Result", "Err"))
2617     } else {
2618         None
2619     };
2620
2621     if let Some((lint, kind, none_value)) = mess {
2622         span_lint_and_help(
2623             cx,
2624             lint,
2625             expr.span,
2626             &format!("used `unwrap()` on `{}` value", kind,),
2627             None,
2628             &format!(
2629                 "if you don't want to handle the `{}` case gracefully, consider \
2630                 using `expect()` to provide a better panic message",
2631                 none_value,
2632             ),
2633         );
2634     }
2635 }
2636
2637 /// lint use of `expect()` for `Option`s and `Result`s
2638 fn lint_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2639     let obj_ty = cx.typeck_results().expr_ty(&expect_args[0]).peel_refs();
2640
2641     let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2642         Some((EXPECT_USED, "an Option", "None"))
2643     } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2644         Some((EXPECT_USED, "a Result", "Err"))
2645     } else {
2646         None
2647     };
2648
2649     if let Some((lint, kind, none_value)) = mess {
2650         span_lint_and_help(
2651             cx,
2652             lint,
2653             expr.span,
2654             &format!("used `expect()` on `{}` value", kind,),
2655             None,
2656             &format!("if this value is an `{}`, it will panic", none_value,),
2657         );
2658     }
2659 }
2660
2661 /// lint use of `ok().expect()` for `Result`s
2662 fn lint_ok_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2663     if_chain! {
2664         // lint if the caller of `ok()` is a `Result`
2665         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym::result_type);
2666         let result_type = cx.typeck_results().expr_ty(&ok_args[0]);
2667         if let Some(error_type) = get_error_type(cx, result_type);
2668         if has_debug_impl(error_type, cx);
2669
2670         then {
2671             span_lint_and_help(
2672                 cx,
2673                 OK_EXPECT,
2674                 expr.span,
2675                 "called `ok().expect()` on a `Result` value",
2676                 None,
2677                 "you can call `expect()` directly on the `Result`",
2678             );
2679         }
2680     }
2681 }
2682
2683 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2684 fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2685     // lint if caller of `.map().flatten()` is an Iterator
2686     if match_trait_method(cx, expr, &paths::ITERATOR) {
2687         let map_closure_ty = cx.typeck_results().expr_ty(&map_args[1]);
2688         let is_map_to_option = match map_closure_ty.kind() {
2689             ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
2690                 let map_closure_sig = match map_closure_ty.kind() {
2691                     ty::Closure(_, substs) => substs.as_closure().sig(),
2692                     _ => map_closure_ty.fn_sig(cx.tcx),
2693                 };
2694                 let map_closure_return_ty = cx.tcx.erase_late_bound_regions(map_closure_sig.output());
2695                 is_type_diagnostic_item(cx, map_closure_return_ty, sym::option_type)
2696             },
2697             _ => false,
2698         };
2699
2700         let method_to_use = if is_map_to_option {
2701             // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
2702             "filter_map"
2703         } else {
2704             // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
2705             "flat_map"
2706         };
2707         let func_snippet = snippet(cx, map_args[1].span, "..");
2708         let hint = format!(".{0}({1})", method_to_use, func_snippet);
2709         span_lint_and_sugg(
2710             cx,
2711             MAP_FLATTEN,
2712             expr.span.with_lo(map_args[0].span.hi()),
2713             "called `map(..).flatten()` on an `Iterator`",
2714             &format!("try using `{}` instead", method_to_use),
2715             hint,
2716             Applicability::MachineApplicable,
2717         );
2718     }
2719
2720     // lint if caller of `.map().flatten()` is an Option
2721     if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type) {
2722         let func_snippet = snippet(cx, map_args[1].span, "..");
2723         let hint = format!(".and_then({})", func_snippet);
2724         span_lint_and_sugg(
2725             cx,
2726             MAP_FLATTEN,
2727             expr.span.with_lo(map_args[0].span.hi()),
2728             "called `map(..).flatten()` on an `Option`",
2729             "try using `and_then` instead",
2730             hint,
2731             Applicability::MachineApplicable,
2732         );
2733     }
2734 }
2735
2736 const MAP_UNWRAP_OR_MSRV: RustcVersion = RustcVersion::new(1, 41, 0);
2737
2738 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2739 /// Return true if lint triggered
2740 fn lint_map_unwrap_or_else<'tcx>(
2741     cx: &LateContext<'tcx>,
2742     expr: &'tcx hir::Expr<'_>,
2743     map_args: &'tcx [hir::Expr<'_>],
2744     unwrap_args: &'tcx [hir::Expr<'_>],
2745     msrv: Option<&RustcVersion>,
2746 ) -> bool {
2747     if !meets_msrv(msrv, &MAP_UNWRAP_OR_MSRV) {
2748         return false;
2749     }
2750     // lint if the caller of `map()` is an `Option`
2751     let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type);
2752     let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::result_type);
2753
2754     if is_option || is_result {
2755         // Don't make a suggestion that may fail to compile due to mutably borrowing
2756         // the same variable twice.
2757         let map_mutated_vars = mutated_variables(&map_args[0], cx);
2758         let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2759         if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2760             if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2761                 return false;
2762             }
2763         } else {
2764             return false;
2765         }
2766
2767         // lint message
2768         let msg = if is_option {
2769             "called `map(<f>).unwrap_or_else(<g>)` on an `Option` value. This can be done more directly by calling \
2770             `map_or_else(<g>, <f>)` instead"
2771         } else {
2772             "called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling \
2773             `.map_or_else(<g>, <f>)` instead"
2774         };
2775         // get snippets for args to map() and unwrap_or_else()
2776         let map_snippet = snippet(cx, map_args[1].span, "..");
2777         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2778         // lint, with note if neither arg is > 1 line and both map() and
2779         // unwrap_or_else() have the same span
2780         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2781         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2782         if same_span && !multiline {
2783             let var_snippet = snippet(cx, map_args[0].span, "..");
2784             span_lint_and_sugg(
2785                 cx,
2786                 MAP_UNWRAP_OR,
2787                 expr.span,
2788                 msg,
2789                 "try this",
2790                 format!("{}.map_or_else({}, {})", var_snippet, unwrap_snippet, map_snippet),
2791                 Applicability::MachineApplicable,
2792             );
2793             return true;
2794         } else if same_span && multiline {
2795             span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2796             return true;
2797         }
2798     }
2799
2800     false
2801 }
2802
2803 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
2804 fn lint_map_or_none<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>]) {
2805     let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::option_type);
2806     let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::result_type);
2807
2808     // There are two variants of this `map_or` lint:
2809     // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
2810     // (2) using `map_or` as a combinator instead of `and_then`
2811     //
2812     // (For this lint) we don't care if any other type calls `map_or`
2813     if !is_option && !is_result {
2814         return;
2815     }
2816
2817     let (lint_name, msg, instead, hint) = {
2818         let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2819             match_qpath(qpath, &paths::OPTION_NONE)
2820         } else {
2821             return;
2822         };
2823
2824         if !default_arg_is_none {
2825             // nothing to lint!
2826             return;
2827         }
2828
2829         let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
2830             match_qpath(qpath, &paths::OPTION_SOME)
2831         } else {
2832             false
2833         };
2834
2835         if is_option {
2836             let self_snippet = snippet(cx, map_or_args[0].span, "..");
2837             let func_snippet = snippet(cx, map_or_args[2].span, "..");
2838             let msg = "called `map_or(None, ..)` on an `Option` value. This can be done more directly by calling \
2839                        `and_then(..)` instead";
2840             (
2841                 OPTION_MAP_OR_NONE,
2842                 msg,
2843                 "try using `and_then` instead",
2844                 format!("{0}.and_then({1})", self_snippet, func_snippet),
2845             )
2846         } else if f_arg_is_some {
2847             let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
2848                        `ok()` instead";
2849             let self_snippet = snippet(cx, map_or_args[0].span, "..");
2850             (
2851                 RESULT_MAP_OR_INTO_OPTION,
2852                 msg,
2853                 "try using `ok` instead",
2854                 format!("{0}.ok()", self_snippet),
2855             )
2856         } else {
2857             // nothing to lint!
2858             return;
2859         }
2860     };
2861
2862     span_lint_and_sugg(
2863         cx,
2864         lint_name,
2865         expr.span,
2866         msg,
2867         instead,
2868         hint,
2869         Applicability::MachineApplicable,
2870     );
2871 }
2872
2873 /// lint use of `filter().next()` for `Iterators`
2874 fn lint_filter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
2875     // lint if caller of `.filter().next()` is an Iterator
2876     if match_trait_method(cx, expr, &paths::ITERATOR) {
2877         let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
2878                    `.find(..)` instead.";
2879         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2880         if filter_snippet.lines().count() <= 1 {
2881             let iter_snippet = snippet(cx, filter_args[0].span, "..");
2882             // add note if not multi-line
2883             span_lint_and_sugg(
2884                 cx,
2885                 FILTER_NEXT,
2886                 expr.span,
2887                 msg,
2888                 "try this",
2889                 format!("{}.find({})", iter_snippet, filter_snippet),
2890                 Applicability::MachineApplicable,
2891             );
2892         } else {
2893             span_lint(cx, FILTER_NEXT, expr.span, msg);
2894         }
2895     }
2896 }
2897
2898 /// lint use of `skip_while().next()` for `Iterators`
2899 fn lint_skip_while_next<'tcx>(
2900     cx: &LateContext<'tcx>,
2901     expr: &'tcx hir::Expr<'_>,
2902     _skip_while_args: &'tcx [hir::Expr<'_>],
2903 ) {
2904     // lint if caller of `.skip_while().next()` is an Iterator
2905     if match_trait_method(cx, expr, &paths::ITERATOR) {
2906         span_lint_and_help(
2907             cx,
2908             SKIP_WHILE_NEXT,
2909             expr.span,
2910             "called `skip_while(<p>).next()` on an `Iterator`",
2911             None,
2912             "this is more succinctly expressed by calling `.find(!<p>)` instead",
2913         );
2914     }
2915 }
2916
2917 /// lint use of `filter().map()` for `Iterators`
2918 fn lint_filter_map<'tcx>(
2919     cx: &LateContext<'tcx>,
2920     expr: &'tcx hir::Expr<'_>,
2921     _filter_args: &'tcx [hir::Expr<'_>],
2922     _map_args: &'tcx [hir::Expr<'_>],
2923 ) {
2924     // lint if caller of `.filter().map()` is an Iterator
2925     if match_trait_method(cx, expr, &paths::ITERATOR) {
2926         let msg = "called `filter(..).map(..)` on an `Iterator`";
2927         let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2928         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2929     }
2930 }
2931
2932 const FILTER_MAP_NEXT_MSRV: RustcVersion = RustcVersion::new(1, 30, 0);
2933
2934 /// lint use of `filter_map().next()` for `Iterators`
2935 fn lint_filter_map_next<'tcx>(
2936     cx: &LateContext<'tcx>,
2937     expr: &'tcx hir::Expr<'_>,
2938     filter_args: &'tcx [hir::Expr<'_>],
2939     msrv: Option<&RustcVersion>,
2940 ) {
2941     if match_trait_method(cx, expr, &paths::ITERATOR) {
2942         if !meets_msrv(msrv, &FILTER_MAP_NEXT_MSRV) {
2943             return;
2944         }
2945
2946         let msg = "called `filter_map(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
2947                    `.find_map(..)` instead.";
2948         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2949         if filter_snippet.lines().count() <= 1 {
2950             let iter_snippet = snippet(cx, filter_args[0].span, "..");
2951             span_lint_and_sugg(
2952                 cx,
2953                 FILTER_MAP_NEXT,
2954                 expr.span,
2955                 msg,
2956                 "try this",
2957                 format!("{}.find_map({})", iter_snippet, filter_snippet),
2958                 Applicability::MachineApplicable,
2959             );
2960         } else {
2961             span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2962         }
2963     }
2964 }
2965
2966 /// lint use of `find().map()` for `Iterators`
2967 fn lint_find_map<'tcx>(
2968     cx: &LateContext<'tcx>,
2969     expr: &'tcx hir::Expr<'_>,
2970     _find_args: &'tcx [hir::Expr<'_>],
2971     map_args: &'tcx [hir::Expr<'_>],
2972 ) {
2973     // lint if caller of `.filter().map()` is an Iterator
2974     if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2975         let msg = "called `find(..).map(..)` on an `Iterator`";
2976         let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2977         span_lint_and_help(cx, FIND_MAP, expr.span, msg, None, hint);
2978     }
2979 }
2980
2981 /// lint use of `filter_map().map()` for `Iterators`
2982 fn lint_filter_map_map<'tcx>(
2983     cx: &LateContext<'tcx>,
2984     expr: &'tcx hir::Expr<'_>,
2985     _filter_args: &'tcx [hir::Expr<'_>],
2986     _map_args: &'tcx [hir::Expr<'_>],
2987 ) {
2988     // lint if caller of `.filter().map()` is an Iterator
2989     if match_trait_method(cx, expr, &paths::ITERATOR) {
2990         let msg = "called `filter_map(..).map(..)` on an `Iterator`";
2991         let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2992         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2993     }
2994 }
2995
2996 /// lint use of `filter().flat_map()` for `Iterators`
2997 fn lint_filter_flat_map<'tcx>(
2998     cx: &LateContext<'tcx>,
2999     expr: &'tcx hir::Expr<'_>,
3000     _filter_args: &'tcx [hir::Expr<'_>],
3001     _map_args: &'tcx [hir::Expr<'_>],
3002 ) {
3003     // lint if caller of `.filter().flat_map()` is an Iterator
3004     if match_trait_method(cx, expr, &paths::ITERATOR) {
3005         let msg = "called `filter(..).flat_map(..)` on an `Iterator`";
3006         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3007                     and filtering by returning `iter::empty()`";
3008         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3009     }
3010 }
3011
3012 /// lint use of `filter_map().flat_map()` for `Iterators`
3013 fn lint_filter_map_flat_map<'tcx>(
3014     cx: &LateContext<'tcx>,
3015     expr: &'tcx hir::Expr<'_>,
3016     _filter_args: &'tcx [hir::Expr<'_>],
3017     _map_args: &'tcx [hir::Expr<'_>],
3018 ) {
3019     // lint if caller of `.filter_map().flat_map()` is an Iterator
3020     if match_trait_method(cx, expr, &paths::ITERATOR) {
3021         let msg = "called `filter_map(..).flat_map(..)` on an `Iterator`";
3022         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3023                     and filtering by returning `iter::empty()`";
3024         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3025     }
3026 }
3027
3028 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
3029 fn lint_flat_map_identity<'tcx>(
3030     cx: &LateContext<'tcx>,
3031     expr: &'tcx hir::Expr<'_>,
3032     flat_map_args: &'tcx [hir::Expr<'_>],
3033     flat_map_span: Span,
3034 ) {
3035     if match_trait_method(cx, expr, &paths::ITERATOR) {
3036         let arg_node = &flat_map_args[1].kind;
3037
3038         let apply_lint = |message: &str| {
3039             span_lint_and_sugg(
3040                 cx,
3041                 FLAT_MAP_IDENTITY,
3042                 flat_map_span.with_hi(expr.span.hi()),
3043                 message,
3044                 "try",
3045                 "flatten()".to_string(),
3046                 Applicability::MachineApplicable,
3047             );
3048         };
3049
3050         if_chain! {
3051             if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
3052             let body = cx.tcx.hir().body(*body_id);
3053
3054             if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
3055             if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
3056
3057             if path.segments.len() == 1;
3058             if path.segments[0].ident.as_str() == binding_ident.as_str();
3059
3060             then {
3061                 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
3062             }
3063         }
3064
3065         if_chain! {
3066             if let hir::ExprKind::Path(ref qpath) = arg_node;
3067
3068             if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
3069
3070             then {
3071                 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
3072             }
3073         }
3074     }
3075 }
3076
3077 /// lint searching an Iterator followed by `is_some()`
3078 /// or calling `find()` on a string followed by `is_some()`
3079 fn lint_search_is_some<'tcx>(
3080     cx: &LateContext<'tcx>,
3081     expr: &'tcx hir::Expr<'_>,
3082     search_method: &str,
3083     search_args: &'tcx [hir::Expr<'_>],
3084     is_some_args: &'tcx [hir::Expr<'_>],
3085     method_span: Span,
3086 ) {
3087     // lint if caller of search is an Iterator
3088     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
3089         let msg = format!(
3090             "called `is_some()` after searching an `Iterator` with `{}`",
3091             search_method
3092         );
3093         let hint = "this is more succinctly expressed by calling `any()`";
3094         let search_snippet = snippet(cx, search_args[1].span, "..");
3095         if search_snippet.lines().count() <= 1 {
3096             // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
3097             // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
3098             let any_search_snippet = if_chain! {
3099                 if search_method == "find";
3100                 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
3101                 let closure_body = cx.tcx.hir().body(body_id);
3102                 if let Some(closure_arg) = closure_body.params.get(0);
3103                 then {
3104                     if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
3105                         Some(search_snippet.replacen('&', "", 1))
3106                     } else if let Some(name) = get_arg_name(&closure_arg.pat) {
3107                         Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
3108                     } else {
3109                         None
3110                     }
3111                 } else {
3112                     None
3113                 }
3114             };
3115             // add note if not multi-line
3116             span_lint_and_sugg(
3117                 cx,
3118                 SEARCH_IS_SOME,
3119                 method_span.with_hi(expr.span.hi()),
3120                 &msg,
3121                 "use `any()` instead",
3122                 format!(
3123                     "any({})",
3124                     any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
3125                 ),
3126                 Applicability::MachineApplicable,
3127             );
3128         } else {
3129             span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, hint);
3130         }
3131     }
3132     // lint if `find()` is called by `String` or `&str`
3133     else if search_method == "find" {
3134         let is_string_or_str_slice = |e| {
3135             let self_ty = cx.typeck_results().expr_ty(e).peel_refs();
3136             if is_type_diagnostic_item(cx, self_ty, sym!(string_type)) {
3137                 true
3138             } else {
3139                 *self_ty.kind() == ty::Str
3140             }
3141         };
3142         if_chain! {
3143             if is_string_or_str_slice(&search_args[0]);
3144             if is_string_or_str_slice(&search_args[1]);
3145             then {
3146                 let msg = "called `is_some()` after calling `find()` on a string";
3147                 let mut applicability = Applicability::MachineApplicable;
3148                 let find_arg = snippet_with_applicability(cx, search_args[1].span, "..", &mut applicability);
3149                 span_lint_and_sugg(
3150                     cx,
3151                     SEARCH_IS_SOME,
3152                     method_span.with_hi(expr.span.hi()),
3153                     msg,
3154                     "use `contains()` instead",
3155                     format!("contains({})", find_arg),
3156                     applicability,
3157                 );
3158             }
3159         }
3160     }
3161 }
3162
3163 /// Used for `lint_binary_expr_with_method_call`.
3164 #[derive(Copy, Clone)]
3165 struct BinaryExprInfo<'a> {
3166     expr: &'a hir::Expr<'a>,
3167     chain: &'a hir::Expr<'a>,
3168     other: &'a hir::Expr<'a>,
3169     eq: bool,
3170 }
3171
3172 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3173 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3174     macro_rules! lint_with_both_lhs_and_rhs {
3175         ($func:ident, $cx:expr, $info:ident) => {
3176             if !$func($cx, $info) {
3177                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3178                 if $func($cx, $info) {
3179                     return;
3180                 }
3181             }
3182         };
3183     }
3184
3185     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
3186     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
3187     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
3188     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
3189 }
3190
3191 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3192 fn lint_chars_cmp(
3193     cx: &LateContext<'_>,
3194     info: &BinaryExprInfo<'_>,
3195     chain_methods: &[&str],
3196     lint: &'static Lint,
3197     suggest: &str,
3198 ) -> bool {
3199     if_chain! {
3200         if let Some(args) = method_chain_args(info.chain, chain_methods);
3201         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
3202         if arg_char.len() == 1;
3203         if let hir::ExprKind::Path(ref qpath) = fun.kind;
3204         if let Some(segment) = single_segment_path(qpath);
3205         if segment.ident.name == sym::Some;
3206         then {
3207             let mut applicability = Applicability::MachineApplicable;
3208             let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
3209
3210             if *self_ty.kind() != ty::Str {
3211                 return false;
3212             }
3213
3214             span_lint_and_sugg(
3215                 cx,
3216                 lint,
3217                 info.expr.span,
3218                 &format!("you should use the `{}` method", suggest),
3219                 "like this",
3220                 format!("{}{}.{}({})",
3221                         if info.eq { "" } else { "!" },
3222                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3223                         suggest,
3224                         snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
3225                 applicability,
3226             );
3227
3228             return true;
3229         }
3230     }
3231
3232     false
3233 }
3234
3235 /// Checks for the `CHARS_NEXT_CMP` lint.
3236 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3237     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
3238 }
3239
3240 /// Checks for the `CHARS_LAST_CMP` lint.
3241 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3242     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
3243         true
3244     } else {
3245         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
3246     }
3247 }
3248
3249 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
3250 fn lint_chars_cmp_with_unwrap<'tcx>(
3251     cx: &LateContext<'tcx>,
3252     info: &BinaryExprInfo<'_>,
3253     chain_methods: &[&str],
3254     lint: &'static Lint,
3255     suggest: &str,
3256 ) -> bool {
3257     if_chain! {
3258         if let Some(args) = method_chain_args(info.chain, chain_methods);
3259         if let hir::ExprKind::Lit(ref lit) = info.other.kind;
3260         if let ast::LitKind::Char(c) = lit.node;
3261         then {
3262             let mut applicability = Applicability::MachineApplicable;
3263             span_lint_and_sugg(
3264                 cx,
3265                 lint,
3266                 info.expr.span,
3267                 &format!("you should use the `{}` method", suggest),
3268                 "like this",
3269                 format!("{}{}.{}('{}')",
3270                         if info.eq { "" } else { "!" },
3271                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3272                         suggest,
3273                         c),
3274                 applicability,
3275             );
3276
3277             true
3278         } else {
3279             false
3280         }
3281     }
3282 }
3283
3284 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3285 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3286     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3287 }
3288
3289 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3290 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3291     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3292         true
3293     } else {
3294         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3295     }
3296 }
3297
3298 fn get_hint_if_single_char_arg(
3299     cx: &LateContext<'_>,
3300     arg: &hir::Expr<'_>,
3301     applicability: &mut Applicability,
3302 ) -> Option<String> {
3303     if_chain! {
3304         if let hir::ExprKind::Lit(lit) = &arg.kind;
3305         if let ast::LitKind::Str(r, style) = lit.node;
3306         let string = r.as_str();
3307         if string.chars().count() == 1;
3308         then {
3309             let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
3310             let ch = if let ast::StrStyle::Raw(nhash) = style {
3311                 let nhash = nhash as usize;
3312                 // for raw string: r##"a"##
3313                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3314             } else {
3315                 // for regular string: "a"
3316                 &snip[1..(snip.len() - 1)]
3317             };
3318             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3319             Some(hint)
3320         } else {
3321             None
3322         }
3323     }
3324 }
3325
3326 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3327 fn lint_single_char_pattern(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
3328     let mut applicability = Applicability::MachineApplicable;
3329     if let Some(hint) = get_hint_if_single_char_arg(cx, arg, &mut applicability) {
3330         span_lint_and_sugg(
3331             cx,
3332             SINGLE_CHAR_PATTERN,
3333             arg.span,
3334             "single-character string constant used as pattern",
3335             "try using a `char` instead",
3336             hint,
3337             applicability,
3338         );
3339     }
3340 }
3341
3342 /// lint for length-1 `str`s as argument for `push_str`
3343 fn lint_single_char_push_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3344     let mut applicability = Applicability::MachineApplicable;
3345     if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[1], &mut applicability) {
3346         let base_string_snippet =
3347             snippet_with_applicability(cx, args[0].span.source_callsite(), "..", &mut applicability);
3348         let sugg = format!("{}.push({})", base_string_snippet, extension_string);
3349         span_lint_and_sugg(
3350             cx,
3351             SINGLE_CHAR_ADD_STR,
3352             expr.span,
3353             "calling `push_str()` using a single-character string literal",
3354             "consider using `push` with a character literal",
3355             sugg,
3356             applicability,
3357         );
3358     }
3359 }
3360
3361 /// lint for length-1 `str`s as argument for `insert_str`
3362 fn lint_single_char_insert_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3363     let mut applicability = Applicability::MachineApplicable;
3364     if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[2], &mut applicability) {
3365         let base_string_snippet =
3366             snippet_with_applicability(cx, args[0].span.source_callsite(), "_", &mut applicability);
3367         let pos_arg = snippet_with_applicability(cx, args[1].span, "..", &mut applicability);
3368         let sugg = format!("{}.insert({}, {})", base_string_snippet, pos_arg, extension_string);
3369         span_lint_and_sugg(
3370             cx,
3371             SINGLE_CHAR_ADD_STR,
3372             expr.span,
3373             "calling `insert_str()` using a single-character string literal",
3374             "consider using `insert` with a character literal",
3375             sugg,
3376             applicability,
3377         );
3378     }
3379 }
3380
3381 /// Checks for the `USELESS_ASREF` lint.
3382 fn lint_asref(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3383     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3384     // check if the call is to the actual `AsRef` or `AsMut` trait
3385     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3386         // check if the type after `as_ref` or `as_mut` is the same as before
3387         let recvr = &as_ref_args[0];
3388         let rcv_ty = cx.typeck_results().expr_ty(recvr);
3389         let res_ty = cx.typeck_results().expr_ty(expr);
3390         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3391         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3392         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3393             // allow the `as_ref` or `as_mut` if it is followed by another method call
3394             if_chain! {
3395                 if let Some(parent) = get_parent_expr(cx, expr);
3396                 if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
3397                 if span != &expr.span;
3398                 then {
3399                     return;
3400                 }
3401             }
3402
3403             let mut applicability = Applicability::MachineApplicable;
3404             span_lint_and_sugg(
3405                 cx,
3406                 USELESS_ASREF,
3407                 expr.span,
3408                 &format!("this call to `{}` does nothing", call_name),
3409                 "try this",
3410                 snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(),
3411                 applicability,
3412             );
3413         }
3414     }
3415 }
3416
3417 fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3418     has_iter_method(cx, self_ref_ty).map(|ty_name| {
3419         let mutbl = match self_ref_ty.kind() {
3420             ty::Ref(_, _, mutbl) => mutbl,
3421             _ => unreachable!(),
3422         };
3423         let method_name = match mutbl {
3424             hir::Mutability::Not => "iter",
3425             hir::Mutability::Mut => "iter_mut",
3426         };
3427         (ty_name, method_name)
3428     })
3429 }
3430
3431 fn lint_into_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3432     if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3433         return;
3434     }
3435     if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3436         span_lint_and_sugg(
3437             cx,
3438             INTO_ITER_ON_REF,
3439             method_span,
3440             &format!(
3441                 "this `.into_iter()` call is equivalent to `.{}()` and will not consume the `{}`",
3442                 method_name, kind,
3443             ),
3444             "call directly",
3445             method_name.to_string(),
3446             Applicability::MachineApplicable,
3447         );
3448     }
3449 }
3450
3451 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3452 fn lint_maybe_uninit(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3453     if_chain! {
3454         if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3455         if args.is_empty();
3456         if let hir::ExprKind::Path(ref path) = callee.kind;
3457         if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3458         if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer));
3459         then {
3460             span_lint(
3461                 cx,
3462                 UNINIT_ASSUMED_INIT,
3463                 outer.span,
3464                 "this call for this type may be undefined behavior"
3465             );
3466         }
3467     }
3468 }
3469
3470 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
3471     match ty.kind() {
3472         ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3473         ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3474         ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3475         _ => false,
3476     }
3477 }
3478
3479 fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
3480     span_lint_and_help(
3481         cx,
3482         SUSPICIOUS_MAP,
3483         expr.span,
3484         "this call to `map()` won't have an effect on the call to `count()`",
3485         None,
3486         "make sure you did not confuse `map` with `filter` or `for_each`",
3487     );
3488 }
3489
3490 const OPTION_AS_REF_DEREF_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
3491
3492 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3493 fn lint_option_as_ref_deref<'tcx>(
3494     cx: &LateContext<'tcx>,
3495     expr: &hir::Expr<'_>,
3496     as_ref_args: &[hir::Expr<'_>],
3497     map_args: &[hir::Expr<'_>],
3498     is_mut: bool,
3499     msrv: Option<&RustcVersion>,
3500 ) {
3501     if !meets_msrv(msrv, &OPTION_AS_REF_DEREF_MSRV) {
3502         return;
3503     }
3504
3505     let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3506
3507     let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]);
3508     if !is_type_diagnostic_item(cx, option_ty, sym::option_type) {
3509         return;
3510     }
3511
3512     let deref_aliases: [&[&str]; 9] = [
3513         &paths::DEREF_TRAIT_METHOD,
3514         &paths::DEREF_MUT_TRAIT_METHOD,
3515         &paths::CSTRING_AS_C_STR,
3516         &paths::OS_STRING_AS_OS_STR,
3517         &paths::PATH_BUF_AS_PATH,
3518         &paths::STRING_AS_STR,
3519         &paths::STRING_AS_MUT_STR,
3520         &paths::VEC_AS_SLICE,
3521         &paths::VEC_AS_MUT_SLICE,
3522     ];
3523
3524     let is_deref = match map_args[1].kind {
3525         hir::ExprKind::Path(ref expr_qpath) => cx
3526             .qpath_res(expr_qpath, map_args[1].hir_id)
3527             .opt_def_id()
3528             .map_or(false, |fun_def_id| {
3529                 deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
3530             }),
3531         hir::ExprKind::Closure(_, _, body_id, _, _) => {
3532             let closure_body = cx.tcx.hir().body(body_id);
3533             let closure_expr = remove_blocks(&closure_body.value);
3534
3535             match &closure_expr.kind {
3536                 hir::ExprKind::MethodCall(_, _, args, _) => {
3537                     if_chain! {
3538                         if args.len() == 1;
3539                         if let hir::ExprKind::Path(qpath) = &args[0].kind;
3540                         if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, args[0].hir_id);
3541                         if closure_body.params[0].pat.hir_id == local_id;
3542                         let adj = cx
3543                             .typeck_results()
3544                             .expr_adjustments(&args[0])
3545                             .iter()
3546                             .map(|x| &x.kind)
3547                             .collect::<Box<[_]>>();
3548                         if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3549                         then {
3550                             let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
3551                             deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3552                         } else {
3553                             false
3554                         }
3555                     }
3556                 },
3557                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3558                     if_chain! {
3559                         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind;
3560                         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind;
3561                         if let hir::ExprKind::Path(ref qpath) = inner2.kind;
3562                         if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, inner2.hir_id);
3563                         then {
3564                             closure_body.params[0].pat.hir_id == local_id
3565                         } else {
3566                             false
3567                         }
3568                     }
3569                 },
3570                 _ => false,
3571             }
3572         },
3573         _ => false,
3574     };
3575
3576     if is_deref {
3577         let current_method = if is_mut {
3578             format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3579         } else {
3580             format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3581         };
3582         let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3583         let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3584         let suggestion = format!("try using {} instead", method_hint);
3585
3586         let msg = format!(
3587             "called `{0}` on an Option value. This can be done more directly \
3588             by calling `{1}` instead",
3589             current_method, hint
3590         );
3591         span_lint_and_sugg(
3592             cx,
3593             OPTION_AS_REF_DEREF,
3594             expr.span,
3595             &msg,
3596             &suggestion,
3597             hint,
3598             Applicability::MachineApplicable,
3599         );
3600     }
3601 }
3602
3603 fn lint_map_collect(
3604     cx: &LateContext<'_>,
3605     expr: &hir::Expr<'_>,
3606     map_args: &[hir::Expr<'_>],
3607     collect_args: &[hir::Expr<'_>],
3608 ) {
3609     if_chain! {
3610         // called on Iterator
3611         if let [map_expr] = collect_args;
3612         if match_trait_method(cx, map_expr, &paths::ITERATOR);
3613         // return of collect `Result<(),_>`
3614         let collect_ret_ty = cx.typeck_results().expr_ty(expr);
3615         if is_type_diagnostic_item(cx, collect_ret_ty, sym::result_type);
3616         if let ty::Adt(_, substs) = collect_ret_ty.kind();
3617         if let Some(result_t) = substs.types().next();
3618         if result_t.is_unit();
3619         // get parts for snippet
3620         if let [iter, map_fn] = map_args;
3621         then {
3622             span_lint_and_sugg(
3623                 cx,
3624                 MAP_COLLECT_RESULT_UNIT,
3625                 expr.span,
3626                 "`.map().collect()` can be replaced with `.try_for_each()`",
3627                 "try this",
3628                 format!(
3629                     "{}.try_for_each({})",
3630                     snippet(cx, iter.span, ".."),
3631                     snippet(cx, map_fn.span, "..")
3632                 ),
3633                 Applicability::MachineApplicable,
3634             );
3635         }
3636     }
3637 }
3638
3639 /// Given a `Result<T, E>` type, return its error type (`E`).
3640 fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3641     match ty.kind() {
3642         ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::result_type) => substs.types().nth(1),
3643         _ => None,
3644     }
3645 }
3646
3647 /// This checks whether a given type is known to implement Debug.
3648 fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
3649     cx.tcx
3650         .get_diagnostic_item(sym::debug_trait)
3651         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3652 }
3653
3654 enum Convention {
3655     Eq(&'static str),
3656     StartsWith(&'static str),
3657 }
3658
3659 #[rustfmt::skip]
3660 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3661     (Convention::Eq("new"), &[SelfKind::No]),
3662     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3663     (Convention::StartsWith("from_"), &[SelfKind::No]),
3664     (Convention::StartsWith("into_"), &[SelfKind::Value]),
3665     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3666     (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3667     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3668 ];
3669
3670 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3671     unsafety: hir::Unsafety::Normal,
3672     constness: hir::Constness::NotConst,
3673     asyncness: hir::IsAsync::NotAsync,
3674     abi: rustc_target::spec::abi::Abi::Rust,
3675 };
3676
3677 struct ShouldImplTraitCase {
3678     trait_name: &'static str,
3679     method_name: &'static str,
3680     param_count: usize,
3681     fn_header: hir::FnHeader,
3682     // implicit self kind expected (none, self, &self, ...)
3683     self_kind: SelfKind,
3684     // checks against the output type
3685     output_type: OutType,
3686     // certain methods with explicit lifetimes can't implement the equivalent trait method
3687     lint_explicit_lifetime: bool,
3688 }
3689 impl ShouldImplTraitCase {
3690     const fn new(
3691         trait_name: &'static str,
3692         method_name: &'static str,
3693         param_count: usize,
3694         fn_header: hir::FnHeader,
3695         self_kind: SelfKind,
3696         output_type: OutType,
3697         lint_explicit_lifetime: bool,
3698     ) -> ShouldImplTraitCase {
3699         ShouldImplTraitCase {
3700             trait_name,
3701             method_name,
3702             param_count,
3703             fn_header,
3704             self_kind,
3705             output_type,
3706             lint_explicit_lifetime,
3707         }
3708     }
3709
3710     fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3711         self.lint_explicit_lifetime
3712             || !impl_item.generics.params.iter().any(|p| {
3713                 matches!(
3714                     p.kind,
3715                     hir::GenericParamKind::Lifetime {
3716                         kind: hir::LifetimeParamKind::Explicit
3717                     }
3718                 )
3719             })
3720     }
3721 }
3722
3723 #[rustfmt::skip]
3724 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3725     ShouldImplTraitCase::new("std::ops::Add", "add",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3726     ShouldImplTraitCase::new("std::convert::AsMut", "as_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3727     ShouldImplTraitCase::new("std::convert::AsRef", "as_ref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3728     ShouldImplTraitCase::new("std::ops::BitAnd", "bitand",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3729     ShouldImplTraitCase::new("std::ops::BitOr", "bitor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3730     ShouldImplTraitCase::new("std::ops::BitXor", "bitxor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3731     ShouldImplTraitCase::new("std::borrow::Borrow", "borrow",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3732     ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3733     ShouldImplTraitCase::new("std::clone::Clone", "clone",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
3734     ShouldImplTraitCase::new("std::cmp::Ord", "cmp",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
3735     // FIXME: default doesn't work
3736     ShouldImplTraitCase::new("std::default::Default", "default",  0,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3737     ShouldImplTraitCase::new("std::ops::Deref", "deref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3738     ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3739     ShouldImplTraitCase::new("std::ops::Div", "div",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3740     ShouldImplTraitCase::new("std::ops::Drop", "drop",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Unit, true),
3741     ShouldImplTraitCase::new("std::cmp::PartialEq", "eq",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Bool, true),
3742     ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3743     ShouldImplTraitCase::new("std::str::FromStr", "from_str",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
3744     ShouldImplTraitCase::new("std::hash::Hash", "hash",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Unit, true),
3745     ShouldImplTraitCase::new("std::ops::Index", "index",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
3746     ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut",  2,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
3747     ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3748     ShouldImplTraitCase::new("std::ops::Mul", "mul",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3749     ShouldImplTraitCase::new("std::ops::Neg", "neg",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3750     ShouldImplTraitCase::new("std::iter::Iterator", "next",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Any, false),
3751     ShouldImplTraitCase::new("std::ops::Not", "not",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3752     ShouldImplTraitCase::new("std::ops::Rem", "rem",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3753     ShouldImplTraitCase::new("std::ops::Shl", "shl",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3754     ShouldImplTraitCase::new("std::ops::Shr", "shr",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3755     ShouldImplTraitCase::new("std::ops::Sub", "sub",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
3756 ];
3757
3758 #[rustfmt::skip]
3759 const PATTERN_METHODS: [(&str, usize); 17] = [
3760     ("contains", 1),
3761     ("starts_with", 1),
3762     ("ends_with", 1),
3763     ("find", 1),
3764     ("rfind", 1),
3765     ("split", 1),
3766     ("rsplit", 1),
3767     ("split_terminator", 1),
3768     ("rsplit_terminator", 1),
3769     ("splitn", 2),
3770     ("rsplitn", 2),
3771     ("matches", 1),
3772     ("rmatches", 1),
3773     ("match_indices", 1),
3774     ("rmatch_indices", 1),
3775     ("trim_start_matches", 1),
3776     ("trim_end_matches", 1),
3777 ];
3778
3779 #[derive(Clone, Copy, PartialEq, Debug)]
3780 enum SelfKind {
3781     Value,
3782     Ref,
3783     RefMut,
3784     No,
3785 }
3786
3787 impl SelfKind {
3788     fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3789         fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3790             if ty == parent_ty {
3791                 true
3792             } else if ty.is_box() {
3793                 ty.boxed_ty() == parent_ty
3794             } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3795                 if let ty::Adt(_, substs) = ty.kind() {
3796                     substs.types().next().map_or(false, |t| t == parent_ty)
3797                 } else {
3798                     false
3799                 }
3800             } else {
3801                 false
3802             }
3803         }
3804
3805         fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3806             if let ty::Ref(_, t, m) = *ty.kind() {
3807                 return m == mutability && t == parent_ty;
3808             }
3809
3810             let trait_path = match mutability {
3811                 hir::Mutability::Not => &paths::ASREF_TRAIT,
3812                 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3813             };
3814
3815             let trait_def_id = match get_trait_def_id(cx, trait_path) {
3816                 Some(did) => did,
3817                 None => return false,
3818             };
3819             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3820         }
3821
3822         match self {
3823             Self::Value => matches_value(cx, parent_ty, ty),
3824             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3825             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3826             Self::No => ty != parent_ty,
3827         }
3828     }
3829
3830     #[must_use]
3831     fn description(self) -> &'static str {
3832         match self {
3833             Self::Value => "self by value",
3834             Self::Ref => "self by reference",
3835             Self::RefMut => "self by mutable reference",
3836             Self::No => "no self",
3837         }
3838     }
3839 }
3840
3841 impl Convention {
3842     #[must_use]
3843     fn check(&self, other: &str) -> bool {
3844         match *self {
3845             Self::Eq(this) => this == other,
3846             Self::StartsWith(this) => other.starts_with(this) && this != other,
3847         }
3848     }
3849 }
3850
3851 impl fmt::Display for Convention {
3852     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3853         match *self {
3854             Self::Eq(this) => this.fmt(f),
3855             Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3856         }
3857     }
3858 }
3859
3860 #[derive(Clone, Copy)]
3861 enum OutType {
3862     Unit,
3863     Bool,
3864     Any,
3865     Ref,
3866 }
3867
3868 impl OutType {
3869     fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
3870         let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3871         match (self, ty) {
3872             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3873             (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3874             (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3875             (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3876             (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3877             _ => false,
3878         }
3879     }
3880 }
3881
3882 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3883     if let hir::TyKind::Path(ref p) = ty.kind {
3884         match_qpath(p, &["bool"])
3885     } else {
3886         false
3887     }
3888 }
3889
3890 fn check_pointer_offset(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3891     if_chain! {
3892         if args.len() == 2;
3893         if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind();
3894         if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3895         if layout.is_zst();
3896         then {
3897             span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3898         }
3899     }
3900 }
3901
3902 fn lint_filetype_is_file(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3903     let ty = cx.typeck_results().expr_ty(&args[0]);
3904
3905     if !match_type(cx, ty, &paths::FILE_TYPE) {
3906         return;
3907     }
3908
3909     let span: Span;
3910     let verb: &str;
3911     let lint_unary: &str;
3912     let help_unary: &str;
3913     if_chain! {
3914         if let Some(parent) = get_parent_expr(cx, expr);
3915         if let hir::ExprKind::Unary(op, _) = parent.kind;
3916         if op == hir::UnOp::UnNot;
3917         then {
3918             lint_unary = "!";
3919             verb = "denies";
3920             help_unary = "";
3921             span = parent.span;
3922         } else {
3923             lint_unary = "";
3924             verb = "covers";
3925             help_unary = "!";
3926             span = expr.span;
3927         }
3928     }
3929     let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3930     let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3931     span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
3932 }
3933
3934 fn lint_from_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3935     let ty = cx.typeck_results().expr_ty(expr);
3936     let arg_ty = cx.typeck_results().expr_ty(&args[0]);
3937
3938     if_chain! {
3939         if let Some(from_iter_id) = get_trait_def_id(cx, &paths::FROM_ITERATOR);
3940         if let Some(iter_id) = get_trait_def_id(cx, &paths::ITERATOR);
3941
3942         if implements_trait(cx, ty, from_iter_id, &[]) && implements_trait(cx, arg_ty, iter_id, &[]);
3943         then {
3944             // `expr` implements `FromIterator` trait
3945             let iter_expr = snippet(cx, args[0].span, "..");
3946             span_lint_and_sugg(
3947                 cx,
3948                 FROM_ITER_INSTEAD_OF_COLLECT,
3949                 expr.span,
3950                 "usage of `FromIterator::from_iter`",
3951                 "use `.collect()` instead of `::from_iter()`",
3952                 format!("{}.collect()", iter_expr),
3953                 Applicability::MaybeIncorrect,
3954             );
3955         }
3956     }
3957 }
3958
3959 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3960     expected.constness == actual.constness
3961         && expected.unsafety == actual.unsafety
3962         && expected.asyncness == actual.asyncness
3963 }