]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
32b3b7f7947f695eca2b3d4df94c8cd64f238ddc
[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         // (path, fn_has_argument, methods, suffix)
1618         let know_types: &[(&[_], _, &[_], _)] = &[
1619             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1620             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1621             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1622             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1623         ];
1624
1625         if_chain! {
1626             if know_types.iter().any(|k| k.2.contains(&name));
1627
1628             let mut finder = FunCallFinder { cx: &cx, found: false };
1629             if { finder.visit_expr(&arg); finder.found };
1630             if !contains_return(&arg);
1631
1632             let self_ty = cx.tables.expr_ty(self_expr);
1633
1634             if let Some(&(_, fn_has_arguments, poss, suffix)) =
1635                 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1636
1637             if poss.contains(&name);
1638
1639             then {
1640                 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1641                     (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1642                     (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1643                     (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1644                 };
1645                 let span_replace_word = method_span.with_hi(span.hi());
1646                 span_lint_and_sugg(
1647                     cx,
1648                     OR_FUN_CALL,
1649                     span_replace_word,
1650                     &format!("use of `{}` followed by a function call", name),
1651                     "try this",
1652                     format!("{}_{}({})", name, suffix, sugg),
1653                     Applicability::HasPlaceholders,
1654                 );
1655             }
1656         }
1657     }
1658
1659     if args.len() == 2 {
1660         match args[1].kind {
1661             hir::ExprKind::Call(ref fun, ref or_args) => {
1662                 let or_has_args = !or_args.is_empty();
1663                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1664                     check_general_case(
1665                         cx,
1666                         name,
1667                         method_span,
1668                         fun.span,
1669                         &args[0],
1670                         &args[1],
1671                         or_has_args,
1672                         expr.span,
1673                     );
1674                 }
1675             },
1676             hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1677                 cx,
1678                 name,
1679                 method_span,
1680                 span,
1681                 &args[0],
1682                 &args[1],
1683                 !or_args.is_empty(),
1684                 expr.span,
1685             ),
1686             _ => {},
1687         }
1688     }
1689 }
1690
1691 /// Checks for the `EXPECT_FUN_CALL` lint.
1692 #[allow(clippy::too_many_lines)]
1693 fn lint_expect_fun_call(
1694     cx: &LateContext<'_, '_>,
1695     expr: &hir::Expr<'_>,
1696     method_span: Span,
1697     name: &str,
1698     args: &[hir::Expr<'_>],
1699 ) {
1700     // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1701     // `&str`
1702     fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1703         let mut arg_root = arg;
1704         loop {
1705             arg_root = match &arg_root.kind {
1706                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1707                 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1708                     if call_args.len() == 1
1709                         && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1710                         && {
1711                             let arg_type = cx.tables.expr_ty(&call_args[0]);
1712                             let base_type = walk_ptrs_ty(arg_type);
1713                             base_type.kind == ty::Str || is_type_diagnostic_item(cx, base_type, sym!(string_type))
1714                         }
1715                     {
1716                         &call_args[0]
1717                     } else {
1718                         break;
1719                     }
1720                 },
1721                 _ => break,
1722             };
1723         }
1724         arg_root
1725     }
1726
1727     // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1728     // converted to string.
1729     fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1730         let arg_ty = cx.tables.expr_ty(arg);
1731         if is_type_diagnostic_item(cx, arg_ty, sym!(string_type)) {
1732             return false;
1733         }
1734         if let ty::Ref(_, ty, ..) = arg_ty.kind {
1735             if ty.kind == ty::Str && can_be_static_str(cx, arg) {
1736                 return false;
1737             }
1738         };
1739         true
1740     }
1741
1742     // Check if an expression could have type `&'static str`, knowing that it
1743     // has type `&str` for some lifetime.
1744     fn can_be_static_str(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1745         match arg.kind {
1746             hir::ExprKind::Lit(_) => true,
1747             hir::ExprKind::Call(fun, _) => {
1748                 if let hir::ExprKind::Path(ref p) = fun.kind {
1749                     match cx.tables.qpath_res(p, fun.hir_id) {
1750                         hir::def::Res::Def(hir::def::DefKind::Fn, def_id)
1751                         | hir::def::Res::Def(hir::def::DefKind::AssocFn, def_id) => matches!(
1752                             cx.tcx.fn_sig(def_id).output().skip_binder().kind,
1753                             ty::Ref(ty::ReStatic, ..)
1754                         ),
1755                         _ => false,
1756                     }
1757                 } else {
1758                     false
1759                 }
1760             },
1761             hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(arg.hir_id).map_or(false, |method_id| {
1762                 matches!(
1763                     cx.tcx.fn_sig(method_id).output().skip_binder().kind,
1764                     ty::Ref(ty::ReStatic, ..)
1765                 )
1766             }),
1767             hir::ExprKind::Path(ref p) => match cx.tables.qpath_res(p, arg.hir_id) {
1768                 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _) => true,
1769                 _ => false,
1770             },
1771             _ => false,
1772         }
1773     }
1774
1775     fn generate_format_arg_snippet(
1776         cx: &LateContext<'_, '_>,
1777         a: &hir::Expr<'_>,
1778         applicability: &mut Applicability,
1779     ) -> Vec<String> {
1780         if_chain! {
1781             if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1782             if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1783             if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1784
1785             then {
1786                 format_arg_expr_tup
1787                     .iter()
1788                     .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1789                     .collect()
1790             } else {
1791                 unreachable!()
1792             }
1793         }
1794     }
1795
1796     fn is_call(node: &hir::ExprKind<'_>) -> bool {
1797         match node {
1798             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1799                 is_call(&expr.kind)
1800             },
1801             hir::ExprKind::Call(..)
1802             | hir::ExprKind::MethodCall(..)
1803             // These variants are debatable or require further examination
1804             | hir::ExprKind::Match(..)
1805             | hir::ExprKind::Block{ .. } => true,
1806             _ => false,
1807         }
1808     }
1809
1810     if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1811         return;
1812     }
1813
1814     let receiver_type = cx.tables.expr_ty_adjusted(&args[0]);
1815     let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym!(option_type)) {
1816         "||"
1817     } else if is_type_diagnostic_item(cx, receiver_type, sym!(result_type)) {
1818         "|_|"
1819     } else {
1820         return;
1821     };
1822
1823     let arg_root = get_arg_root(cx, &args[1]);
1824
1825     let span_replace_word = method_span.with_hi(expr.span.hi());
1826
1827     let mut applicability = Applicability::MachineApplicable;
1828
1829     //Special handling for `format!` as arg_root
1830     if_chain! {
1831         if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1832         if block.stmts.len() == 1;
1833         if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1834         if let Some(arg_root) = &local.init;
1835         if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1836         if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
1837         if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
1838         then {
1839             let fmt_spec = &format_args[0];
1840             let fmt_args = &format_args[1];
1841
1842             let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1843
1844             args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1845
1846             let sugg = args.join(", ");
1847
1848             span_lint_and_sugg(
1849                 cx,
1850                 EXPECT_FUN_CALL,
1851                 span_replace_word,
1852                 &format!("use of `{}` followed by a function call", name),
1853                 "try this",
1854                 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1855                 applicability,
1856             );
1857
1858             return;
1859         }
1860     }
1861
1862     let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1863     if requires_to_string(cx, arg_root) {
1864         arg_root_snippet.to_mut().push_str(".to_string()");
1865     }
1866
1867     span_lint_and_sugg(
1868         cx,
1869         EXPECT_FUN_CALL,
1870         span_replace_word,
1871         &format!("use of `{}` followed by a function call", name),
1872         "try this",
1873         format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1874         applicability,
1875     );
1876 }
1877
1878 /// Checks for the `CLONE_ON_COPY` lint.
1879 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
1880     let ty = cx.tables.expr_ty(expr);
1881     if let ty::Ref(_, inner, _) = arg_ty.kind {
1882         if let ty::Ref(_, innermost, _) = inner.kind {
1883             span_lint_and_then(
1884                 cx,
1885                 CLONE_DOUBLE_REF,
1886                 expr.span,
1887                 "using `clone` on a double-reference; \
1888                 this will copy the reference instead of cloning the inner type",
1889                 |diag| {
1890                     if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1891                         let mut ty = innermost;
1892                         let mut n = 0;
1893                         while let ty::Ref(_, inner, _) = ty.kind {
1894                             ty = inner;
1895                             n += 1;
1896                         }
1897                         let refs: String = iter::repeat('&').take(n + 1).collect();
1898                         let derefs: String = iter::repeat('*').take(n).collect();
1899                         let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
1900                         diag.span_suggestion(
1901                             expr.span,
1902                             "try dereferencing it",
1903                             format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1904                             Applicability::MaybeIncorrect,
1905                         );
1906                         diag.span_suggestion(
1907                             expr.span,
1908                             "or try being explicit if you are sure, that you want to clone a reference",
1909                             explicit,
1910                             Applicability::MaybeIncorrect,
1911                         );
1912                     }
1913                 },
1914             );
1915             return; // don't report clone_on_copy
1916         }
1917     }
1918
1919     if is_copy(cx, ty) {
1920         let snip;
1921         if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1922             let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1923             match &cx.tcx.hir().get(parent) {
1924                 hir::Node::Expr(parent) => match parent.kind {
1925                     // &*x is a nop, &x.clone() is not
1926                     hir::ExprKind::AddrOf(..) => return,
1927                     // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1928                     hir::ExprKind::MethodCall(_, _, parent_args) if expr.hir_id == parent_args[0].hir_id => return,
1929
1930                     _ => {},
1931                 },
1932                 hir::Node::Stmt(stmt) => {
1933                     if let hir::StmtKind::Local(ref loc) = stmt.kind {
1934                         if let hir::PatKind::Ref(..) = loc.pat.kind {
1935                             // let ref y = *x borrows x, let ref y = x.clone() does not
1936                             return;
1937                         }
1938                     }
1939                 },
1940                 _ => {},
1941             }
1942
1943             // x.clone() might have dereferenced x, possibly through Deref impls
1944             if cx.tables.expr_ty(arg) == ty {
1945                 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1946             } else {
1947                 let deref_count = cx
1948                     .tables
1949                     .expr_adjustments(arg)
1950                     .iter()
1951                     .filter(|adj| {
1952                         if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1953                             true
1954                         } else {
1955                             false
1956                         }
1957                     })
1958                     .count();
1959                 let derefs: String = iter::repeat('*').take(deref_count).collect();
1960                 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1961             }
1962         } else {
1963             snip = None;
1964         }
1965         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |diag| {
1966             if let Some((text, snip)) = snip {
1967                 diag.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1968             }
1969         });
1970     }
1971 }
1972
1973 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
1974     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1975
1976     if let ty::Adt(_, subst) = obj_ty.kind {
1977         let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
1978             "Rc"
1979         } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
1980             "Arc"
1981         } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1982             "Weak"
1983         } else {
1984             return;
1985         };
1986
1987         span_lint_and_sugg(
1988             cx,
1989             CLONE_ON_REF_PTR,
1990             expr.span,
1991             "using `.clone()` on a ref-counted pointer",
1992             "try this",
1993             format!(
1994                 "{}::<{}>::clone(&{})",
1995                 caller_type,
1996                 subst.type_at(0),
1997                 snippet(cx, arg.span, "_")
1998             ),
1999             Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2000         );
2001     }
2002 }
2003
2004 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2005     let arg = &args[1];
2006     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2007         let target = &arglists[0][0];
2008         let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
2009         let ref_str = if self_ty.kind == ty::Str {
2010             ""
2011         } else if is_type_diagnostic_item(cx, self_ty, sym!(string_type)) {
2012             "&"
2013         } else {
2014             return;
2015         };
2016
2017         let mut applicability = Applicability::MachineApplicable;
2018         span_lint_and_sugg(
2019             cx,
2020             STRING_EXTEND_CHARS,
2021             expr.span,
2022             "calling `.extend(_.chars())`",
2023             "try this",
2024             format!(
2025                 "{}.push_str({}{})",
2026                 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
2027                 ref_str,
2028                 snippet_with_applicability(cx, target.span, "_", &mut applicability)
2029             ),
2030             applicability,
2031         );
2032     }
2033 }
2034
2035 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2036     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
2037     if is_type_diagnostic_item(cx, obj_ty, sym!(string_type)) {
2038         lint_string_extend(cx, expr, args);
2039     }
2040 }
2041
2042 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2043     if_chain! {
2044         let source_type = cx.tables.expr_ty(source);
2045         if let ty::Adt(def, substs) = source_type.kind;
2046         if cx.tcx.is_diagnostic_item(sym!(result_type), def.did);
2047         if match_type(cx, substs.type_at(0), &paths::CSTRING);
2048         then {
2049             span_lint_and_then(
2050                 cx,
2051                 TEMPORARY_CSTRING_AS_PTR,
2052                 expr.span,
2053                 "you are getting the inner pointer of a temporary `CString`",
2054                 |diag| {
2055                     diag.note("that pointer will be invalid outside this expression");
2056                     diag.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2057                 });
2058         }
2059     }
2060 }
2061
2062 fn lint_iter_cloned_collect<'a, 'tcx>(
2063     cx: &LateContext<'a, 'tcx>,
2064     expr: &hir::Expr<'_>,
2065     iter_args: &'tcx [hir::Expr<'_>],
2066 ) {
2067     if_chain! {
2068         if is_type_diagnostic_item(cx, cx.tables.expr_ty(expr), sym!(vec_type));
2069         if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0]));
2070         if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2071
2072         then {
2073             span_lint_and_sugg(
2074                 cx,
2075                 ITER_CLONED_COLLECT,
2076                 to_replace,
2077                 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2078                 more readable",
2079                 "try",
2080                 ".to_vec()".to_string(),
2081                 Applicability::MachineApplicable,
2082             );
2083         }
2084     }
2085 }
2086
2087 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2088     fn check_fold_with_op(
2089         cx: &LateContext<'_, '_>,
2090         expr: &hir::Expr<'_>,
2091         fold_args: &[hir::Expr<'_>],
2092         fold_span: Span,
2093         op: hir::BinOpKind,
2094         replacement_method_name: &str,
2095         replacement_has_args: bool,
2096     ) {
2097         if_chain! {
2098             // Extract the body of the closure passed to fold
2099             if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2100             let closure_body = cx.tcx.hir().body(body_id);
2101             let closure_expr = remove_blocks(&closure_body.value);
2102
2103             // Check if the closure body is of the form `acc <op> some_expr(x)`
2104             if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2105             if bin_op.node == op;
2106
2107             // Extract the names of the two arguments to the closure
2108             if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2109             if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2110
2111             if match_var(&*left_expr, first_arg_ident);
2112             if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2113
2114             then {
2115                 let mut applicability = Applicability::MachineApplicable;
2116                 let sugg = if replacement_has_args {
2117                     format!(
2118                         "{replacement}(|{s}| {r})",
2119                         replacement = replacement_method_name,
2120                         s = second_arg_ident,
2121                         r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2122                     )
2123                 } else {
2124                     format!(
2125                         "{replacement}()",
2126                         replacement = replacement_method_name,
2127                     )
2128                 };
2129
2130                 span_lint_and_sugg(
2131                     cx,
2132                     UNNECESSARY_FOLD,
2133                     fold_span.with_hi(expr.span.hi()),
2134                     // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2135                     "this `.fold` can be written more succinctly using another method",
2136                     "try",
2137                     sugg,
2138                     applicability,
2139                 );
2140             }
2141         }
2142     }
2143
2144     // Check that this is a call to Iterator::fold rather than just some function called fold
2145     if !match_trait_method(cx, expr, &paths::ITERATOR) {
2146         return;
2147     }
2148
2149     assert!(
2150         fold_args.len() == 3,
2151         "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2152     );
2153
2154     // Check if the first argument to .fold is a suitable literal
2155     if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2156         match lit.node {
2157             ast::LitKind::Bool(false) => {
2158                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2159             },
2160             ast::LitKind::Bool(true) => {
2161                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2162             },
2163             ast::LitKind::Int(0, _) => {
2164                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2165             },
2166             ast::LitKind::Int(1, _) => {
2167                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2168             },
2169             _ => (),
2170         }
2171     }
2172 }
2173
2174 fn lint_step_by<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2175     if match_trait_method(cx, expr, &paths::ITERATOR) {
2176         if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
2177             span_lint(
2178                 cx,
2179                 ITERATOR_STEP_BY_ZERO,
2180                 expr.span,
2181                 "Iterator::step_by(0) will panic at runtime",
2182             );
2183         }
2184     }
2185 }
2186
2187 fn lint_iter_nth<'a, 'tcx>(
2188     cx: &LateContext<'a, 'tcx>,
2189     expr: &hir::Expr<'_>,
2190     nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2191     is_mut: bool,
2192 ) {
2193     let iter_args = nth_and_iter_args[1];
2194     let mut_str = if is_mut { "_mut" } else { "" };
2195     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
2196         "slice"
2197     } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), sym!(vec_type)) {
2198         "Vec"
2199     } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
2200         "VecDeque"
2201     } else {
2202         let nth_args = nth_and_iter_args[0];
2203         lint_iter_nth_zero(cx, expr, &nth_args);
2204         return; // caller is not a type that we want to lint
2205     };
2206
2207     span_lint_and_help(
2208         cx,
2209         ITER_NTH,
2210         expr.span,
2211         &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2212         None,
2213         &format!("calling `.get{}()` is both faster and more readable", mut_str),
2214     );
2215 }
2216
2217 fn lint_iter_nth_zero<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2218     if_chain! {
2219         if match_trait_method(cx, expr, &paths::ITERATOR);
2220         if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &nth_args[1]);
2221         then {
2222             let mut applicability = Applicability::MachineApplicable;
2223             span_lint_and_sugg(
2224                 cx,
2225                 ITER_NTH_ZERO,
2226                 expr.span,
2227                 "called `.nth(0)` on a `std::iter::Iterator`",
2228                 "try calling",
2229                 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2230                 applicability,
2231             );
2232         }
2233     }
2234 }
2235
2236 fn lint_get_unwrap<'a, 'tcx>(
2237     cx: &LateContext<'a, 'tcx>,
2238     expr: &hir::Expr<'_>,
2239     get_args: &'tcx [hir::Expr<'_>],
2240     is_mut: bool,
2241 ) {
2242     // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2243     // because they do not implement `IndexMut`
2244     let mut applicability = Applicability::MachineApplicable;
2245     let expr_ty = cx.tables.expr_ty(&get_args[0]);
2246     let get_args_str = if get_args.len() > 1 {
2247         snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
2248     } else {
2249         return; // not linting on a .get().unwrap() chain or variant
2250     };
2251     let mut needs_ref;
2252     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2253         needs_ref = get_args_str.parse::<usize>().is_ok();
2254         "slice"
2255     } else if is_type_diagnostic_item(cx, expr_ty, sym!(vec_type)) {
2256         needs_ref = get_args_str.parse::<usize>().is_ok();
2257         "Vec"
2258     } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
2259         needs_ref = get_args_str.parse::<usize>().is_ok();
2260         "VecDeque"
2261     } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
2262         needs_ref = true;
2263         "HashMap"
2264     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2265         needs_ref = true;
2266         "BTreeMap"
2267     } else {
2268         return; // caller is not a type that we want to lint
2269     };
2270
2271     let mut span = expr.span;
2272
2273     // Handle the case where the result is immediately dereferenced
2274     // by not requiring ref and pulling the dereference into the
2275     // suggestion.
2276     if_chain! {
2277         if needs_ref;
2278         if let Some(parent) = get_parent_expr(cx, expr);
2279         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2280         then {
2281             needs_ref = false;
2282             span = parent.span;
2283         }
2284     }
2285
2286     let mut_str = if is_mut { "_mut" } else { "" };
2287     let borrow_str = if !needs_ref {
2288         ""
2289     } else if is_mut {
2290         "&mut "
2291     } else {
2292         "&"
2293     };
2294
2295     span_lint_and_sugg(
2296         cx,
2297         GET_UNWRAP,
2298         span,
2299         &format!(
2300             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2301             mut_str, caller_type
2302         ),
2303         "try this",
2304         format!(
2305             "{}{}[{}]",
2306             borrow_str,
2307             snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
2308             get_args_str
2309         ),
2310         applicability,
2311     );
2312 }
2313
2314 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
2315     // lint if caller of skip is an Iterator
2316     if match_trait_method(cx, expr, &paths::ITERATOR) {
2317         span_lint_and_help(
2318             cx,
2319             ITER_SKIP_NEXT,
2320             expr.span,
2321             "called `skip(x).next()` on an iterator",
2322             None,
2323             "this is more succinctly expressed by calling `nth(x)`",
2324         );
2325     }
2326 }
2327
2328 fn derefs_to_slice<'a, 'tcx>(
2329     cx: &LateContext<'a, 'tcx>,
2330     expr: &'tcx hir::Expr<'tcx>,
2331     ty: Ty<'tcx>,
2332 ) -> Option<&'tcx hir::Expr<'tcx>> {
2333     fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
2334         match ty.kind {
2335             ty::Slice(_) => true,
2336             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2337             ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym!(vec_type)),
2338             ty::Array(_, size) => {
2339                 if let Some(size) = size.try_eval_usize(cx.tcx, cx.param_env) {
2340                     size < 32
2341                 } else {
2342                     false
2343                 }
2344             },
2345             ty::Ref(_, inner, _) => may_slice(cx, inner),
2346             _ => false,
2347         }
2348     }
2349
2350     if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
2351         if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
2352             Some(&args[0])
2353         } else {
2354             None
2355         }
2356     } else {
2357         match ty.kind {
2358             ty::Slice(_) => Some(expr),
2359             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2360             ty::Ref(_, inner, _) => {
2361                 if may_slice(cx, inner) {
2362                     Some(expr)
2363                 } else {
2364                     None
2365                 }
2366             },
2367             _ => None,
2368         }
2369     }
2370 }
2371
2372 /// lint use of `unwrap()` for `Option`s and `Result`s
2373 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2374     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
2375
2376     let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2377         Some((UNWRAP_USED, "an Option", "None"))
2378     } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2379         Some((UNWRAP_USED, "a Result", "Err"))
2380     } else {
2381         None
2382     };
2383
2384     if let Some((lint, kind, none_value)) = mess {
2385         span_lint_and_help(
2386             cx,
2387             lint,
2388             expr.span,
2389             &format!("used `unwrap()` on `{}` value", kind,),
2390             None,
2391             &format!(
2392                 "if you don't want to handle the `{}` case gracefully, consider \
2393                 using `expect()` to provide a better panic message",
2394                 none_value,
2395             ),
2396         );
2397     }
2398 }
2399
2400 /// lint use of `expect()` for `Option`s and `Result`s
2401 fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2402     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&expect_args[0]));
2403
2404     let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2405         Some((EXPECT_USED, "an Option", "None"))
2406     } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2407         Some((EXPECT_USED, "a Result", "Err"))
2408     } else {
2409         None
2410     };
2411
2412     if let Some((lint, kind, none_value)) = mess {
2413         span_lint_and_help(
2414             cx,
2415             lint,
2416             expr.span,
2417             &format!("used `expect()` on `{}` value", kind,),
2418             None,
2419             &format!("if this value is an `{}`, it will panic", none_value,),
2420         );
2421     }
2422 }
2423
2424 /// lint use of `ok().expect()` for `Result`s
2425 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2426     if_chain! {
2427         // lint if the caller of `ok()` is a `Result`
2428         if is_type_diagnostic_item(cx, cx.tables.expr_ty(&ok_args[0]), sym!(result_type));
2429         let result_type = cx.tables.expr_ty(&ok_args[0]);
2430         if let Some(error_type) = get_error_type(cx, result_type);
2431         if has_debug_impl(error_type, cx);
2432
2433         then {
2434             span_lint_and_help(
2435                 cx,
2436                 OK_EXPECT,
2437                 expr.span,
2438                 "called `ok().expect()` on a `Result` value",
2439                 None,
2440                 "you can call `expect()` directly on the `Result`",
2441             );
2442         }
2443     }
2444 }
2445
2446 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2447 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2448     // lint if caller of `.map().flatten()` is an Iterator
2449     if match_trait_method(cx, expr, &paths::ITERATOR) {
2450         let msg = "called `map(..).flatten()` on an `Iterator`. \
2451                     This is more succinctly expressed by calling `.flat_map(..)`";
2452         let self_snippet = snippet(cx, map_args[0].span, "..");
2453         let func_snippet = snippet(cx, map_args[1].span, "..");
2454         let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
2455         span_lint_and_sugg(
2456             cx,
2457             MAP_FLATTEN,
2458             expr.span,
2459             msg,
2460             "try using `flat_map` instead",
2461             hint,
2462             Applicability::MachineApplicable,
2463         );
2464     }
2465
2466     // lint if caller of `.map().flatten()` is an Option
2467     if is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_args[0]), sym!(option_type)) {
2468         let msg = "called `map(..).flatten()` on an `Option`. \
2469                     This is more succinctly expressed by calling `.and_then(..)`";
2470         let self_snippet = snippet(cx, map_args[0].span, "..");
2471         let func_snippet = snippet(cx, map_args[1].span, "..");
2472         let hint = format!("{0}.and_then({1})", self_snippet, func_snippet);
2473         span_lint_and_sugg(
2474             cx,
2475             MAP_FLATTEN,
2476             expr.span,
2477             msg,
2478             "try using `and_then` instead",
2479             hint,
2480             Applicability::MachineApplicable,
2481         );
2482     }
2483 }
2484
2485 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2486 fn lint_map_unwrap_or_else<'a, 'tcx>(
2487     cx: &LateContext<'a, 'tcx>,
2488     expr: &'tcx hir::Expr<'_>,
2489     map_args: &'tcx [hir::Expr<'_>],
2490     unwrap_args: &'tcx [hir::Expr<'_>],
2491 ) {
2492     // lint if the caller of `map()` is an `Option`
2493     let is_option = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_args[0]), sym!(option_type));
2494     let is_result = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_args[0]), sym!(result_type));
2495
2496     if is_option || is_result {
2497         // Don't make a suggestion that may fail to compile due to mutably borrowing
2498         // the same variable twice.
2499         let map_mutated_vars = mutated_variables(&map_args[0], cx);
2500         let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2501         if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2502             if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2503                 return;
2504             }
2505         } else {
2506             return;
2507         }
2508
2509         // lint message
2510         let msg = if is_option {
2511             "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
2512             `map_or_else(g, f)` instead"
2513         } else {
2514             "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
2515             `.map_or_else(g, f)` instead"
2516         };
2517         // get snippets for args to map() and unwrap_or_else()
2518         let map_snippet = snippet(cx, map_args[1].span, "..");
2519         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2520         // lint, with note if neither arg is > 1 line and both map() and
2521         // unwrap_or_else() have the same span
2522         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2523         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2524         if same_span && !multiline {
2525             span_lint_and_note(
2526                 cx,
2527                 MAP_UNWRAP_OR,
2528                 expr.span,
2529                 msg,
2530                 None,
2531                 &format!(
2532                     "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
2533                     map_snippet, unwrap_snippet,
2534                 ),
2535             );
2536         } else if same_span && multiline {
2537             span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2538         };
2539     }
2540 }
2541
2542 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
2543 fn lint_map_or_none<'a, 'tcx>(
2544     cx: &LateContext<'a, 'tcx>,
2545     expr: &'tcx hir::Expr<'_>,
2546     map_or_args: &'tcx [hir::Expr<'_>],
2547 ) {
2548     let is_option = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_or_args[0]), sym!(option_type));
2549     let is_result = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_or_args[0]), sym!(result_type));
2550
2551     // There are two variants of this `map_or` lint:
2552     // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
2553     // (2) using `map_or` as a combinator instead of `and_then`
2554     //
2555     // (For this lint) we don't care if any other type calls `map_or`
2556     if !is_option && !is_result {
2557         return;
2558     }
2559
2560     let (lint_name, msg, instead, hint) = {
2561         let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2562             match_qpath(qpath, &paths::OPTION_NONE)
2563         } else {
2564             return;
2565         };
2566
2567         if !default_arg_is_none {
2568             // nothing to lint!
2569             return;
2570         }
2571
2572         let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
2573             match_qpath(qpath, &paths::OPTION_SOME)
2574         } else {
2575             false
2576         };
2577
2578         if is_option {
2579             let self_snippet = snippet(cx, map_or_args[0].span, "..");
2580             let func_snippet = snippet(cx, map_or_args[2].span, "..");
2581             let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
2582                        `and_then(f)` instead";
2583             (
2584                 OPTION_MAP_OR_NONE,
2585                 msg,
2586                 "try using `and_then` instead",
2587                 format!("{0}.and_then({1})", self_snippet, func_snippet),
2588             )
2589         } else if f_arg_is_some {
2590             let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
2591                        `ok()` instead";
2592             let self_snippet = snippet(cx, map_or_args[0].span, "..");
2593             (
2594                 RESULT_MAP_OR_INTO_OPTION,
2595                 msg,
2596                 "try using `ok` instead",
2597                 format!("{0}.ok()", self_snippet),
2598             )
2599         } else {
2600             // nothing to lint!
2601             return;
2602         }
2603     };
2604
2605     span_lint_and_sugg(
2606         cx,
2607         lint_name,
2608         expr.span,
2609         msg,
2610         instead,
2611         hint,
2612         Applicability::MachineApplicable,
2613     );
2614 }
2615
2616 /// lint use of `filter().next()` for `Iterators`
2617 fn lint_filter_next<'a, 'tcx>(
2618     cx: &LateContext<'a, 'tcx>,
2619     expr: &'tcx hir::Expr<'_>,
2620     filter_args: &'tcx [hir::Expr<'_>],
2621 ) {
2622     // lint if caller of `.filter().next()` is an Iterator
2623     if match_trait_method(cx, expr, &paths::ITERATOR) {
2624         let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2625                    `.find(p)` instead.";
2626         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2627         if filter_snippet.lines().count() <= 1 {
2628             // add note if not multi-line
2629             span_lint_and_note(
2630                 cx,
2631                 FILTER_NEXT,
2632                 expr.span,
2633                 msg,
2634                 None,
2635                 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2636             );
2637         } else {
2638             span_lint(cx, FILTER_NEXT, expr.span, msg);
2639         }
2640     }
2641 }
2642
2643 /// lint use of `skip_while().next()` for `Iterators`
2644 fn lint_skip_while_next<'a, 'tcx>(
2645     cx: &LateContext<'a, 'tcx>,
2646     expr: &'tcx hir::Expr<'_>,
2647     _skip_while_args: &'tcx [hir::Expr<'_>],
2648 ) {
2649     // lint if caller of `.skip_while().next()` is an Iterator
2650     if match_trait_method(cx, expr, &paths::ITERATOR) {
2651         span_lint_and_help(
2652             cx,
2653             SKIP_WHILE_NEXT,
2654             expr.span,
2655             "called `skip_while(p).next()` on an `Iterator`",
2656             None,
2657             "this is more succinctly expressed by calling `.find(!p)` instead",
2658         );
2659     }
2660 }
2661
2662 /// lint use of `filter().map()` for `Iterators`
2663 fn lint_filter_map<'a, 'tcx>(
2664     cx: &LateContext<'a, 'tcx>,
2665     expr: &'tcx hir::Expr<'_>,
2666     _filter_args: &'tcx [hir::Expr<'_>],
2667     _map_args: &'tcx [hir::Expr<'_>],
2668 ) {
2669     // lint if caller of `.filter().map()` is an Iterator
2670     if match_trait_method(cx, expr, &paths::ITERATOR) {
2671         let msg = "called `filter(p).map(q)` on an `Iterator`";
2672         let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2673         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2674     }
2675 }
2676
2677 /// lint use of `filter_map().next()` for `Iterators`
2678 fn lint_filter_map_next<'a, 'tcx>(
2679     cx: &LateContext<'a, 'tcx>,
2680     expr: &'tcx hir::Expr<'_>,
2681     filter_args: &'tcx [hir::Expr<'_>],
2682 ) {
2683     if match_trait_method(cx, expr, &paths::ITERATOR) {
2684         let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2685                    `.find_map(p)` instead.";
2686         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2687         if filter_snippet.lines().count() <= 1 {
2688             span_lint_and_note(
2689                 cx,
2690                 FILTER_MAP_NEXT,
2691                 expr.span,
2692                 msg,
2693                 None,
2694                 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2695             );
2696         } else {
2697             span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2698         }
2699     }
2700 }
2701
2702 /// lint use of `find().map()` for `Iterators`
2703 fn lint_find_map<'a, 'tcx>(
2704     cx: &LateContext<'a, 'tcx>,
2705     expr: &'tcx hir::Expr<'_>,
2706     _find_args: &'tcx [hir::Expr<'_>],
2707     map_args: &'tcx [hir::Expr<'_>],
2708 ) {
2709     // lint if caller of `.filter().map()` is an Iterator
2710     if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2711         let msg = "called `find(p).map(q)` on an `Iterator`";
2712         let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2713         span_lint_and_help(cx, FIND_MAP, expr.span, msg, None, hint);
2714     }
2715 }
2716
2717 /// lint use of `filter_map().map()` for `Iterators`
2718 fn lint_filter_map_map<'a, 'tcx>(
2719     cx: &LateContext<'a, 'tcx>,
2720     expr: &'tcx hir::Expr<'_>,
2721     _filter_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, expr, &paths::ITERATOR) {
2726         let msg = "called `filter_map(p).map(q)` on an `Iterator`";
2727         let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2728         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2729     }
2730 }
2731
2732 /// lint use of `filter().flat_map()` for `Iterators`
2733 fn lint_filter_flat_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().flat_map()` is an Iterator
2740     if match_trait_method(cx, expr, &paths::ITERATOR) {
2741         let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
2742         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2743                     and filtering by returning `iter::empty()`";
2744         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2745     }
2746 }
2747
2748 /// lint use of `filter_map().flat_map()` for `Iterators`
2749 fn lint_filter_map_flat_map<'a, 'tcx>(
2750     cx: &LateContext<'a, 'tcx>,
2751     expr: &'tcx hir::Expr<'_>,
2752     _filter_args: &'tcx [hir::Expr<'_>],
2753     _map_args: &'tcx [hir::Expr<'_>],
2754 ) {
2755     // lint if caller of `.filter_map().flat_map()` is an Iterator
2756     if match_trait_method(cx, expr, &paths::ITERATOR) {
2757         let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
2758         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2759                     and filtering by returning `iter::empty()`";
2760         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2761     }
2762 }
2763
2764 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2765 fn lint_flat_map_identity<'a, 'tcx>(
2766     cx: &LateContext<'a, 'tcx>,
2767     expr: &'tcx hir::Expr<'_>,
2768     flat_map_args: &'tcx [hir::Expr<'_>],
2769     flat_map_span: Span,
2770 ) {
2771     if match_trait_method(cx, expr, &paths::ITERATOR) {
2772         let arg_node = &flat_map_args[1].kind;
2773
2774         let apply_lint = |message: &str| {
2775             span_lint_and_sugg(
2776                 cx,
2777                 FLAT_MAP_IDENTITY,
2778                 flat_map_span.with_hi(expr.span.hi()),
2779                 message,
2780                 "try",
2781                 "flatten()".to_string(),
2782                 Applicability::MachineApplicable,
2783             );
2784         };
2785
2786         if_chain! {
2787             if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2788             let body = cx.tcx.hir().body(*body_id);
2789
2790             if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2791             if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2792
2793             if path.segments.len() == 1;
2794             if path.segments[0].ident.as_str() == binding_ident.as_str();
2795
2796             then {
2797                 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2798             }
2799         }
2800
2801         if_chain! {
2802             if let hir::ExprKind::Path(ref qpath) = arg_node;
2803
2804             if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2805
2806             then {
2807                 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
2808             }
2809         }
2810     }
2811 }
2812
2813 /// lint searching an Iterator followed by `is_some()`
2814 fn lint_search_is_some<'a, 'tcx>(
2815     cx: &LateContext<'a, 'tcx>,
2816     expr: &'tcx hir::Expr<'_>,
2817     search_method: &str,
2818     search_args: &'tcx [hir::Expr<'_>],
2819     is_some_args: &'tcx [hir::Expr<'_>],
2820     method_span: Span,
2821 ) {
2822     // lint if caller of search is an Iterator
2823     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2824         let msg = format!(
2825             "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2826              expressed by calling `any()`.",
2827             search_method
2828         );
2829         let search_snippet = snippet(cx, search_args[1].span, "..");
2830         if search_snippet.lines().count() <= 1 {
2831             // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2832             // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
2833             let any_search_snippet = if_chain! {
2834                 if search_method == "find";
2835                 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
2836                 let closure_body = cx.tcx.hir().body(body_id);
2837                 if let Some(closure_arg) = closure_body.params.get(0);
2838                 then {
2839                     if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
2840                         Some(search_snippet.replacen('&', "", 1))
2841                     } else if let Some(name) = get_arg_name(&closure_arg.pat) {
2842                         Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
2843                     } else {
2844                         None
2845                     }
2846                 } else {
2847                     None
2848                 }
2849             };
2850             // add note if not multi-line
2851             span_lint_and_sugg(
2852                 cx,
2853                 SEARCH_IS_SOME,
2854                 method_span.with_hi(expr.span.hi()),
2855                 &msg,
2856                 "try this",
2857                 format!(
2858                     "any({})",
2859                     any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2860                 ),
2861                 Applicability::MachineApplicable,
2862             );
2863         } else {
2864             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2865         }
2866     }
2867 }
2868
2869 /// Used for `lint_binary_expr_with_method_call`.
2870 #[derive(Copy, Clone)]
2871 struct BinaryExprInfo<'a> {
2872     expr: &'a hir::Expr<'a>,
2873     chain: &'a hir::Expr<'a>,
2874     other: &'a hir::Expr<'a>,
2875     eq: bool,
2876 }
2877
2878 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2879 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2880     macro_rules! lint_with_both_lhs_and_rhs {
2881         ($func:ident, $cx:expr, $info:ident) => {
2882             if !$func($cx, $info) {
2883                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2884                 if $func($cx, $info) {
2885                     return;
2886                 }
2887             }
2888         };
2889     }
2890
2891     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2892     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2893     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2894     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2895 }
2896
2897 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2898 fn lint_chars_cmp(
2899     cx: &LateContext<'_, '_>,
2900     info: &BinaryExprInfo<'_>,
2901     chain_methods: &[&str],
2902     lint: &'static Lint,
2903     suggest: &str,
2904 ) -> bool {
2905     if_chain! {
2906         if let Some(args) = method_chain_args(info.chain, chain_methods);
2907         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2908         if arg_char.len() == 1;
2909         if let hir::ExprKind::Path(ref qpath) = fun.kind;
2910         if let Some(segment) = single_segment_path(qpath);
2911         if segment.ident.name == sym!(Some);
2912         then {
2913             let mut applicability = Applicability::MachineApplicable;
2914             let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2915
2916             if self_ty.kind != ty::Str {
2917                 return false;
2918             }
2919
2920             span_lint_and_sugg(
2921                 cx,
2922                 lint,
2923                 info.expr.span,
2924                 &format!("you should use the `{}` method", suggest),
2925                 "like this",
2926                 format!("{}{}.{}({})",
2927                         if info.eq { "" } else { "!" },
2928                         snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2929                         suggest,
2930                         snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2931                 applicability,
2932             );
2933
2934             return true;
2935         }
2936     }
2937
2938     false
2939 }
2940
2941 /// Checks for the `CHARS_NEXT_CMP` lint.
2942 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2943     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2944 }
2945
2946 /// Checks for the `CHARS_LAST_CMP` lint.
2947 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2948     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2949         true
2950     } else {
2951         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2952     }
2953 }
2954
2955 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2956 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2957     cx: &LateContext<'a, 'tcx>,
2958     info: &BinaryExprInfo<'_>,
2959     chain_methods: &[&str],
2960     lint: &'static Lint,
2961     suggest: &str,
2962 ) -> bool {
2963     if_chain! {
2964         if let Some(args) = method_chain_args(info.chain, chain_methods);
2965         if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2966         if let ast::LitKind::Char(c) = lit.node;
2967         then {
2968             let mut applicability = Applicability::MachineApplicable;
2969             span_lint_and_sugg(
2970                 cx,
2971                 lint,
2972                 info.expr.span,
2973                 &format!("you should use the `{}` method", suggest),
2974                 "like this",
2975                 format!("{}{}.{}('{}')",
2976                         if info.eq { "" } else { "!" },
2977                         snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2978                         suggest,
2979                         c),
2980                 applicability,
2981             );
2982
2983             true
2984         } else {
2985             false
2986         }
2987     }
2988 }
2989
2990 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2991 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2992     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2993 }
2994
2995 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2996 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2997     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2998         true
2999     } else {
3000         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3001     }
3002 }
3003
3004 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3005 fn lint_single_char_pattern<'a, 'tcx>(
3006     cx: &LateContext<'a, 'tcx>,
3007     _expr: &'tcx hir::Expr<'_>,
3008     arg: &'tcx hir::Expr<'_>,
3009 ) {
3010     if_chain! {
3011         if let hir::ExprKind::Lit(lit) = &arg.kind;
3012         if let ast::LitKind::Str(r, style) = lit.node;
3013         if r.as_str().len() == 1;
3014         then {
3015             let mut applicability = Applicability::MachineApplicable;
3016             let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
3017             let ch = if let ast::StrStyle::Raw(nhash) = style {
3018                 let nhash = nhash as usize;
3019                 // for raw string: r##"a"##
3020                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3021             } else {
3022                 // for regular string: "a"
3023                 &snip[1..(snip.len() - 1)]
3024             };
3025             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3026             span_lint_and_sugg(
3027                 cx,
3028                 SINGLE_CHAR_PATTERN,
3029                 arg.span,
3030                 "single-character string constant used as pattern",
3031                 "try using a `char` instead",
3032                 hint,
3033                 applicability,
3034             );
3035         }
3036     }
3037 }
3038
3039 /// Checks for the `USELESS_ASREF` lint.
3040 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3041     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3042     // check if the call is to the actual `AsRef` or `AsMut` trait
3043     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3044         // check if the type after `as_ref` or `as_mut` is the same as before
3045         let recvr = &as_ref_args[0];
3046         let rcv_ty = cx.tables.expr_ty(recvr);
3047         let res_ty = cx.tables.expr_ty(expr);
3048         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3049         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3050         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3051             // allow the `as_ref` or `as_mut` if it is followed by another method call
3052             if_chain! {
3053                 if let Some(parent) = get_parent_expr(cx, expr);
3054                 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.kind;
3055                 if span != &expr.span;
3056                 then {
3057                     return;
3058                 }
3059             }
3060
3061             let mut applicability = Applicability::MachineApplicable;
3062             span_lint_and_sugg(
3063                 cx,
3064                 USELESS_ASREF,
3065                 expr.span,
3066                 &format!("this call to `{}` does nothing", call_name),
3067                 "try this",
3068                 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
3069                 applicability,
3070             );
3071         }
3072     }
3073 }
3074
3075 fn ty_has_iter_method(cx: &LateContext<'_, '_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3076     has_iter_method(cx, self_ref_ty).map(|ty_name| {
3077         let mutbl = match self_ref_ty.kind {
3078             ty::Ref(_, _, mutbl) => mutbl,
3079             _ => unreachable!(),
3080         };
3081         let method_name = match mutbl {
3082             hir::Mutability::Not => "iter",
3083             hir::Mutability::Mut => "iter_mut",
3084         };
3085         (ty_name, method_name)
3086     })
3087 }
3088
3089 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3090     if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3091         return;
3092     }
3093     if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3094         span_lint_and_sugg(
3095             cx,
3096             INTO_ITER_ON_REF,
3097             method_span,
3098             &format!(
3099                 "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
3100                 method_name, kind,
3101             ),
3102             "call directly",
3103             method_name.to_string(),
3104             Applicability::MachineApplicable,
3105         );
3106     }
3107 }
3108
3109 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3110 fn lint_maybe_uninit(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3111     if_chain! {
3112         if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3113         if args.is_empty();
3114         if let hir::ExprKind::Path(ref path) = callee.kind;
3115         if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3116         if !is_maybe_uninit_ty_valid(cx, cx.tables.expr_ty_adjusted(outer));
3117         then {
3118             span_lint(
3119                 cx,
3120                 UNINIT_ASSUMED_INIT,
3121                 outer.span,
3122                 "this call for this type may be undefined behavior"
3123             );
3124         }
3125     }
3126 }
3127
3128 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
3129     match ty.kind {
3130         ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3131         ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3132         ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3133         _ => false,
3134     }
3135 }
3136
3137 fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
3138     span_lint_and_help(
3139         cx,
3140         SUSPICIOUS_MAP,
3141         expr.span,
3142         "this call to `map()` won't have an effect on the call to `count()`",
3143         None,
3144         "make sure you did not confuse `map` with `filter` or `for_each`",
3145     );
3146 }
3147
3148 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3149 fn lint_option_as_ref_deref<'a, 'tcx>(
3150     cx: &LateContext<'a, 'tcx>,
3151     expr: &hir::Expr<'_>,
3152     as_ref_args: &[hir::Expr<'_>],
3153     map_args: &[hir::Expr<'_>],
3154     is_mut: bool,
3155 ) {
3156     let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3157
3158     let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3159     if !is_type_diagnostic_item(cx, option_ty, sym!(option_type)) {
3160         return;
3161     }
3162
3163     let deref_aliases: [&[&str]; 9] = [
3164         &paths::DEREF_TRAIT_METHOD,
3165         &paths::DEREF_MUT_TRAIT_METHOD,
3166         &paths::CSTRING_AS_C_STR,
3167         &paths::OS_STRING_AS_OS_STR,
3168         &paths::PATH_BUF_AS_PATH,
3169         &paths::STRING_AS_STR,
3170         &paths::STRING_AS_MUT_STR,
3171         &paths::VEC_AS_SLICE,
3172         &paths::VEC_AS_MUT_SLICE,
3173     ];
3174
3175     let is_deref = match map_args[1].kind {
3176         hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3177         hir::ExprKind::Closure(_, _, body_id, _, _) => {
3178             let closure_body = cx.tcx.hir().body(body_id);
3179             let closure_expr = remove_blocks(&closure_body.value);
3180
3181             match &closure_expr.kind {
3182                 hir::ExprKind::MethodCall(_, _, args) => {
3183                     if_chain! {
3184                         if args.len() == 1;
3185                         if let hir::ExprKind::Path(qpath) = &args[0].kind;
3186                         if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3187                         if closure_body.params[0].pat.hir_id == local_id;
3188                         let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3189                         if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3190                         then {
3191                             let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3192                             deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3193                         } else {
3194                             false
3195                         }
3196                     }
3197                 },
3198                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3199                     if_chain! {
3200                         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind;
3201                         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind;
3202                         if let hir::ExprKind::Path(ref qpath) = inner2.kind;
3203                         if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, inner2.hir_id);
3204                         then {
3205                             closure_body.params[0].pat.hir_id == local_id
3206                         } else {
3207                             false
3208                         }
3209                     }
3210                 },
3211                 _ => false,
3212             }
3213         },
3214         _ => false,
3215     };
3216
3217     if is_deref {
3218         let current_method = if is_mut {
3219             format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3220         } else {
3221             format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3222         };
3223         let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3224         let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3225         let suggestion = format!("try using {} instead", method_hint);
3226
3227         let msg = format!(
3228             "called `{0}` on an Option value. This can be done more directly \
3229             by calling `{1}` instead",
3230             current_method, hint
3231         );
3232         span_lint_and_sugg(
3233             cx,
3234             OPTION_AS_REF_DEREF,
3235             expr.span,
3236             &msg,
3237             &suggestion,
3238             hint,
3239             Applicability::MachineApplicable,
3240         );
3241     }
3242 }
3243
3244 /// Given a `Result<T, E>` type, return its error type (`E`).
3245 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3246     match ty.kind {
3247         ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym!(result_type)) => substs.types().nth(1),
3248         _ => None,
3249     }
3250 }
3251
3252 /// This checks whether a given type is known to implement Debug.
3253 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
3254     cx.tcx
3255         .get_diagnostic_item(sym::debug_trait)
3256         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3257 }
3258
3259 enum Convention {
3260     Eq(&'static str),
3261     StartsWith(&'static str),
3262 }
3263
3264 #[rustfmt::skip]
3265 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3266     (Convention::Eq("new"), &[SelfKind::No]),
3267     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3268     (Convention::StartsWith("from_"), &[SelfKind::No]),
3269     (Convention::StartsWith("into_"), &[SelfKind::Value]),
3270     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3271     (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3272     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3273 ];
3274
3275 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3276     unsafety: hir::Unsafety::Normal,
3277     constness: hir::Constness::NotConst,
3278     asyncness: hir::IsAsync::NotAsync,
3279     abi: rustc_target::spec::abi::Abi::Rust,
3280 };
3281
3282 #[rustfmt::skip]
3283 const TRAIT_METHODS: [(&str, usize, &hir::FnHeader, SelfKind, OutType, &str); 30] = [
3284     ("add", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Add"),
3285     ("as_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
3286     ("as_ref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
3287     ("bitand", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
3288     ("bitor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
3289     ("bitxor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
3290     ("borrow", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
3291     ("borrow_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
3292     ("clone", 1, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
3293     ("cmp", 2, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
3294     ("default", 0, &FN_HEADER, SelfKind::No, OutType::Any, "std::default::Default"),
3295     ("deref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
3296     ("deref_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
3297     ("div", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Div"),
3298     ("drop", 1, &FN_HEADER, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
3299     ("eq", 2, &FN_HEADER, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
3300     ("from_iter", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
3301     ("from_str", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::str::FromStr"),
3302     ("hash", 2, &FN_HEADER, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
3303     ("index", 2, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
3304     ("index_mut", 2, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
3305     ("into_iter", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
3306     ("mul", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Mul"),
3307     ("neg", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Neg"),
3308     ("next", 1, &FN_HEADER, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
3309     ("not", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Not"),
3310     ("rem", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Rem"),
3311     ("shl", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shl"),
3312     ("shr", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shr"),
3313     ("sub", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Sub"),
3314 ];
3315
3316 #[rustfmt::skip]
3317 const PATTERN_METHODS: [(&str, usize); 17] = [
3318     ("contains", 1),
3319     ("starts_with", 1),
3320     ("ends_with", 1),
3321     ("find", 1),
3322     ("rfind", 1),
3323     ("split", 1),
3324     ("rsplit", 1),
3325     ("split_terminator", 1),
3326     ("rsplit_terminator", 1),
3327     ("splitn", 2),
3328     ("rsplitn", 2),
3329     ("matches", 1),
3330     ("rmatches", 1),
3331     ("match_indices", 1),
3332     ("rmatch_indices", 1),
3333     ("trim_start_matches", 1),
3334     ("trim_end_matches", 1),
3335 ];
3336
3337 #[derive(Clone, Copy, PartialEq, Debug)]
3338 enum SelfKind {
3339     Value,
3340     Ref,
3341     RefMut,
3342     No,
3343 }
3344
3345 impl SelfKind {
3346     fn matches<'a>(self, cx: &LateContext<'_, 'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3347         fn matches_value<'a>(cx: &LateContext<'_, 'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3348             if ty == parent_ty {
3349                 true
3350             } else if ty.is_box() {
3351                 ty.boxed_ty() == parent_ty
3352             } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3353                 if let ty::Adt(_, substs) = ty.kind {
3354                     substs.types().next().map_or(false, |t| t == parent_ty)
3355                 } else {
3356                     false
3357                 }
3358             } else {
3359                 false
3360             }
3361         }
3362
3363         fn matches_ref<'a>(
3364             cx: &LateContext<'_, 'a>,
3365             mutability: hir::Mutability,
3366             parent_ty: Ty<'a>,
3367             ty: Ty<'a>,
3368         ) -> bool {
3369             if let ty::Ref(_, t, m) = ty.kind {
3370                 return m == mutability && t == parent_ty;
3371             }
3372
3373             let trait_path = match mutability {
3374                 hir::Mutability::Not => &paths::ASREF_TRAIT,
3375                 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3376             };
3377
3378             let trait_def_id = match get_trait_def_id(cx, trait_path) {
3379                 Some(did) => did,
3380                 None => return false,
3381             };
3382             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3383         }
3384
3385         match self {
3386             Self::Value => matches_value(cx, parent_ty, ty),
3387             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3388             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3389             Self::No => ty != parent_ty,
3390         }
3391     }
3392
3393     #[must_use]
3394     fn description(self) -> &'static str {
3395         match self {
3396             Self::Value => "self by value",
3397             Self::Ref => "self by reference",
3398             Self::RefMut => "self by mutable reference",
3399             Self::No => "no self",
3400         }
3401     }
3402 }
3403
3404 impl Convention {
3405     #[must_use]
3406     fn check(&self, other: &str) -> bool {
3407         match *self {
3408             Self::Eq(this) => this == other,
3409             Self::StartsWith(this) => other.starts_with(this) && this != other,
3410         }
3411     }
3412 }
3413
3414 impl fmt::Display for Convention {
3415     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3416         match *self {
3417             Self::Eq(this) => this.fmt(f),
3418             Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3419         }
3420     }
3421 }
3422
3423 #[derive(Clone, Copy)]
3424 enum OutType {
3425     Unit,
3426     Bool,
3427     Any,
3428     Ref,
3429 }
3430
3431 impl OutType {
3432     fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FnRetTy<'_>) -> bool {
3433         let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3434         match (self, ty) {
3435             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3436             (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3437             (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3438             (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3439             (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3440             _ => false,
3441         }
3442     }
3443 }
3444
3445 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3446     if let hir::TyKind::Path(ref p) = ty.kind {
3447         match_qpath(p, &["bool"])
3448     } else {
3449         false
3450     }
3451 }
3452
3453 // Returns `true` if `expr` contains a return expression
3454 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3455     struct RetCallFinder {
3456         found: bool,
3457     }
3458
3459     impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3460         type Map = Map<'tcx>;
3461
3462         fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3463             if self.found {
3464                 return;
3465             }
3466             if let hir::ExprKind::Ret(..) = &expr.kind {
3467                 self.found = true;
3468             } else {
3469                 intravisit::walk_expr(self, expr);
3470             }
3471         }
3472
3473         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3474             intravisit::NestedVisitorMap::None
3475         }
3476     }
3477
3478     let mut visitor = RetCallFinder { found: false };
3479     visitor.visit_expr(expr);
3480     visitor.found
3481 }
3482
3483 fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3484     if_chain! {
3485         if args.len() == 2;
3486         if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.tables.expr_ty(&args[0]).kind;
3487         if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3488         if layout.is_zst();
3489         then {
3490             span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3491         }
3492     }
3493 }
3494
3495 fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3496     let ty = cx.tables.expr_ty(&args[0]);
3497
3498     if !match_type(cx, ty, &paths::FILE_TYPE) {
3499         return;
3500     }
3501
3502     let span: Span;
3503     let verb: &str;
3504     let lint_unary: &str;
3505     let help_unary: &str;
3506     if_chain! {
3507         if let Some(parent) = get_parent_expr(cx, expr);
3508         if let hir::ExprKind::Unary(op, _) = parent.kind;
3509         if op == hir::UnOp::UnNot;
3510         then {
3511             lint_unary = "!";
3512             verb = "denies";
3513             help_unary = "";
3514             span = parent.span;
3515         } else {
3516             lint_unary = "";
3517             verb = "covers";
3518             help_unary = "!";
3519             span = expr.span;
3520         }
3521     }
3522     let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3523     let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3524     span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
3525 }
3526
3527 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3528     expected.constness == actual.constness
3529         && expected.unsafety == actual.unsafety
3530         && expected.asyncness == actual.asyncness
3531 }