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