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