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