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