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