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