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