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