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