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