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