]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
124fc1d9878e80ef22b501941608eb5802c809de
[rust.git] / clippy_lints / src / methods / mod.rs
1 mod inefficient_to_string;
2 mod manual_saturating_arithmetic;
3 mod option_map_unwrap_or;
4 mod unnecessary_filter_map;
5
6 use std::borrow::Cow;
7 use std::fmt;
8 use std::iter;
9
10 use if_chain::if_chain;
11 use rustc_ast::ast;
12 use rustc_errors::Applicability;
13 use rustc_hir as hir;
14 use rustc_hir::intravisit::{self, Visitor};
15 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::lint::in_external_macro;
18 use rustc_middle::ty::subst::GenericArgKind;
19 use rustc_middle::ty::{self, Predicate, Ty};
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::source_map::Span;
22 use rustc_span::symbol::{sym, Symbol, SymbolStr};
23
24 use crate::consts::{constant, Constant};
25 use crate::utils::usage::mutated_variables;
26 use crate::utils::{
27     get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, implements_trait, in_macro, is_copy,
28     is_ctor_or_promotable_const_function, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
29     match_def_path, match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, paths,
30     remove_blocks, return_ty, same_tys, single_segment_path, snippet, snippet_with_applicability,
31     snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
32     span_lint_and_then, sugg, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
33 };
34
35 declare_clippy_lint! {
36     /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
37     ///
38     /// **Why is this bad?** Usually it is better to handle the `None` case, or to
39     /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
40     /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
41     /// `Allow` by default.
42     ///
43     /// **Known problems:** None.
44     ///
45     /// **Example:**
46     ///
47     /// Using unwrap on an `Option`:
48     ///
49     /// ```rust
50     /// let opt = Some(1);
51     /// opt.unwrap();
52     /// ```
53     ///
54     /// Better:
55     ///
56     /// ```rust
57     /// let opt = Some(1);
58     /// opt.expect("more helpful message");
59     /// ```
60     pub OPTION_UNWRAP_USED,
61     restriction,
62     "using `Option.unwrap()`, which should at least get a better message using `expect()`"
63 }
64
65 declare_clippy_lint! {
66     /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
67     ///
68     /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
69     /// values. Normally, you want to implement more sophisticated error handling,
70     /// and propagate errors upwards with `?` operator.
71     ///
72     /// Even if you want to panic on errors, not all `Error`s implement good
73     /// messages on display. Therefore, it may be beneficial to look at the places
74     /// where they may get displayed. Activate this lint to do just that.
75     ///
76     /// **Known problems:** None.
77     ///
78     /// **Example:**
79     /// Using unwrap on an `Result`:
80     ///
81     /// ```rust
82     /// let res: Result<usize, ()> = Ok(1);
83     /// res.unwrap();
84     /// ```
85     ///
86     /// Better:
87     ///
88     /// ```rust
89     /// let res: Result<usize, ()> = Ok(1);
90     /// res.expect("more helpful message");
91     /// ```
92     pub RESULT_UNWRAP_USED,
93     restriction,
94     "using `Result.unwrap()`, which might be better handled"
95 }
96
97 declare_clippy_lint! {
98     /// **What it does:** Checks for `.expect()` calls on `Option`s.
99     ///
100     /// **Why is this bad?** Usually it is better to handle the `None` case. Still,
101     ///  for a lot of quick-and-dirty code, `expect` is a good choice, which is why
102     ///  this lint is `Allow` by default.
103     ///
104     /// **Known problems:** None.
105     ///
106     /// **Example:**
107     ///
108     /// Using expect on an `Option`:
109     ///
110     /// ```rust
111     /// let opt = Some(1);
112     /// opt.expect("one");
113     /// ```
114     ///
115     /// Better:
116     ///
117     /// ```rust,ignore
118     /// let opt = Some(1);
119     /// opt?;
120     /// ```
121     pub OPTION_EXPECT_USED,
122     restriction,
123     "using `Option.expect()`, which might be better handled"
124 }
125
126 declare_clippy_lint! {
127     /// **What it does:** Checks for `.expect()` calls on `Result`s.
128     ///
129     /// **Why is this bad?** `result.expect()` will let the thread panic on `Err`
130     /// values. Normally, you want to implement more sophisticated error handling,
131     /// and propagate errors upwards with `?` operator.
132     ///
133     /// **Known problems:** None.
134     ///
135     /// **Example:**
136     /// Using expect on an `Result`:
137     ///
138     /// ```rust
139     /// let res: Result<usize, ()> = Ok(1);
140     /// res.expect("one");
141     /// ```
142     ///
143     /// Better:
144     ///
145     /// ```rust
146     /// let res: Result<usize, ()> = Ok(1);
147     /// res?;
148     /// # Ok::<(), ()>(())
149     /// ```
150     pub RESULT_EXPECT_USED,
151     restriction,
152     "using `Result.expect()`, which might be better handled"
153 }
154
155 declare_clippy_lint! {
156     /// **What it does:** Checks for methods that should live in a trait
157     /// implementation of a `std` trait (see [llogiq's blog
158     /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
159     /// information) instead of an inherent implementation.
160     ///
161     /// **Why is this bad?** Implementing the traits improve ergonomics for users of
162     /// the code, often with very little cost. Also people seeing a `mul(...)`
163     /// method
164     /// may expect `*` to work equally, so you should have good reason to disappoint
165     /// them.
166     ///
167     /// **Known problems:** None.
168     ///
169     /// **Example:**
170     /// ```rust
171     /// struct X;
172     /// impl X {
173     ///     fn add(&self, other: &X) -> X {
174     ///         // ..
175     /// # X
176     ///     }
177     /// }
178     /// ```
179     pub SHOULD_IMPLEMENT_TRAIT,
180     style,
181     "defining a method that should be implementing a std trait"
182 }
183
184 declare_clippy_lint! {
185     /// **What it does:** Checks for methods with certain name prefixes and which
186     /// doesn't match how self is taken. The actual rules are:
187     ///
188     /// |Prefix |`self` taken          |
189     /// |-------|----------------------|
190     /// |`as_`  |`&self` or `&mut self`|
191     /// |`from_`| none                 |
192     /// |`into_`|`self`                |
193     /// |`is_`  |`&self` or none       |
194     /// |`to_`  |`&self`               |
195     ///
196     /// **Why is this bad?** Consistency breeds readability. If you follow the
197     /// conventions, your users won't be surprised that they, e.g., need to supply a
198     /// mutable reference to a `as_..` function.
199     ///
200     /// **Known problems:** None.
201     ///
202     /// **Example:**
203     /// ```rust
204     /// # struct X;
205     /// impl X {
206     ///     fn as_str(self) -> &'static str {
207     ///         // ..
208     /// # ""
209     ///     }
210     /// }
211     /// ```
212     pub WRONG_SELF_CONVENTION,
213     style,
214     "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
215 }
216
217 declare_clippy_lint! {
218     /// **What it does:** This is the same as
219     /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
220     ///
221     /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
222     ///
223     /// **Known problems:** Actually *renaming* the function may break clients if
224     /// the function is part of the public interface. In that case, be mindful of
225     /// the stability guarantees you've given your users.
226     ///
227     /// **Example:**
228     /// ```rust
229     /// # struct X;
230     /// impl<'a> X {
231     ///     pub fn as_str(self) -> &'a str {
232     ///         "foo"
233     ///     }
234     /// }
235     /// ```
236     pub WRONG_PUB_SELF_CONVENTION,
237     restriction,
238     "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
239 }
240
241 declare_clippy_lint! {
242     /// **What it does:** Checks for usage of `ok().expect(..)`.
243     ///
244     /// **Why is this bad?** Because you usually call `expect()` on the `Result`
245     /// directly to get a better error message.
246     ///
247     /// **Known problems:** The error type needs to implement `Debug`
248     ///
249     /// **Example:**
250     /// ```rust
251     /// # let x = Ok::<_, ()>(());
252     /// x.ok().expect("why did I do this again?")
253     /// ```
254     pub OK_EXPECT,
255     style,
256     "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
257 }
258
259 declare_clippy_lint! {
260     /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
261     ///
262     /// **Why is this bad?** Readability, this can be written more concisely as
263     /// `_.map_or(_, _)`.
264     ///
265     /// **Known problems:** The order of the arguments is not in execution order
266     ///
267     /// **Example:**
268     /// ```rust
269     /// # let x = Some(1);
270     /// x.map(|a| a + 1).unwrap_or(0);
271     /// ```
272     pub OPTION_MAP_UNWRAP_OR,
273     pedantic,
274     "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as `map_or(a, f)`"
275 }
276
277 declare_clippy_lint! {
278     /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
279     ///
280     /// **Why is this bad?** Readability, this can be written more concisely as
281     /// `_.map_or_else(_, _)`.
282     ///
283     /// **Known problems:** The order of the arguments is not in execution order.
284     ///
285     /// **Example:**
286     /// ```rust
287     /// # let x = Some(1);
288     /// # fn some_function() -> usize { 1 }
289     /// x.map(|a| a + 1).unwrap_or_else(some_function);
290     /// ```
291     pub OPTION_MAP_UNWRAP_OR_ELSE,
292     pedantic,
293     "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `map_or_else(g, f)`"
294 }
295
296 declare_clippy_lint! {
297     /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
298     ///
299     /// **Why is this bad?** Readability, this can be written more concisely as
300     /// `result.map_or_else(_, _)`.
301     ///
302     /// **Known problems:** None.
303     ///
304     /// **Example:**
305     /// ```rust
306     /// # let x: Result<usize, ()> = Ok(1);
307     /// # fn some_function(foo: ()) -> usize { 1 }
308     /// x.map(|a| a + 1).unwrap_or_else(some_function);
309     /// ```
310     pub RESULT_MAP_UNWRAP_OR_ELSE,
311     pedantic,
312     "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `.map_or_else(g, f)`"
313 }
314
315 declare_clippy_lint! {
316     /// **What it does:** Checks for usage of `_.map_or(None, _)`.
317     ///
318     /// **Why is this bad?** Readability, this can be written more concisely as
319     /// `_.and_then(_)`.
320     ///
321     /// **Known problems:** The order of the arguments is not in execution order.
322     ///
323     /// **Example:**
324     /// ```rust
325     /// # let opt = Some(1);
326     /// opt.map_or(None, |a| Some(a + 1))
327     /// # ;
328     /// ```
329     pub OPTION_MAP_OR_NONE,
330     style,
331     "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
332 }
333
334 declare_clippy_lint! {
335     /// **What it does:** Checks for usage of `_.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 self_ty = cx.tcx.type_of(def_id);
1412         if_chain! {
1413             if let hir::ImplItemKind::Fn(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, self_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, self_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::Fn(_, _) = impl_item.kind {
1473             let ret_ty = return_ty(cx, impl_item.hir_id);
1474
1475             let contains_self_ty = |ty: Ty<'tcx>| {
1476                 ty.walk().any(|inner| match inner.unpack() {
1477                     GenericArgKind::Type(inner_ty) => same_tys(cx, self_ty, inner_ty),
1478
1479                     GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
1480                 })
1481             };
1482
1483             // walk the return type and check for Self (this does not check associated types)
1484             if contains_self_ty(ret_ty) {
1485                 return;
1486             }
1487
1488             // if return type is impl trait, check the associated types
1489             if let ty::Opaque(def_id, _) = ret_ty.kind {
1490                 // one of the associated types must be Self
1491                 for predicate in cx.tcx.predicates_of(def_id).predicates {
1492                     match predicate {
1493                         (Predicate::Projection(poly_projection_predicate), _) => {
1494                             let binder = poly_projection_predicate.ty();
1495                             let associated_type = binder.skip_binder();
1496
1497                             // walk the associated type and check for Self
1498                             if contains_self_ty(associated_type) {
1499                                 return;
1500                             }
1501                         },
1502                         (_, _) => {},
1503                     }
1504                 }
1505             }
1506
1507             if name == "new" && !same_tys(cx, ret_ty, self_ty) {
1508                 span_lint(
1509                     cx,
1510                     NEW_RET_NO_SELF,
1511                     impl_item.span,
1512                     "methods called `new` usually return `Self`",
1513                 );
1514             }
1515         }
1516     }
1517 }
1518
1519 /// Checks for the `OR_FUN_CALL` lint.
1520 #[allow(clippy::too_many_lines)]
1521 fn lint_or_fun_call<'a, 'tcx>(
1522     cx: &LateContext<'a, 'tcx>,
1523     expr: &hir::Expr<'_>,
1524     method_span: Span,
1525     name: &str,
1526     args: &'tcx [hir::Expr<'_>],
1527 ) {
1528     // Searches an expression for method calls or function calls that aren't ctors
1529     struct FunCallFinder<'a, 'tcx> {
1530         cx: &'a LateContext<'a, 'tcx>,
1531         found: bool,
1532     }
1533
1534     impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1535         type Map = Map<'tcx>;
1536
1537         fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
1538             let call_found = match &expr.kind {
1539                 // ignore enum and struct constructors
1540                 hir::ExprKind::Call(..) => !is_ctor_or_promotable_const_function(self.cx, expr),
1541                 hir::ExprKind::MethodCall(..) => true,
1542                 _ => false,
1543             };
1544
1545             if call_found {
1546                 self.found |= true;
1547             }
1548
1549             if !self.found {
1550                 intravisit::walk_expr(self, expr);
1551             }
1552         }
1553
1554         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1555             intravisit::NestedVisitorMap::None
1556         }
1557     }
1558
1559     /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1560     fn check_unwrap_or_default(
1561         cx: &LateContext<'_, '_>,
1562         name: &str,
1563         fun: &hir::Expr<'_>,
1564         self_expr: &hir::Expr<'_>,
1565         arg: &hir::Expr<'_>,
1566         or_has_args: bool,
1567         span: Span,
1568     ) -> bool {
1569         if_chain! {
1570             if !or_has_args;
1571             if name == "unwrap_or";
1572             if let hir::ExprKind::Path(ref qpath) = fun.kind;
1573             let path = &*last_path_segment(qpath).ident.as_str();
1574             if ["default", "new"].contains(&path);
1575             let arg_ty = cx.tables.expr_ty(arg);
1576             if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1577             if implements_trait(cx, arg_ty, default_trait_id, &[]);
1578
1579             then {
1580                 let mut applicability = Applicability::MachineApplicable;
1581                 span_lint_and_sugg(
1582                     cx,
1583                     OR_FUN_CALL,
1584                     span,
1585                     &format!("use of `{}` followed by a call to `{}`", name, path),
1586                     "try this",
1587                     format!(
1588                         "{}.unwrap_or_default()",
1589                         snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1590                     ),
1591                     applicability,
1592                 );
1593
1594                 true
1595             } else {
1596                 false
1597             }
1598         }
1599     }
1600
1601     /// Checks for `*or(foo())`.
1602     #[allow(clippy::too_many_arguments)]
1603     fn check_general_case<'a, 'tcx>(
1604         cx: &LateContext<'a, 'tcx>,
1605         name: &str,
1606         method_span: Span,
1607         fun_span: Span,
1608         self_expr: &hir::Expr<'_>,
1609         arg: &'tcx hir::Expr<'_>,
1610         or_has_args: bool,
1611         span: Span,
1612     ) {
1613         // (path, fn_has_argument, methods, suffix)
1614         let know_types: &[(&[_], _, &[_], _)] = &[
1615             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1616             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1617             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1618             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1619         ];
1620
1621         if_chain! {
1622             if know_types.iter().any(|k| k.2.contains(&name));
1623
1624             let mut finder = FunCallFinder { cx: &cx, found: false };
1625             if { finder.visit_expr(&arg); finder.found };
1626             if !contains_return(&arg);
1627
1628             let self_ty = cx.tables.expr_ty(self_expr);
1629
1630             if let Some(&(_, fn_has_arguments, poss, suffix)) =
1631                    know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1632
1633             if poss.contains(&name);
1634
1635             then {
1636                 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1637                     (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1638                     (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1639                     (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1640                 };
1641                 let span_replace_word = method_span.with_hi(span.hi());
1642                 span_lint_and_sugg(
1643                     cx,
1644                     OR_FUN_CALL,
1645                     span_replace_word,
1646                     &format!("use of `{}` followed by a function call", name),
1647                     "try this",
1648                     format!("{}_{}({})", name, suffix, sugg),
1649                     Applicability::HasPlaceholders,
1650                 );
1651             }
1652         }
1653     }
1654
1655     if args.len() == 2 {
1656         match args[1].kind {
1657             hir::ExprKind::Call(ref fun, ref or_args) => {
1658                 let or_has_args = !or_args.is_empty();
1659                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1660                     check_general_case(
1661                         cx,
1662                         name,
1663                         method_span,
1664                         fun.span,
1665                         &args[0],
1666                         &args[1],
1667                         or_has_args,
1668                         expr.span,
1669                     );
1670                 }
1671             },
1672             hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1673                 cx,
1674                 name,
1675                 method_span,
1676                 span,
1677                 &args[0],
1678                 &args[1],
1679                 !or_args.is_empty(),
1680                 expr.span,
1681             ),
1682             _ => {},
1683         }
1684     }
1685 }
1686
1687 /// Checks for the `EXPECT_FUN_CALL` lint.
1688 #[allow(clippy::too_many_lines)]
1689 fn lint_expect_fun_call(
1690     cx: &LateContext<'_, '_>,
1691     expr: &hir::Expr<'_>,
1692     method_span: Span,
1693     name: &str,
1694     args: &[hir::Expr<'_>],
1695 ) {
1696     // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1697     // `&str`
1698     fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1699         let mut arg_root = arg;
1700         loop {
1701             arg_root = match &arg_root.kind {
1702                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1703                 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1704                     if call_args.len() == 1
1705                         && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1706                         && {
1707                             let arg_type = cx.tables.expr_ty(&call_args[0]);
1708                             let base_type = walk_ptrs_ty(arg_type);
1709                             base_type.kind == ty::Str || match_type(cx, base_type, &paths::STRING)
1710                         }
1711                     {
1712                         &call_args[0]
1713                     } else {
1714                         break;
1715                     }
1716                 },
1717                 _ => break,
1718             };
1719         }
1720         arg_root
1721     }
1722
1723     // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1724     // converted to string.
1725     fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1726         let arg_ty = cx.tables.expr_ty(arg);
1727         if match_type(cx, arg_ty, &paths::STRING) {
1728             return false;
1729         }
1730         if let ty::Ref(_, ty, ..) = arg_ty.kind {
1731             if ty.kind == ty::Str && can_be_static_str(cx, arg) {
1732                 return false;
1733             }
1734         };
1735         true
1736     }
1737
1738     // Check if an expression could have type `&'static str`, knowing that it
1739     // has type `&str` for some lifetime.
1740     fn can_be_static_str(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1741         match arg.kind {
1742             hir::ExprKind::Lit(_) => true,
1743             hir::ExprKind::Call(fun, _) => {
1744                 if let hir::ExprKind::Path(ref p) = fun.kind {
1745                     match cx.tables.qpath_res(p, fun.hir_id) {
1746                         hir::def::Res::Def(hir::def::DefKind::Fn, def_id)
1747                         | hir::def::Res::Def(hir::def::DefKind::AssocFn, def_id) => matches!(
1748                             cx.tcx.fn_sig(def_id).output().skip_binder().kind,
1749                             ty::Ref(ty::ReStatic, ..)
1750                         ),
1751                         _ => false,
1752                     }
1753                 } else {
1754                     false
1755                 }
1756             },
1757             hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(arg.hir_id).map_or(false, |method_id| {
1758                 matches!(
1759                     cx.tcx.fn_sig(method_id).output().skip_binder().kind,
1760                     ty::Ref(ty::ReStatic, ..)
1761                 )
1762             }),
1763             hir::ExprKind::Path(ref p) => match cx.tables.qpath_res(p, arg.hir_id) {
1764                 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _) => true,
1765                 _ => false,
1766             },
1767             _ => false,
1768         }
1769     }
1770
1771     fn generate_format_arg_snippet(
1772         cx: &LateContext<'_, '_>,
1773         a: &hir::Expr<'_>,
1774         applicability: &mut Applicability,
1775     ) -> Vec<String> {
1776         if_chain! {
1777             if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1778             if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1779             if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1780
1781             then {
1782                 format_arg_expr_tup
1783                     .iter()
1784                     .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1785                     .collect()
1786             } else {
1787                 unreachable!()
1788             }
1789         }
1790     }
1791
1792     fn is_call(node: &hir::ExprKind<'_>) -> bool {
1793         match node {
1794             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1795                 is_call(&expr.kind)
1796             },
1797             hir::ExprKind::Call(..)
1798             | hir::ExprKind::MethodCall(..)
1799             // These variants are debatable or require further examination
1800             | hir::ExprKind::Match(..)
1801             | hir::ExprKind::Block{ .. } => true,
1802             _ => false,
1803         }
1804     }
1805
1806     if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1807         return;
1808     }
1809
1810     let receiver_type = cx.tables.expr_ty_adjusted(&args[0]);
1811     let closure_args = if match_type(cx, receiver_type, &paths::OPTION) {
1812         "||"
1813     } else if match_type(cx, receiver_type, &paths::RESULT) {
1814         "|_|"
1815     } else {
1816         return;
1817     };
1818
1819     let arg_root = get_arg_root(cx, &args[1]);
1820
1821     let span_replace_word = method_span.with_hi(expr.span.hi());
1822
1823     let mut applicability = Applicability::MachineApplicable;
1824
1825     //Special handling for `format!` as arg_root
1826     if_chain! {
1827         if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1828         if block.stmts.len() == 1;
1829         if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1830         if let Some(arg_root) = &local.init;
1831         if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1832         if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
1833         if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
1834         then {
1835             let fmt_spec = &format_args[0];
1836             let fmt_args = &format_args[1];
1837
1838             let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1839
1840             args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1841
1842             let sugg = args.join(", ");
1843
1844             span_lint_and_sugg(
1845                 cx,
1846                 EXPECT_FUN_CALL,
1847                 span_replace_word,
1848                 &format!("use of `{}` followed by a function call", name),
1849                 "try this",
1850                 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1851                 applicability,
1852             );
1853
1854             return;
1855         }
1856     }
1857
1858     let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1859     if requires_to_string(cx, arg_root) {
1860         arg_root_snippet.to_mut().push_str(".to_string()");
1861     }
1862
1863     span_lint_and_sugg(
1864         cx,
1865         EXPECT_FUN_CALL,
1866         span_replace_word,
1867         &format!("use of `{}` followed by a function call", name),
1868         "try this",
1869         format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1870         applicability,
1871     );
1872 }
1873
1874 /// Checks for the `CLONE_ON_COPY` lint.
1875 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
1876     let ty = cx.tables.expr_ty(expr);
1877     if let ty::Ref(_, inner, _) = arg_ty.kind {
1878         if let ty::Ref(_, innermost, _) = inner.kind {
1879             span_lint_and_then(
1880                 cx,
1881                 CLONE_DOUBLE_REF,
1882                 expr.span,
1883                 "using `clone` on a double-reference; \
1884                  this will copy the reference instead of cloning the inner type",
1885                 |db| {
1886                     if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1887                         let mut ty = innermost;
1888                         let mut n = 0;
1889                         while let ty::Ref(_, inner, _) = ty.kind {
1890                             ty = inner;
1891                             n += 1;
1892                         }
1893                         let refs: String = iter::repeat('&').take(n + 1).collect();
1894                         let derefs: String = iter::repeat('*').take(n).collect();
1895                         let explicit = format!("{}{}::clone({})", refs, ty, snip);
1896                         db.span_suggestion(
1897                             expr.span,
1898                             "try dereferencing it",
1899                             format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1900                             Applicability::MaybeIncorrect,
1901                         );
1902                         db.span_suggestion(
1903                             expr.span,
1904                             "or try being explicit about what type to clone",
1905                             explicit,
1906                             Applicability::MaybeIncorrect,
1907                         );
1908                     }
1909                 },
1910             );
1911             return; // don't report clone_on_copy
1912         }
1913     }
1914
1915     if is_copy(cx, ty) {
1916         let snip;
1917         if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1918             let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1919             match &cx.tcx.hir().get(parent) {
1920                 hir::Node::Expr(parent) => match parent.kind {
1921                     // &*x is a nop, &x.clone() is not
1922                     hir::ExprKind::AddrOf(..) |
1923                     // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1924                     hir::ExprKind::MethodCall(..) => return,
1925                     _ => {},
1926                 },
1927                 hir::Node::Stmt(stmt) => {
1928                     if let hir::StmtKind::Local(ref loc) = stmt.kind {
1929                         if let hir::PatKind::Ref(..) = loc.pat.kind {
1930                             // let ref y = *x borrows x, let ref y = x.clone() does not
1931                             return;
1932                         }
1933                     }
1934                 },
1935                 _ => {},
1936             }
1937
1938             // x.clone() might have dereferenced x, possibly through Deref impls
1939             if cx.tables.expr_ty(arg) == ty {
1940                 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1941             } else {
1942                 let deref_count = cx
1943                     .tables
1944                     .expr_adjustments(arg)
1945                     .iter()
1946                     .filter(|adj| {
1947                         if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1948                             true
1949                         } else {
1950                             false
1951                         }
1952                     })
1953                     .count();
1954                 let derefs: String = iter::repeat('*').take(deref_count).collect();
1955                 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1956             }
1957         } else {
1958             snip = None;
1959         }
1960         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1961             if let Some((text, snip)) = snip {
1962                 db.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1963             }
1964         });
1965     }
1966 }
1967
1968 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
1969     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1970
1971     if let ty::Adt(_, subst) = obj_ty.kind {
1972         let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1973             "Rc"
1974         } else if match_type(cx, obj_ty, &paths::ARC) {
1975             "Arc"
1976         } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1977             "Weak"
1978         } else {
1979             return;
1980         };
1981
1982         span_lint_and_sugg(
1983             cx,
1984             CLONE_ON_REF_PTR,
1985             expr.span,
1986             "using `.clone()` on a ref-counted pointer",
1987             "try this",
1988             format!(
1989                 "{}::<{}>::clone(&{})",
1990                 caller_type,
1991                 subst.type_at(0),
1992                 snippet(cx, arg.span, "_")
1993             ),
1994             Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
1995         );
1996     }
1997 }
1998
1999 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2000     let arg = &args[1];
2001     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2002         let target = &arglists[0][0];
2003         let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
2004         let ref_str = if self_ty.kind == ty::Str {
2005             ""
2006         } else if match_type(cx, self_ty, &paths::STRING) {
2007             "&"
2008         } else {
2009             return;
2010         };
2011
2012         let mut applicability = Applicability::MachineApplicable;
2013         span_lint_and_sugg(
2014             cx,
2015             STRING_EXTEND_CHARS,
2016             expr.span,
2017             "calling `.extend(_.chars())`",
2018             "try this",
2019             format!(
2020                 "{}.push_str({}{})",
2021                 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
2022                 ref_str,
2023                 snippet_with_applicability(cx, target.span, "_", &mut applicability)
2024             ),
2025             applicability,
2026         );
2027     }
2028 }
2029
2030 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2031     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
2032     if match_type(cx, obj_ty, &paths::STRING) {
2033         lint_string_extend(cx, expr, args);
2034     }
2035 }
2036
2037 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2038     if_chain! {
2039         let source_type = cx.tables.expr_ty(source);
2040         if let ty::Adt(def, substs) = source_type.kind;
2041         if match_def_path(cx, def.did, &paths::RESULT);
2042         if match_type(cx, substs.type_at(0), &paths::CSTRING);
2043         then {
2044             span_lint_and_then(
2045                 cx,
2046                 TEMPORARY_CSTRING_AS_PTR,
2047                 expr.span,
2048                 "you are getting the inner pointer of a temporary `CString`",
2049                 |db| {
2050                     db.note("that pointer will be invalid outside this expression");
2051                     db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2052                 });
2053         }
2054     }
2055 }
2056
2057 fn lint_iter_cloned_collect<'a, 'tcx>(
2058     cx: &LateContext<'a, 'tcx>,
2059     expr: &hir::Expr<'_>,
2060     iter_args: &'tcx [hir::Expr<'_>],
2061 ) {
2062     if_chain! {
2063         if is_type_diagnostic_item(cx, cx.tables.expr_ty(expr), Symbol::intern("vec_type"));
2064         if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0]));
2065         if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2066
2067         then {
2068             span_lint_and_sugg(
2069                 cx,
2070                 ITER_CLONED_COLLECT,
2071                 to_replace,
2072                 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2073                  more readable",
2074                 "try",
2075                 ".to_vec()".to_string(),
2076                 Applicability::MachineApplicable,
2077             );
2078         }
2079     }
2080 }
2081
2082 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2083     fn check_fold_with_op(
2084         cx: &LateContext<'_, '_>,
2085         expr: &hir::Expr<'_>,
2086         fold_args: &[hir::Expr<'_>],
2087         fold_span: Span,
2088         op: hir::BinOpKind,
2089         replacement_method_name: &str,
2090         replacement_has_args: bool,
2091     ) {
2092         if_chain! {
2093             // Extract the body of the closure passed to fold
2094             if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2095             let closure_body = cx.tcx.hir().body(body_id);
2096             let closure_expr = remove_blocks(&closure_body.value);
2097
2098             // Check if the closure body is of the form `acc <op> some_expr(x)`
2099             if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2100             if bin_op.node == op;
2101
2102             // Extract the names of the two arguments to the closure
2103             if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2104             if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2105
2106             if match_var(&*left_expr, first_arg_ident);
2107             if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2108
2109             then {
2110                 let mut applicability = Applicability::MachineApplicable;
2111                 let sugg = if replacement_has_args {
2112                     format!(
2113                         "{replacement}(|{s}| {r})",
2114                         replacement = replacement_method_name,
2115                         s = second_arg_ident,
2116                         r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2117                     )
2118                 } else {
2119                     format!(
2120                         "{replacement}()",
2121                         replacement = replacement_method_name,
2122                     )
2123                 };
2124
2125                 span_lint_and_sugg(
2126                     cx,
2127                     UNNECESSARY_FOLD,
2128                     fold_span.with_hi(expr.span.hi()),
2129                     // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2130                     "this `.fold` can be written more succinctly using another method",
2131                     "try",
2132                     sugg,
2133                     applicability,
2134                 );
2135             }
2136         }
2137     }
2138
2139     // Check that this is a call to Iterator::fold rather than just some function called fold
2140     if !match_trait_method(cx, expr, &paths::ITERATOR) {
2141         return;
2142     }
2143
2144     assert!(
2145         fold_args.len() == 3,
2146         "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2147     );
2148
2149     // Check if the first argument to .fold is a suitable literal
2150     if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2151         match lit.node {
2152             ast::LitKind::Bool(false) => {
2153                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2154             },
2155             ast::LitKind::Bool(true) => {
2156                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2157             },
2158             ast::LitKind::Int(0, _) => {
2159                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2160             },
2161             ast::LitKind::Int(1, _) => {
2162                 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2163             },
2164             _ => (),
2165         }
2166     }
2167 }
2168
2169 fn lint_step_by<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2170     if match_trait_method(cx, expr, &paths::ITERATOR) {
2171         if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
2172             span_lint(
2173                 cx,
2174                 ITERATOR_STEP_BY_ZERO,
2175                 expr.span,
2176                 "Iterator::step_by(0) will panic at runtime",
2177             );
2178         }
2179     }
2180 }
2181
2182 fn lint_iter_nth<'a, 'tcx>(
2183     cx: &LateContext<'a, 'tcx>,
2184     expr: &hir::Expr<'_>,
2185     nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2186     is_mut: bool,
2187 ) {
2188     let iter_args = nth_and_iter_args[1];
2189     let mut_str = if is_mut { "_mut" } else { "" };
2190     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
2191         "slice"
2192     } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), Symbol::intern("vec_type")) {
2193         "Vec"
2194     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
2195         "VecDeque"
2196     } else {
2197         let nth_args = nth_and_iter_args[0];
2198         lint_iter_nth_zero(cx, expr, &nth_args);
2199         return; // caller is not a type that we want to lint
2200     };
2201
2202     span_lint_and_help(
2203         cx,
2204         ITER_NTH,
2205         expr.span,
2206         &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2207         &format!("calling `.get{}()` is both faster and more readable", mut_str),
2208     );
2209 }
2210
2211 fn lint_iter_nth_zero<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2212     if_chain! {
2213         if match_trait_method(cx, expr, &paths::ITERATOR);
2214         if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &nth_args[1]);
2215         then {
2216             let mut applicability = Applicability::MachineApplicable;
2217             span_lint_and_sugg(
2218                 cx,
2219                 ITER_NTH_ZERO,
2220                 expr.span,
2221                 "called `.nth(0)` on a `std::iter::Iterator`",
2222                 "try calling",
2223                 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2224                 applicability,
2225             );
2226         }
2227     }
2228 }
2229
2230 fn lint_get_unwrap<'a, 'tcx>(
2231     cx: &LateContext<'a, 'tcx>,
2232     expr: &hir::Expr<'_>,
2233     get_args: &'tcx [hir::Expr<'_>],
2234     is_mut: bool,
2235 ) {
2236     // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2237     // because they do not implement `IndexMut`
2238     let mut applicability = Applicability::MachineApplicable;
2239     let expr_ty = cx.tables.expr_ty(&get_args[0]);
2240     let get_args_str = if get_args.len() > 1 {
2241         snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
2242     } else {
2243         return; // not linting on a .get().unwrap() chain or variant
2244     };
2245     let mut needs_ref;
2246     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2247         needs_ref = get_args_str.parse::<usize>().is_ok();
2248         "slice"
2249     } else if is_type_diagnostic_item(cx, expr_ty, Symbol::intern("vec_type")) {
2250         needs_ref = get_args_str.parse::<usize>().is_ok();
2251         "Vec"
2252     } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
2253         needs_ref = get_args_str.parse::<usize>().is_ok();
2254         "VecDeque"
2255     } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
2256         needs_ref = true;
2257         "HashMap"
2258     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2259         needs_ref = true;
2260         "BTreeMap"
2261     } else {
2262         return; // caller is not a type that we want to lint
2263     };
2264
2265     let mut span = expr.span;
2266
2267     // Handle the case where the result is immediately dereferenced
2268     // by not requiring ref and pulling the dereference into the
2269     // suggestion.
2270     if_chain! {
2271         if needs_ref;
2272         if let Some(parent) = get_parent_expr(cx, expr);
2273         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2274         then {
2275             needs_ref = false;
2276             span = parent.span;
2277         }
2278     }
2279
2280     let mut_str = if is_mut { "_mut" } else { "" };
2281     let borrow_str = if !needs_ref {
2282         ""
2283     } else if is_mut {
2284         "&mut "
2285     } else {
2286         "&"
2287     };
2288
2289     span_lint_and_sugg(
2290         cx,
2291         GET_UNWRAP,
2292         span,
2293         &format!(
2294             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2295             mut_str, caller_type
2296         ),
2297         "try this",
2298         format!(
2299             "{}{}[{}]",
2300             borrow_str,
2301             snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
2302             get_args_str
2303         ),
2304         applicability,
2305     );
2306 }
2307
2308 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
2309     // lint if caller of skip is an Iterator
2310     if match_trait_method(cx, expr, &paths::ITERATOR) {
2311         span_lint_and_help(
2312             cx,
2313             ITER_SKIP_NEXT,
2314             expr.span,
2315             "called `skip(x).next()` on an iterator",
2316             "this is more succinctly expressed by calling `nth(x)`",
2317         );
2318     }
2319 }
2320
2321 fn derefs_to_slice<'a, 'tcx>(
2322     cx: &LateContext<'a, 'tcx>,
2323     expr: &'tcx hir::Expr<'tcx>,
2324     ty: Ty<'tcx>,
2325 ) -> Option<&'tcx hir::Expr<'tcx>> {
2326     fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
2327         match ty.kind {
2328             ty::Slice(_) => true,
2329             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2330             ty::Adt(..) => is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type")),
2331             ty::Array(_, size) => {
2332                 if let Some(size) = size.try_eval_usize(cx.tcx, cx.param_env) {
2333                     size < 32
2334                 } else {
2335                     false
2336                 }
2337             },
2338             ty::Ref(_, inner, _) => may_slice(cx, inner),
2339             _ => false,
2340         }
2341     }
2342
2343     if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
2344         if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
2345             Some(&args[0])
2346         } else {
2347             None
2348         }
2349     } else {
2350         match ty.kind {
2351             ty::Slice(_) => Some(expr),
2352             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2353             ty::Ref(_, inner, _) => {
2354                 if may_slice(cx, inner) {
2355                     Some(expr)
2356                 } else {
2357                     None
2358                 }
2359             },
2360             _ => None,
2361         }
2362     }
2363 }
2364
2365 /// lint use of `unwrap()` for `Option`s and `Result`s
2366 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2367     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
2368
2369     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2370         Some((OPTION_UNWRAP_USED, "an Option", "None"))
2371     } else if match_type(cx, obj_ty, &paths::RESULT) {
2372         Some((RESULT_UNWRAP_USED, "a Result", "Err"))
2373     } else {
2374         None
2375     };
2376
2377     if let Some((lint, kind, none_value)) = mess {
2378         span_lint_and_help(
2379             cx,
2380             lint,
2381             expr.span,
2382             &format!("used `unwrap()` on `{}` value", kind,),
2383             &format!(
2384                 "if you don't want to handle the `{}` case gracefully, consider \
2385                  using `expect()` to provide a better panic message",
2386                 none_value,
2387             ),
2388         );
2389     }
2390 }
2391
2392 /// lint use of `expect()` for `Option`s and `Result`s
2393 fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2394     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&expect_args[0]));
2395
2396     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2397         Some((OPTION_EXPECT_USED, "an Option", "None"))
2398     } else if match_type(cx, obj_ty, &paths::RESULT) {
2399         Some((RESULT_EXPECT_USED, "a Result", "Err"))
2400     } else {
2401         None
2402     };
2403
2404     if let Some((lint, kind, none_value)) = mess {
2405         span_lint_and_help(
2406             cx,
2407             lint,
2408             expr.span,
2409             &format!("used `expect()` on `{}` value", kind,),
2410             &format!("if this value is an `{}`, it will panic", none_value,),
2411         );
2412     }
2413 }
2414
2415 /// lint use of `ok().expect()` for `Result`s
2416 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2417     if_chain! {
2418         // lint if the caller of `ok()` is a `Result`
2419         if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT);
2420         let result_type = cx.tables.expr_ty(&ok_args[0]);
2421         if let Some(error_type) = get_error_type(cx, result_type);
2422         if has_debug_impl(error_type, cx);
2423
2424         then {
2425             span_lint_and_help(
2426                 cx,
2427                 OK_EXPECT,
2428                 expr.span,
2429                 "called `ok().expect()` on a `Result` value",
2430                 "you can call `expect()` directly on the `Result`",
2431             );
2432         }
2433     }
2434 }
2435
2436 /// lint use of `map().flatten()` for `Iterators`
2437 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2438     // lint if caller of `.map().flatten()` is an Iterator
2439     if match_trait_method(cx, expr, &paths::ITERATOR) {
2440         let msg = "called `map(..).flatten()` on an `Iterator`. \
2441                    This is more succinctly expressed by calling `.flat_map(..)`";
2442         let self_snippet = snippet(cx, map_args[0].span, "..");
2443         let func_snippet = snippet(cx, map_args[1].span, "..");
2444         let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
2445         span_lint_and_sugg(
2446             cx,
2447             MAP_FLATTEN,
2448             expr.span,
2449             msg,
2450             "try using `flat_map` instead",
2451             hint,
2452             Applicability::MachineApplicable,
2453         );
2454     }
2455 }
2456
2457 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2458 fn lint_map_unwrap_or_else<'a, 'tcx>(
2459     cx: &LateContext<'a, 'tcx>,
2460     expr: &'tcx hir::Expr<'_>,
2461     map_args: &'tcx [hir::Expr<'_>],
2462     unwrap_args: &'tcx [hir::Expr<'_>],
2463 ) {
2464     // lint if the caller of `map()` is an `Option`
2465     let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
2466     let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
2467
2468     if is_option || is_result {
2469         // Don't make a suggestion that may fail to compile due to mutably borrowing
2470         // the same variable twice.
2471         let map_mutated_vars = mutated_variables(&map_args[0], cx);
2472         let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2473         if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2474             if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2475                 return;
2476             }
2477         } else {
2478             return;
2479         }
2480
2481         // lint message
2482         let msg = if is_option {
2483             "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
2484              `map_or_else(g, f)` instead"
2485         } else {
2486             "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
2487              `.map_or_else(g, f)` instead"
2488         };
2489         // get snippets for args to map() and unwrap_or_else()
2490         let map_snippet = snippet(cx, map_args[1].span, "..");
2491         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2492         // lint, with note if neither arg is > 1 line and both map() and
2493         // unwrap_or_else() have the same span
2494         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2495         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2496         if same_span && !multiline {
2497             span_lint_and_note(
2498                 cx,
2499                 if is_option {
2500                     OPTION_MAP_UNWRAP_OR_ELSE
2501                 } else {
2502                     RESULT_MAP_UNWRAP_OR_ELSE
2503                 },
2504                 expr.span,
2505                 msg,
2506                 expr.span,
2507                 &format!(
2508                     "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
2509                     map_snippet, unwrap_snippet,
2510                 ),
2511             );
2512         } else if same_span && multiline {
2513             span_lint(
2514                 cx,
2515                 if is_option {
2516                     OPTION_MAP_UNWRAP_OR_ELSE
2517                 } else {
2518                     RESULT_MAP_UNWRAP_OR_ELSE
2519                 },
2520                 expr.span,
2521                 msg,
2522             );
2523         };
2524     }
2525 }
2526
2527 /// lint use of `_.map_or(None, _)` for `Option`s
2528 fn lint_map_or_none<'a, 'tcx>(
2529     cx: &LateContext<'a, 'tcx>,
2530     expr: &'tcx hir::Expr<'_>,
2531     map_or_args: &'tcx [hir::Expr<'_>],
2532 ) {
2533     if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
2534         // check if the first non-self argument to map_or() is None
2535         let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2536             match_qpath(qpath, &paths::OPTION_NONE)
2537         } else {
2538             false
2539         };
2540
2541         if map_or_arg_is_none {
2542             // lint message
2543             let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
2544                        `and_then(f)` instead";
2545             let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
2546             let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
2547             let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
2548             span_lint_and_sugg(
2549                 cx,
2550                 OPTION_MAP_OR_NONE,
2551                 expr.span,
2552                 msg,
2553                 "try using `and_then` instead",
2554                 hint,
2555                 Applicability::MachineApplicable,
2556             );
2557         }
2558     }
2559 }
2560
2561 /// Lint use of `_.and_then(|x| Some(y))` for `Option`s
2562 fn lint_option_and_then_some(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2563     const LINT_MSG: &str = "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`";
2564     const NO_OP_MSG: &str = "using `Option.and_then(Some)`, which is a no-op";
2565
2566     let ty = cx.tables.expr_ty(&args[0]);
2567     if !match_type(cx, ty, &paths::OPTION) {
2568         return;
2569     }
2570
2571     match args[1].kind {
2572         hir::ExprKind::Closure(_, _, body_id, closure_args_span, _) => {
2573             let closure_body = cx.tcx.hir().body(body_id);
2574             let closure_expr = remove_blocks(&closure_body.value);
2575             if_chain! {
2576                 if let hir::ExprKind::Call(ref some_expr, ref some_args) = closure_expr.kind;
2577                 if let hir::ExprKind::Path(ref qpath) = some_expr.kind;
2578                 if match_qpath(qpath, &paths::OPTION_SOME);
2579                 if some_args.len() == 1;
2580                 then {
2581                     let inner_expr = &some_args[0];
2582
2583                     if contains_return(inner_expr) {
2584                         return;
2585                     }
2586
2587                     let some_inner_snip = if inner_expr.span.from_expansion() {
2588                         snippet_with_macro_callsite(cx, inner_expr.span, "_")
2589                     } else {
2590                         snippet(cx, inner_expr.span, "_")
2591                     };
2592
2593                     let closure_args_snip = snippet(cx, closure_args_span, "..");
2594                     let option_snip = snippet(cx, args[0].span, "..");
2595                     let note = format!("{}.map({} {})", option_snip, closure_args_snip, some_inner_snip);
2596                     span_lint_and_sugg(
2597                         cx,
2598                         OPTION_AND_THEN_SOME,
2599                         expr.span,
2600                         LINT_MSG,
2601                         "try this",
2602                         note,
2603                         Applicability::MachineApplicable,
2604                     );
2605                 }
2606             }
2607         },
2608         // `_.and_then(Some)` case, which is no-op.
2609         hir::ExprKind::Path(ref qpath) => {
2610             if match_qpath(qpath, &paths::OPTION_SOME) {
2611                 let option_snip = snippet(cx, args[0].span, "..");
2612                 let note = format!("{}", option_snip);
2613                 span_lint_and_sugg(
2614                     cx,
2615                     OPTION_AND_THEN_SOME,
2616                     expr.span,
2617                     NO_OP_MSG,
2618                     "use the expression directly",
2619                     note,
2620                     Applicability::MachineApplicable,
2621                 );
2622             }
2623         },
2624         _ => {},
2625     }
2626 }
2627
2628 /// lint use of `filter().next()` for `Iterators`
2629 fn lint_filter_next<'a, 'tcx>(
2630     cx: &LateContext<'a, 'tcx>,
2631     expr: &'tcx hir::Expr<'_>,
2632     filter_args: &'tcx [hir::Expr<'_>],
2633 ) {
2634     // lint if caller of `.filter().next()` is an Iterator
2635     if match_trait_method(cx, expr, &paths::ITERATOR) {
2636         let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2637                    `.find(p)` instead.";
2638         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2639         if filter_snippet.lines().count() <= 1 {
2640             // add note if not multi-line
2641             span_lint_and_note(
2642                 cx,
2643                 FILTER_NEXT,
2644                 expr.span,
2645                 msg,
2646                 expr.span,
2647                 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2648             );
2649         } else {
2650             span_lint(cx, FILTER_NEXT, expr.span, msg);
2651         }
2652     }
2653 }
2654
2655 /// lint use of `skip_while().next()` for `Iterators`
2656 fn lint_skip_while_next<'a, 'tcx>(
2657     cx: &LateContext<'a, 'tcx>,
2658     expr: &'tcx hir::Expr<'_>,
2659     _skip_while_args: &'tcx [hir::Expr<'_>],
2660 ) {
2661     // lint if caller of `.skip_while().next()` is an Iterator
2662     if match_trait_method(cx, expr, &paths::ITERATOR) {
2663         span_lint_and_help(
2664             cx,
2665             SKIP_WHILE_NEXT,
2666             expr.span,
2667             "called `skip_while(p).next()` on an `Iterator`",
2668             "this is more succinctly expressed by calling `.find(!p)` instead",
2669         );
2670     }
2671 }
2672
2673 /// lint use of `filter().map()` for `Iterators`
2674 fn lint_filter_map<'a, 'tcx>(
2675     cx: &LateContext<'a, 'tcx>,
2676     expr: &'tcx hir::Expr<'_>,
2677     _filter_args: &'tcx [hir::Expr<'_>],
2678     _map_args: &'tcx [hir::Expr<'_>],
2679 ) {
2680     // lint if caller of `.filter().map()` is an Iterator
2681     if match_trait_method(cx, expr, &paths::ITERATOR) {
2682         let msg = "called `filter(p).map(q)` on an `Iterator`";
2683         let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2684         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2685     }
2686 }
2687
2688 /// lint use of `filter_map().next()` for `Iterators`
2689 fn lint_filter_map_next<'a, 'tcx>(
2690     cx: &LateContext<'a, 'tcx>,
2691     expr: &'tcx hir::Expr<'_>,
2692     filter_args: &'tcx [hir::Expr<'_>],
2693 ) {
2694     if match_trait_method(cx, expr, &paths::ITERATOR) {
2695         let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2696                    `.find_map(p)` instead.";
2697         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2698         if filter_snippet.lines().count() <= 1 {
2699             span_lint_and_note(
2700                 cx,
2701                 FILTER_MAP_NEXT,
2702                 expr.span,
2703                 msg,
2704                 expr.span,
2705                 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2706             );
2707         } else {
2708             span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2709         }
2710     }
2711 }
2712
2713 /// lint use of `find().map()` for `Iterators`
2714 fn lint_find_map<'a, 'tcx>(
2715     cx: &LateContext<'a, 'tcx>,
2716     expr: &'tcx hir::Expr<'_>,
2717     _find_args: &'tcx [hir::Expr<'_>],
2718     map_args: &'tcx [hir::Expr<'_>],
2719 ) {
2720     // lint if caller of `.filter().map()` is an Iterator
2721     if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2722         let msg = "called `find(p).map(q)` on an `Iterator`";
2723         let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2724         span_lint_and_help(cx, FIND_MAP, expr.span, msg, hint);
2725     }
2726 }
2727
2728 /// lint use of `filter_map().map()` for `Iterators`
2729 fn lint_filter_map_map<'a, 'tcx>(
2730     cx: &LateContext<'a, 'tcx>,
2731     expr: &'tcx hir::Expr<'_>,
2732     _filter_args: &'tcx [hir::Expr<'_>],
2733     _map_args: &'tcx [hir::Expr<'_>],
2734 ) {
2735     // lint if caller of `.filter().map()` is an Iterator
2736     if match_trait_method(cx, expr, &paths::ITERATOR) {
2737         let msg = "called `filter_map(p).map(q)` on an `Iterator`";
2738         let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2739         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2740     }
2741 }
2742
2743 /// lint use of `filter().flat_map()` for `Iterators`
2744 fn lint_filter_flat_map<'a, 'tcx>(
2745     cx: &LateContext<'a, 'tcx>,
2746     expr: &'tcx hir::Expr<'_>,
2747     _filter_args: &'tcx [hir::Expr<'_>],
2748     _map_args: &'tcx [hir::Expr<'_>],
2749 ) {
2750     // lint if caller of `.filter().flat_map()` is an Iterator
2751     if match_trait_method(cx, expr, &paths::ITERATOR) {
2752         let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
2753         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2754                     and filtering by returning `iter::empty()`";
2755         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2756     }
2757 }
2758
2759 /// lint use of `filter_map().flat_map()` for `Iterators`
2760 fn lint_filter_map_flat_map<'a, 'tcx>(
2761     cx: &LateContext<'a, 'tcx>,
2762     expr: &'tcx hir::Expr<'_>,
2763     _filter_args: &'tcx [hir::Expr<'_>],
2764     _map_args: &'tcx [hir::Expr<'_>],
2765 ) {
2766     // lint if caller of `.filter_map().flat_map()` is an Iterator
2767     if match_trait_method(cx, expr, &paths::ITERATOR) {
2768         let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
2769         let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2770                     and filtering by returning `iter::empty()`";
2771         span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2772     }
2773 }
2774
2775 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2776 fn lint_flat_map_identity<'a, 'tcx>(
2777     cx: &LateContext<'a, 'tcx>,
2778     expr: &'tcx hir::Expr<'_>,
2779     flat_map_args: &'tcx [hir::Expr<'_>],
2780     flat_map_span: Span,
2781 ) {
2782     if match_trait_method(cx, expr, &paths::ITERATOR) {
2783         let arg_node = &flat_map_args[1].kind;
2784
2785         let apply_lint = |message: &str| {
2786             span_lint_and_sugg(
2787                 cx,
2788                 FLAT_MAP_IDENTITY,
2789                 flat_map_span.with_hi(expr.span.hi()),
2790                 message,
2791                 "try",
2792                 "flatten()".to_string(),
2793                 Applicability::MachineApplicable,
2794             );
2795         };
2796
2797         if_chain! {
2798             if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2799             let body = cx.tcx.hir().body(*body_id);
2800
2801             if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2802             if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2803
2804             if path.segments.len() == 1;
2805             if path.segments[0].ident.as_str() == binding_ident.as_str();
2806
2807             then {
2808                 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2809             }
2810         }
2811
2812         if_chain! {
2813             if let hir::ExprKind::Path(ref qpath) = arg_node;
2814
2815             if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2816
2817             then {
2818                 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
2819             }
2820         }
2821     }
2822 }
2823
2824 /// lint searching an Iterator followed by `is_some()`
2825 fn lint_search_is_some<'a, 'tcx>(
2826     cx: &LateContext<'a, 'tcx>,
2827     expr: &'tcx hir::Expr<'_>,
2828     search_method: &str,
2829     search_args: &'tcx [hir::Expr<'_>],
2830     is_some_args: &'tcx [hir::Expr<'_>],
2831     method_span: Span,
2832 ) {
2833     // lint if caller of search is an Iterator
2834     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2835         let msg = format!(
2836             "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2837              expressed by calling `any()`.",
2838             search_method
2839         );
2840         let search_snippet = snippet(cx, search_args[1].span, "..");
2841         if search_snippet.lines().count() <= 1 {
2842             // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2843             // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
2844             let any_search_snippet = if_chain! {
2845                 if search_method == "find";
2846                 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
2847                 let closure_body = cx.tcx.hir().body(body_id);
2848                 if let Some(closure_arg) = closure_body.params.get(0);
2849                 then {
2850                     if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
2851                         Some(search_snippet.replacen('&', "", 1))
2852                     } else if let Some(name) = get_arg_name(&closure_arg.pat) {
2853                         Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
2854                     } else {
2855                         None
2856                     }
2857                 } else {
2858                     None
2859                 }
2860             };
2861             // add note if not multi-line
2862             span_lint_and_sugg(
2863                 cx,
2864                 SEARCH_IS_SOME,
2865                 method_span.with_hi(expr.span.hi()),
2866                 &msg,
2867                 "try this",
2868                 format!(
2869                     "any({})",
2870                     any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2871                 ),
2872                 Applicability::MachineApplicable,
2873             );
2874         } else {
2875             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2876         }
2877     }
2878 }
2879
2880 /// Used for `lint_binary_expr_with_method_call`.
2881 #[derive(Copy, Clone)]
2882 struct BinaryExprInfo<'a> {
2883     expr: &'a hir::Expr<'a>,
2884     chain: &'a hir::Expr<'a>,
2885     other: &'a hir::Expr<'a>,
2886     eq: bool,
2887 }
2888
2889 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2890 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2891     macro_rules! lint_with_both_lhs_and_rhs {
2892         ($func:ident, $cx:expr, $info:ident) => {
2893             if !$func($cx, $info) {
2894                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2895                 if $func($cx, $info) {
2896                     return;
2897                 }
2898             }
2899         };
2900     }
2901
2902     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2903     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2904     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2905     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2906 }
2907
2908 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2909 fn lint_chars_cmp(
2910     cx: &LateContext<'_, '_>,
2911     info: &BinaryExprInfo<'_>,
2912     chain_methods: &[&str],
2913     lint: &'static Lint,
2914     suggest: &str,
2915 ) -> bool {
2916     if_chain! {
2917         if let Some(args) = method_chain_args(info.chain, chain_methods);
2918         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2919         if arg_char.len() == 1;
2920         if let hir::ExprKind::Path(ref qpath) = fun.kind;
2921         if let Some(segment) = single_segment_path(qpath);
2922         if segment.ident.name == sym!(Some);
2923         then {
2924             let mut applicability = Applicability::MachineApplicable;
2925             let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2926
2927             if self_ty.kind != ty::Str {
2928                 return false;
2929             }
2930
2931             span_lint_and_sugg(
2932                 cx,
2933                 lint,
2934                 info.expr.span,
2935                 &format!("you should use the `{}` method", suggest),
2936                 "like this",
2937                 format!("{}{}.{}({})",
2938                         if info.eq { "" } else { "!" },
2939                         snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2940                         suggest,
2941                         snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2942                 applicability,
2943             );
2944
2945             return true;
2946         }
2947     }
2948
2949     false
2950 }
2951
2952 /// Checks for the `CHARS_NEXT_CMP` lint.
2953 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2954     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2955 }
2956
2957 /// Checks for the `CHARS_LAST_CMP` lint.
2958 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2959     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2960         true
2961     } else {
2962         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2963     }
2964 }
2965
2966 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2967 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2968     cx: &LateContext<'a, 'tcx>,
2969     info: &BinaryExprInfo<'_>,
2970     chain_methods: &[&str],
2971     lint: &'static Lint,
2972     suggest: &str,
2973 ) -> bool {
2974     if_chain! {
2975         if let Some(args) = method_chain_args(info.chain, chain_methods);
2976         if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2977         if let ast::LitKind::Char(c) = lit.node;
2978         then {
2979             let mut applicability = Applicability::MachineApplicable;
2980             span_lint_and_sugg(
2981                 cx,
2982                 lint,
2983                 info.expr.span,
2984                 &format!("you should use the `{}` method", suggest),
2985                 "like this",
2986                 format!("{}{}.{}('{}')",
2987                         if info.eq { "" } else { "!" },
2988                         snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2989                         suggest,
2990                         c),
2991                 applicability,
2992             );
2993
2994             true
2995         } else {
2996             false
2997         }
2998     }
2999 }
3000
3001 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3002 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3003     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3004 }
3005
3006 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3007 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3008     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3009         true
3010     } else {
3011         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3012     }
3013 }
3014
3015 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3016 fn lint_single_char_pattern<'a, 'tcx>(
3017     cx: &LateContext<'a, 'tcx>,
3018     _expr: &'tcx hir::Expr<'_>,
3019     arg: &'tcx hir::Expr<'_>,
3020 ) {
3021     if_chain! {
3022         if let hir::ExprKind::Lit(lit) = &arg.kind;
3023         if let ast::LitKind::Str(r, style) = lit.node;
3024         if r.as_str().len() == 1;
3025         then {
3026             let mut applicability = Applicability::MachineApplicable;
3027             let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
3028             let ch = if let ast::StrStyle::Raw(nhash) = style {
3029                 let nhash = nhash as usize;
3030                 // for raw string: r##"a"##
3031                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3032             } else {
3033                 // for regular string: "a"
3034                 &snip[1..(snip.len() - 1)]
3035             };
3036             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3037             span_lint_and_sugg(
3038                 cx,
3039                 SINGLE_CHAR_PATTERN,
3040                 arg.span,
3041                 "single-character string constant used as pattern",
3042                 "try using a `char` instead",
3043                 hint,
3044                 applicability,
3045             );
3046         }
3047     }
3048 }
3049
3050 /// Checks for the `USELESS_ASREF` lint.
3051 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3052     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3053     // check if the call is to the actual `AsRef` or `AsMut` trait
3054     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3055         // check if the type after `as_ref` or `as_mut` is the same as before
3056         let recvr = &as_ref_args[0];
3057         let rcv_ty = cx.tables.expr_ty(recvr);
3058         let res_ty = cx.tables.expr_ty(expr);
3059         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3060         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3061         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3062             // allow the `as_ref` or `as_mut` if it is followed by another method call
3063             if_chain! {
3064                 if let Some(parent) = get_parent_expr(cx, expr);
3065                 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.kind;
3066                 if span != &expr.span;
3067                 then {
3068                     return;
3069                 }
3070             }
3071
3072             let mut applicability = Applicability::MachineApplicable;
3073             span_lint_and_sugg(
3074                 cx,
3075                 USELESS_ASREF,
3076                 expr.span,
3077                 &format!("this call to `{}` does nothing", call_name),
3078                 "try this",
3079                 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
3080                 applicability,
3081             );
3082         }
3083     }
3084 }
3085
3086 fn ty_has_iter_method(cx: &LateContext<'_, '_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3087     has_iter_method(cx, self_ref_ty).map(|ty_name| {
3088         let mutbl = match self_ref_ty.kind {
3089             ty::Ref(_, _, mutbl) => mutbl,
3090             _ => unreachable!(),
3091         };
3092         let method_name = match mutbl {
3093             hir::Mutability::Not => "iter",
3094             hir::Mutability::Mut => "iter_mut",
3095         };
3096         (ty_name, method_name)
3097     })
3098 }
3099
3100 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3101     if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3102         return;
3103     }
3104     if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3105         span_lint_and_sugg(
3106             cx,
3107             INTO_ITER_ON_REF,
3108             method_span,
3109             &format!(
3110                 "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
3111                 method_name, kind,
3112             ),
3113             "call directly",
3114             method_name.to_string(),
3115             Applicability::MachineApplicable,
3116         );
3117     }
3118 }
3119
3120 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3121 fn lint_maybe_uninit(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3122     if_chain! {
3123         if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3124         if args.is_empty();
3125         if let hir::ExprKind::Path(ref path) = callee.kind;
3126         if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3127         if !is_maybe_uninit_ty_valid(cx, cx.tables.expr_ty_adjusted(outer));
3128         then {
3129             span_lint(
3130                 cx,
3131                 UNINIT_ASSUMED_INIT,
3132                 outer.span,
3133                 "this call for this type may be undefined behavior"
3134             );
3135         }
3136     }
3137 }
3138
3139 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
3140     match ty.kind {
3141         ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3142         ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3143         ty::Adt(ref adt, _) => {
3144             // needs to be a MaybeUninit
3145             match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT)
3146         },
3147         _ => false,
3148     }
3149 }
3150
3151 fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
3152     span_lint_and_help(
3153         cx,
3154         SUSPICIOUS_MAP,
3155         expr.span,
3156         "this call to `map()` won't have an effect on the call to `count()`",
3157         "make sure you did not confuse `map` with `filter` or `for_each`",
3158     );
3159 }
3160
3161 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3162 fn lint_option_as_ref_deref<'a, 'tcx>(
3163     cx: &LateContext<'a, 'tcx>,
3164     expr: &hir::Expr<'_>,
3165     as_ref_args: &[hir::Expr<'_>],
3166     map_args: &[hir::Expr<'_>],
3167     is_mut: bool,
3168 ) {
3169     let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3170     if !match_type(cx, option_ty, &paths::OPTION) {
3171         return;
3172     }
3173
3174     let deref_aliases: [&[&str]; 9] = [
3175         &paths::DEREF_TRAIT_METHOD,
3176         &paths::DEREF_MUT_TRAIT_METHOD,
3177         &paths::CSTRING_AS_C_STR,
3178         &paths::OS_STRING_AS_OS_STR,
3179         &paths::PATH_BUF_AS_PATH,
3180         &paths::STRING_AS_STR,
3181         &paths::STRING_AS_MUT_STR,
3182         &paths::VEC_AS_SLICE,
3183         &paths::VEC_AS_MUT_SLICE,
3184     ];
3185
3186     let is_deref = match map_args[1].kind {
3187         hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3188         hir::ExprKind::Closure(_, _, body_id, _, _) => {
3189             let closure_body = cx.tcx.hir().body(body_id);
3190             let closure_expr = remove_blocks(&closure_body.value);
3191             if_chain! {
3192                 if let hir::ExprKind::MethodCall(_, _, args) = &closure_expr.kind;
3193                 if args.len() == 1;
3194                 if let hir::ExprKind::Path(qpath) = &args[0].kind;
3195                 if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3196                 if closure_body.params[0].pat.hir_id == local_id;
3197                 let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3198                 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3199                 then {
3200                     let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3201                     deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3202                 } else {
3203                     false
3204                 }
3205             }
3206         },
3207
3208         _ => false,
3209     };
3210
3211     if is_deref {
3212         let current_method = if is_mut {
3213             ".as_mut().map(DerefMut::deref_mut)"
3214         } else {
3215             ".as_ref().map(Deref::deref)"
3216         };
3217         let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3218         let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3219         let suggestion = format!("try using {} instead", method_hint);
3220
3221         let msg = format!(
3222             "called `{0}` (or with one of deref aliases) on an Option value. \
3223              This can be done more directly by calling `{1}` instead",
3224             current_method, hint
3225         );
3226         span_lint_and_sugg(
3227             cx,
3228             OPTION_AS_REF_DEREF,
3229             expr.span,
3230             &msg,
3231             &suggestion,
3232             hint,
3233             Applicability::MachineApplicable,
3234         );
3235     }
3236 }
3237
3238 /// Given a `Result<T, E>` type, return its error type (`E`).
3239 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3240     match ty.kind {
3241         ty::Adt(_, substs) if match_type(cx, ty, &paths::RESULT) => substs.types().nth(1),
3242         _ => None,
3243     }
3244 }
3245
3246 /// This checks whether a given type is known to implement Debug.
3247 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
3248     cx.tcx
3249         .get_diagnostic_item(sym::debug_trait)
3250         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3251 }
3252
3253 enum Convention {
3254     Eq(&'static str),
3255     StartsWith(&'static str),
3256 }
3257
3258 #[rustfmt::skip]
3259 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3260     (Convention::Eq("new"), &[SelfKind::No]),
3261     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3262     (Convention::StartsWith("from_"), &[SelfKind::No]),
3263     (Convention::StartsWith("into_"), &[SelfKind::Value]),
3264     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3265     (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3266     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3267 ];
3268
3269 #[rustfmt::skip]
3270 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
3271     ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
3272     ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
3273     ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
3274     ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
3275     ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
3276     ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
3277     ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
3278     ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
3279     ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
3280     ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
3281     ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
3282     ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
3283     ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
3284     ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
3285     ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
3286     ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
3287     ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
3288     ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
3289     ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
3290     ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
3291     ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
3292     ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
3293     ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
3294     ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
3295     ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
3296     ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
3297     ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
3298     ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
3299     ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
3300     ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
3301 ];
3302
3303 #[rustfmt::skip]
3304 const PATTERN_METHODS: [(&str, usize); 17] = [
3305     ("contains", 1),
3306     ("starts_with", 1),
3307     ("ends_with", 1),
3308     ("find", 1),
3309     ("rfind", 1),
3310     ("split", 1),
3311     ("rsplit", 1),
3312     ("split_terminator", 1),
3313     ("rsplit_terminator", 1),
3314     ("splitn", 2),
3315     ("rsplitn", 2),
3316     ("matches", 1),
3317     ("rmatches", 1),
3318     ("match_indices", 1),
3319     ("rmatch_indices", 1),
3320     ("trim_start_matches", 1),
3321     ("trim_end_matches", 1),
3322 ];
3323
3324 #[derive(Clone, Copy, PartialEq, Debug)]
3325 enum SelfKind {
3326     Value,
3327     Ref,
3328     RefMut,
3329     No,
3330 }
3331
3332 impl SelfKind {
3333     fn matches<'a>(self, cx: &LateContext<'_, 'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3334         fn matches_value(parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3335             if ty == parent_ty {
3336                 true
3337             } else if ty.is_box() {
3338                 ty.boxed_ty() == parent_ty
3339             } else if ty.is_rc() || ty.is_arc() {
3340                 if let ty::Adt(_, substs) = ty.kind {
3341                     substs.types().next().map_or(false, |t| t == parent_ty)
3342                 } else {
3343                     false
3344                 }
3345             } else {
3346                 false
3347             }
3348         }
3349
3350         fn matches_ref<'a>(
3351             cx: &LateContext<'_, 'a>,
3352             mutability: hir::Mutability,
3353             parent_ty: Ty<'a>,
3354             ty: Ty<'a>,
3355         ) -> bool {
3356             if let ty::Ref(_, t, m) = ty.kind {
3357                 return m == mutability && t == parent_ty;
3358             }
3359
3360             let trait_path = match mutability {
3361                 hir::Mutability::Not => &paths::ASREF_TRAIT,
3362                 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3363             };
3364
3365             let trait_def_id = match get_trait_def_id(cx, trait_path) {
3366                 Some(did) => did,
3367                 None => return false,
3368             };
3369             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3370         }
3371
3372         match self {
3373             Self::Value => matches_value(parent_ty, ty),
3374             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3375             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3376             Self::No => ty != parent_ty,
3377         }
3378     }
3379
3380     #[must_use]
3381     fn description(self) -> &'static str {
3382         match self {
3383             Self::Value => "self by value",
3384             Self::Ref => "self by reference",
3385             Self::RefMut => "self by mutable reference",
3386             Self::No => "no self",
3387         }
3388     }
3389 }
3390
3391 impl Convention {
3392     #[must_use]
3393     fn check(&self, other: &str) -> bool {
3394         match *self {
3395             Self::Eq(this) => this == other,
3396             Self::StartsWith(this) => other.starts_with(this) && this != other,
3397         }
3398     }
3399 }
3400
3401 impl fmt::Display for Convention {
3402     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3403         match *self {
3404             Self::Eq(this) => this.fmt(f),
3405             Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3406         }
3407     }
3408 }
3409
3410 #[derive(Clone, Copy)]
3411 enum OutType {
3412     Unit,
3413     Bool,
3414     Any,
3415     Ref,
3416 }
3417
3418 impl OutType {
3419     fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FnRetTy<'_>) -> bool {
3420         let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3421         match (self, ty) {
3422             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3423             (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3424             (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3425             (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3426             (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3427             _ => false,
3428         }
3429     }
3430 }
3431
3432 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3433     if let hir::TyKind::Path(ref p) = ty.kind {
3434         match_qpath(p, &["bool"])
3435     } else {
3436         false
3437     }
3438 }
3439
3440 // Returns `true` if `expr` contains a return expression
3441 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3442     struct RetCallFinder {
3443         found: bool,
3444     }
3445
3446     impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3447         type Map = Map<'tcx>;
3448
3449         fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3450             if self.found {
3451                 return;
3452             }
3453             if let hir::ExprKind::Ret(..) = &expr.kind {
3454                 self.found = true;
3455             } else {
3456                 intravisit::walk_expr(self, expr);
3457             }
3458         }
3459
3460         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3461             intravisit::NestedVisitorMap::None
3462         }
3463     }
3464
3465     let mut visitor = RetCallFinder { found: false };
3466     visitor.visit_expr(expr);
3467     visitor.found
3468 }
3469
3470 fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3471     if_chain! {
3472         if args.len() == 2;
3473         if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.tables.expr_ty(&args[0]).kind;
3474         if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3475         if layout.is_zst();
3476         then {
3477             span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3478         }
3479     }
3480 }
3481
3482 fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3483     let ty = cx.tables.expr_ty(&args[0]);
3484
3485     if !match_type(cx, ty, &paths::FILE_TYPE) {
3486         return;
3487     }
3488
3489     let span: Span;
3490     let verb: &str;
3491     let lint_unary: &str;
3492     let help_unary: &str;
3493     if_chain! {
3494         if let Some(parent) = get_parent_expr(cx, expr);
3495         if let hir::ExprKind::Unary(op, _) = parent.kind;
3496         if op == hir::UnOp::UnNot;
3497         then {
3498             lint_unary = "!";
3499             verb = "denies";
3500             help_unary = "";
3501             span = parent.span;
3502         } else {
3503             lint_unary = "";
3504             verb = "covers";
3505             help_unary = "!";
3506             span = expr.span;
3507         }
3508     }
3509     let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3510     let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3511     span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, &help_msg);
3512 }