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