]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
Rename 'flat_map' → 'flat_map_identity'
[rust.git] / clippy_lints / src / methods / mod.rs
1 mod option_map_unwrap_or;
2 mod unnecessary_filter_map;
3
4 use std::borrow::Cow;
5 use std::fmt;
6 use std::iter;
7
8 use if_chain::if_chain;
9 use matches::matches;
10 use rustc::hir;
11 use rustc::hir::def::{DefKind, Res};
12 use rustc::hir::intravisit::{self, Visitor};
13 use rustc::lint::{in_external_macro, LateContext, LateLintPass, Lint, LintArray, LintContext, LintPass};
14 use rustc::ty::{self, Predicate, Ty};
15 use rustc::{declare_lint_pass, declare_tool_lint};
16 use rustc_errors::Applicability;
17 use syntax::ast;
18 use syntax::source_map::{BytePos, Span};
19 use syntax::symbol::LocalInternedString;
20
21 use crate::utils::paths;
22 use crate::utils::sugg;
23 use crate::utils::usage::mutated_variables;
24 use crate::utils::{
25     get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, implements_trait, in_macro, is_copy,
26     is_ctor_function, is_expn_of, is_self, is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path,
27     match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, remove_blocks, return_ty,
28     same_tys, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite, span_lint,
29     span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
30 };
31
32 declare_clippy_lint! {
33     /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
34     ///
35     /// **Why is this bad?** Usually it is better to handle the `None` case, or to
36     /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
37     /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
38     /// `Allow` by default.
39     ///
40     /// **Known problems:** None.
41     ///
42     /// **Example:**
43     ///
44     /// Using unwrap on an `Option`:
45     ///
46     /// ```rust
47     /// let opt = Some(1);
48     /// opt.unwrap();
49     /// ```
50     ///
51     /// Better:
52     ///
53     /// ```rust
54     /// let opt = Some(1);
55     /// opt.expect("more helpful message");
56     /// ```
57     pub OPTION_UNWRAP_USED,
58     restriction,
59     "using `Option.unwrap()`, which should at least get a better message using `expect()`"
60 }
61
62 declare_clippy_lint! {
63     /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
64     ///
65     /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
66     /// values. Normally, you want to implement more sophisticated error handling,
67     /// and propagate errors upwards with `try!`.
68     ///
69     /// Even if you want to panic on errors, not all `Error`s implement good
70     /// messages on display. Therefore, it may be beneficial to look at the places
71     /// where they may get displayed. Activate this lint to do just that.
72     ///
73     /// **Known problems:** None.
74     ///
75     /// **Example:**
76     /// Using unwrap on an `Option`:
77     ///
78     /// ```rust
79     /// let res: Result<usize, ()> = Ok(1);
80     /// res.unwrap();
81     /// ```
82     ///
83     /// Better:
84     ///
85     /// ```rust
86     /// let res: Result<usize, ()> = Ok(1);
87     /// res.expect("more helpful message");
88     /// ```
89     pub RESULT_UNWRAP_USED,
90     restriction,
91     "using `Result.unwrap()`, which might be better handled"
92 }
93
94 declare_clippy_lint! {
95     /// **What it does:** Checks for methods that should live in a trait
96     /// implementation of a `std` trait (see [llogiq's blog
97     /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
98     /// information) instead of an inherent implementation.
99     ///
100     /// **Why is this bad?** Implementing the traits improve ergonomics for users of
101     /// the code, often with very little cost. Also people seeing a `mul(...)`
102     /// method
103     /// may expect `*` to work equally, so you should have good reason to disappoint
104     /// them.
105     ///
106     /// **Known problems:** None.
107     ///
108     /// **Example:**
109     /// ```ignore
110     /// struct X;
111     /// impl X {
112     ///     fn add(&self, other: &X) -> X {
113     ///         ..
114     ///     }
115     /// }
116     /// ```
117     pub SHOULD_IMPLEMENT_TRAIT,
118     style,
119     "defining a method that should be implementing a std trait"
120 }
121
122 declare_clippy_lint! {
123     /// **What it does:** Checks for methods with certain name prefixes and which
124     /// doesn't match how self is taken. The actual rules are:
125     ///
126     /// |Prefix |`self` taken          |
127     /// |-------|----------------------|
128     /// |`as_`  |`&self` or `&mut self`|
129     /// |`from_`| none                 |
130     /// |`into_`|`self`                |
131     /// |`is_`  |`&self` or none       |
132     /// |`to_`  |`&self`               |
133     ///
134     /// **Why is this bad?** Consistency breeds readability. If you follow the
135     /// conventions, your users won't be surprised that they, e.g., need to supply a
136     /// mutable reference to a `as_..` function.
137     ///
138     /// **Known problems:** None.
139     ///
140     /// **Example:**
141     /// ```ignore
142     /// impl X {
143     ///     fn as_str(self) -> &str {
144     ///         ..
145     ///     }
146     /// }
147     /// ```
148     pub WRONG_SELF_CONVENTION,
149     style,
150     "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
151 }
152
153 declare_clippy_lint! {
154     /// **What it does:** This is the same as
155     /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
156     ///
157     /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
158     ///
159     /// **Known problems:** Actually *renaming* the function may break clients if
160     /// the function is part of the public interface. In that case, be mindful of
161     /// the stability guarantees you've given your users.
162     ///
163     /// **Example:**
164     /// ```rust
165     /// # struct X;
166     /// impl<'a> X {
167     ///     pub fn as_str(self) -> &'a str {
168     ///         "foo"
169     ///     }
170     /// }
171     /// ```
172     pub WRONG_PUB_SELF_CONVENTION,
173     restriction,
174     "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
175 }
176
177 declare_clippy_lint! {
178     /// **What it does:** Checks for usage of `ok().expect(..)`.
179     ///
180     /// **Why is this bad?** Because you usually call `expect()` on the `Result`
181     /// directly to get a better error message.
182     ///
183     /// **Known problems:** The error type needs to implement `Debug`
184     ///
185     /// **Example:**
186     /// ```ignore
187     /// x.ok().expect("why did I do this again?")
188     /// ```
189     pub OK_EXPECT,
190     style,
191     "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
192 }
193
194 declare_clippy_lint! {
195     /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
196     ///
197     /// **Why is this bad?** Readability, this can be written more concisely as
198     /// `_.map_or(_, _)`.
199     ///
200     /// **Known problems:** The order of the arguments is not in execution order
201     ///
202     /// **Example:**
203     /// ```rust
204     /// # let x = Some(1);
205     /// x.map(|a| a + 1).unwrap_or(0);
206     /// ```
207     pub OPTION_MAP_UNWRAP_OR,
208     pedantic,
209     "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as `map_or(a, f)`"
210 }
211
212 declare_clippy_lint! {
213     /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
214     ///
215     /// **Why is this bad?** Readability, this can be written more concisely as
216     /// `_.map_or_else(_, _)`.
217     ///
218     /// **Known problems:** The order of the arguments is not in execution order.
219     ///
220     /// **Example:**
221     /// ```rust
222     /// # let x = Some(1);
223     /// # fn some_function() -> usize { 1 }
224     /// x.map(|a| a + 1).unwrap_or_else(some_function);
225     /// ```
226     pub OPTION_MAP_UNWRAP_OR_ELSE,
227     pedantic,
228     "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `map_or_else(g, f)`"
229 }
230
231 declare_clippy_lint! {
232     /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
233     ///
234     /// **Why is this bad?** Readability, this can be written more concisely as
235     /// `result.ok().map_or_else(_, _)`.
236     ///
237     /// **Known problems:** None.
238     ///
239     /// **Example:**
240     /// ```rust
241     /// # let x: Result<usize, ()> = Ok(1);
242     /// # fn some_function(foo: ()) -> usize { 1 }
243     /// x.map(|a| a + 1).unwrap_or_else(some_function);
244     /// ```
245     pub RESULT_MAP_UNWRAP_OR_ELSE,
246     pedantic,
247     "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `.ok().map_or_else(g, f)`"
248 }
249
250 declare_clippy_lint! {
251     /// **What it does:** Checks for usage of `_.map_or(None, _)`.
252     ///
253     /// **Why is this bad?** Readability, this can be written more concisely as
254     /// `_.and_then(_)`.
255     ///
256     /// **Known problems:** The order of the arguments is not in execution order.
257     ///
258     /// **Example:**
259     /// ```ignore
260     /// opt.map_or(None, |a| a + 1)
261     /// ```
262     pub OPTION_MAP_OR_NONE,
263     style,
264     "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
265 }
266
267 declare_clippy_lint! {
268     /// **What it does:** Checks for usage of `_.filter(_).next()`.
269     ///
270     /// **Why is this bad?** Readability, this can be written more concisely as
271     /// `_.find(_)`.
272     ///
273     /// **Known problems:** None.
274     ///
275     /// **Example:**
276     /// ```rust
277     /// # let vec = vec![1];
278     /// vec.iter().filter(|x| **x == 0).next();
279     /// ```
280     pub FILTER_NEXT,
281     complexity,
282     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
283 }
284
285 declare_clippy_lint! {
286     /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
287     ///
288     /// **Why is this bad?** Readability, this can be written more concisely as a
289     /// single method call.
290     ///
291     /// **Known problems:**
292     ///
293     /// **Example:**
294     /// ```rust
295     /// let vec = vec![vec![1]];
296     /// vec.iter().map(|x| x.iter()).flatten();
297     /// ```
298     pub MAP_FLATTEN,
299     pedantic,
300     "using combinations of `flatten` and `map` which can usually be written as a single method call"
301 }
302
303 declare_clippy_lint! {
304     /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
305     /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
306     ///
307     /// **Why is this bad?** Readability, this can be written more concisely as a
308     /// single method call.
309     ///
310     /// **Known problems:** Often requires a condition + Option/Iterator creation
311     /// inside the closure.
312     ///
313     /// **Example:**
314     /// ```rust
315     /// let vec = vec![1];
316     /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
317     /// ```
318     pub FILTER_MAP,
319     pedantic,
320     "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
321 }
322
323 declare_clippy_lint! {
324     /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
325     ///
326     /// **Why is this bad?** Readability, this can be written more concisely as a
327     /// single method call.
328     ///
329     /// **Known problems:** None
330     ///
331     /// **Example:**
332     /// ```rust
333     ///  (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
334     /// ```
335     /// Can be written as
336     ///
337     /// ```rust
338     ///  (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
339     /// ```
340     pub FILTER_MAP_NEXT,
341     pedantic,
342     "using combination of `filter_map` and `next` which can usually be written as a single method call"
343 }
344
345 declare_clippy_lint! {
346     /// **What it does:** Checks for usage of `flat_map(|x| x)`.
347     ///
348     /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
349     ///
350     /// **Known problems:** None
351     ///
352     /// **Example:**
353     /// ```rust
354     /// iter.flat_map(|x| x)
355     /// ```
356     /// Can be written as
357     /// ```rust
358     /// iter.flatten()
359     /// ```
360     pub FLAT_MAP_IDENTITY,
361     pedantic,
362     "call to `flat_map` where `flatten` is sufficient"
363 }
364
365 declare_clippy_lint! {
366     /// **What it does:** Checks for usage of `_.find(_).map(_)`.
367     ///
368     /// **Why is this bad?** Readability, this can be written more concisely as a
369     /// single method call.
370     ///
371     /// **Known problems:** Often requires a condition + Option/Iterator creation
372     /// inside the closure.
373     ///
374     /// **Example:**
375     /// ```rust
376     ///  (0..3).find(|x| *x == 2).map(|x| x * 2);
377     /// ```
378     /// Can be written as
379     /// ```rust
380     ///  (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
381     /// ```
382     pub FIND_MAP,
383     pedantic,
384     "using a combination of `find` and `map` can usually be written as a single method call"
385 }
386
387 declare_clippy_lint! {
388     /// **What it does:** Checks for an iterator search (such as `find()`,
389     /// `position()`, or `rposition()`) followed by a call to `is_some()`.
390     ///
391     /// **Why is this bad?** Readability, this can be written more concisely as
392     /// `_.any(_)`.
393     ///
394     /// **Known problems:** None.
395     ///
396     /// **Example:**
397     /// ```rust
398     /// # let vec = vec![1];
399     /// vec.iter().find(|x| **x == 0).is_some();
400     /// ```
401     pub SEARCH_IS_SOME,
402     complexity,
403     "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
404 }
405
406 declare_clippy_lint! {
407     /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
408     /// if it starts with a given char.
409     ///
410     /// **Why is this bad?** Readability, this can be written more concisely as
411     /// `_.starts_with(_)`.
412     ///
413     /// **Known problems:** None.
414     ///
415     /// **Example:**
416     /// ```rust
417     /// let name = "foo";
418     /// name.chars().next() == Some('_');
419     /// ```
420     pub CHARS_NEXT_CMP,
421     complexity,
422     "using `.chars().next()` to check if a string starts with a char"
423 }
424
425 declare_clippy_lint! {
426     /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
427     /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
428     /// `unwrap_or_default` instead.
429     ///
430     /// **Why is this bad?** The function will always be called and potentially
431     /// allocate an object acting as the default.
432     ///
433     /// **Known problems:** If the function has side-effects, not calling it will
434     /// change the semantic of the program, but you shouldn't rely on that anyway.
435     ///
436     /// **Example:**
437     /// ```rust
438     /// # let foo = Some(String::new());
439     /// foo.unwrap_or(String::new());
440     /// ```
441     /// this can instead be written:
442     /// ```rust
443     /// # let foo = Some(String::new());
444     /// foo.unwrap_or_else(String::new);
445     /// ```
446     /// or
447     /// ```rust
448     /// # let foo = Some(String::new());
449     /// foo.unwrap_or_default();
450     /// ```
451     pub OR_FUN_CALL,
452     perf,
453     "using any `*or` method with a function call, which suggests `*or_else`"
454 }
455
456 declare_clippy_lint! {
457     /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
458     /// etc., and suggests to use `unwrap_or_else` instead
459     ///
460     /// **Why is this bad?** The function will always be called.
461     ///
462     /// **Known problems:** If the function has side-effects, not calling it will
463     /// change the semantics of the program, but you shouldn't rely on that anyway.
464     ///
465     /// **Example:**
466     /// ```rust
467     /// # let foo = Some(String::new());
468     /// # let err_code = "418";
469     /// # let err_msg = "I'm a teapot";
470     /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
471     /// ```
472     /// or
473     /// ```rust
474     /// # let foo = Some(String::new());
475     /// # let err_code = "418";
476     /// # let err_msg = "I'm a teapot";
477     /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
478     /// ```
479     /// this can instead be written:
480     /// ```rust
481     /// # let foo = Some(String::new());
482     /// # let err_code = "418";
483     /// # let err_msg = "I'm a teapot";
484     /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
485     /// ```
486     pub EXPECT_FUN_CALL,
487     perf,
488     "using any `expect` method with a function call"
489 }
490
491 declare_clippy_lint! {
492     /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
493     ///
494     /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
495     /// generics, not for using the `clone` method on a concrete type.
496     ///
497     /// **Known problems:** None.
498     ///
499     /// **Example:**
500     /// ```rust
501     /// 42u64.clone();
502     /// ```
503     pub CLONE_ON_COPY,
504     complexity,
505     "using `clone` on a `Copy` type"
506 }
507
508 declare_clippy_lint! {
509     /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
510     /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
511     /// function syntax instead (e.g., `Rc::clone(foo)`).
512     ///
513     /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
514     /// can obscure the fact that only the pointer is being cloned, not the underlying
515     /// data.
516     ///
517     /// **Example:**
518     /// ```rust
519     /// # use std::rc::Rc;
520     /// let x = Rc::new(1);
521     /// x.clone();
522     /// ```
523     pub CLONE_ON_REF_PTR,
524     restriction,
525     "using 'clone' on a ref-counted pointer"
526 }
527
528 declare_clippy_lint! {
529     /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
530     ///
531     /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
532     /// cloning the underlying `T`.
533     ///
534     /// **Known problems:** None.
535     ///
536     /// **Example:**
537     /// ```rust
538     /// fn main() {
539     ///     let x = vec![1];
540     ///     let y = &&x;
541     ///     let z = y.clone();
542     ///     println!("{:p} {:p}", *y, z); // prints out the same pointer
543     /// }
544     /// ```
545     pub CLONE_DOUBLE_REF,
546     correctness,
547     "using `clone` on `&&T`"
548 }
549
550 declare_clippy_lint! {
551     /// **What it does:** Checks for `new` not returning `Self`.
552     ///
553     /// **Why is this bad?** As a convention, `new` methods are used to make a new
554     /// instance of a type.
555     ///
556     /// **Known problems:** None.
557     ///
558     /// **Example:**
559     /// ```ignore
560     /// impl Foo {
561     ///     fn new(..) -> NotAFoo {
562     ///     }
563     /// }
564     /// ```
565     pub NEW_RET_NO_SELF,
566     style,
567     "not returning `Self` in a `new` method"
568 }
569
570 declare_clippy_lint! {
571     /// **What it does:** Checks for string methods that receive a single-character
572     /// `str` as an argument, e.g., `_.split("x")`.
573     ///
574     /// **Why is this bad?** Performing these methods using a `char` is faster than
575     /// using a `str`.
576     ///
577     /// **Known problems:** Does not catch multi-byte unicode characters.
578     ///
579     /// **Example:**
580     /// `_.split("x")` could be `_.split('x')`
581     pub SINGLE_CHAR_PATTERN,
582     perf,
583     "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
584 }
585
586 declare_clippy_lint! {
587     /// **What it does:** Checks for getting the inner pointer of a temporary
588     /// `CString`.
589     ///
590     /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
591     /// as the `CString` is alive.
592     ///
593     /// **Known problems:** None.
594     ///
595     /// **Example:**
596     /// ```rust,ignore
597     /// let c_str = CString::new("foo").unwrap().as_ptr();
598     /// unsafe {
599     ///     call_some_ffi_func(c_str);
600     /// }
601     /// ```
602     /// Here `c_str` point to a freed address. The correct use would be:
603     /// ```rust,ignore
604     /// let c_str = CString::new("foo").unwrap();
605     /// unsafe {
606     ///     call_some_ffi_func(c_str.as_ptr());
607     /// }
608     /// ```
609     pub TEMPORARY_CSTRING_AS_PTR,
610     correctness,
611     "getting the inner pointer of a temporary `CString`"
612 }
613
614 declare_clippy_lint! {
615     /// **What it does:** Checks for use of `.iter().nth()` (and the related
616     /// `.iter_mut().nth()`) on standard library types with O(1) element access.
617     ///
618     /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
619     /// readable.
620     ///
621     /// **Known problems:** None.
622     ///
623     /// **Example:**
624     /// ```rust
625     /// let some_vec = vec![0, 1, 2, 3];
626     /// let bad_vec = some_vec.iter().nth(3);
627     /// let bad_slice = &some_vec[..].iter().nth(3);
628     /// ```
629     /// The correct use would be:
630     /// ```rust
631     /// let some_vec = vec![0, 1, 2, 3];
632     /// let bad_vec = some_vec.get(3);
633     /// let bad_slice = &some_vec[..].get(3);
634     /// ```
635     pub ITER_NTH,
636     perf,
637     "using `.iter().nth()` on a standard library type with O(1) element access"
638 }
639
640 declare_clippy_lint! {
641     /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
642     ///
643     /// **Why is this bad?** `.nth(x)` is cleaner
644     ///
645     /// **Known problems:** None.
646     ///
647     /// **Example:**
648     /// ```rust
649     /// let some_vec = vec![0, 1, 2, 3];
650     /// let bad_vec = some_vec.iter().skip(3).next();
651     /// let bad_slice = &some_vec[..].iter().skip(3).next();
652     /// ```
653     /// The correct use would be:
654     /// ```rust
655     /// let some_vec = vec![0, 1, 2, 3];
656     /// let bad_vec = some_vec.iter().nth(3);
657     /// let bad_slice = &some_vec[..].iter().nth(3);
658     /// ```
659     pub ITER_SKIP_NEXT,
660     style,
661     "using `.skip(x).next()` on an iterator"
662 }
663
664 declare_clippy_lint! {
665     /// **What it does:** Checks for use of `.get().unwrap()` (or
666     /// `.get_mut().unwrap`) on a standard library type which implements `Index`
667     ///
668     /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
669     /// concise.
670     ///
671     /// **Known problems:** Not a replacement for error handling: Using either
672     /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
673     /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
674     /// temporary placeholder for dealing with the `Option` type, then this does
675     /// not mitigate the need for error handling. If there is a chance that `.get()`
676     /// will be `None` in your program, then it is advisable that the `None` case
677     /// is handled in a future refactor instead of using `.unwrap()` or the Index
678     /// trait.
679     ///
680     /// **Example:**
681     /// ```rust
682     /// let mut some_vec = vec![0, 1, 2, 3];
683     /// let last = some_vec.get(3).unwrap();
684     /// *some_vec.get_mut(0).unwrap() = 1;
685     /// ```
686     /// The correct use would be:
687     /// ```rust
688     /// let mut some_vec = vec![0, 1, 2, 3];
689     /// let last = some_vec[3];
690     /// some_vec[0] = 1;
691     /// ```
692     pub GET_UNWRAP,
693     restriction,
694     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
695 }
696
697 declare_clippy_lint! {
698     /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
699     /// `&str` or `String`.
700     ///
701     /// **Why is this bad?** `.push_str(s)` is clearer
702     ///
703     /// **Known problems:** None.
704     ///
705     /// **Example:**
706     /// ```rust
707     /// let abc = "abc";
708     /// let def = String::from("def");
709     /// let mut s = String::new();
710     /// s.extend(abc.chars());
711     /// s.extend(def.chars());
712     /// ```
713     /// The correct use would be:
714     /// ```rust
715     /// let abc = "abc";
716     /// let def = String::from("def");
717     /// let mut s = String::new();
718     /// s.push_str(abc);
719     /// s.push_str(&def);
720     /// ```
721     pub STRING_EXTEND_CHARS,
722     style,
723     "using `x.extend(s.chars())` where s is a `&str` or `String`"
724 }
725
726 declare_clippy_lint! {
727     /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
728     /// create a `Vec`.
729     ///
730     /// **Why is this bad?** `.to_vec()` is clearer
731     ///
732     /// **Known problems:** None.
733     ///
734     /// **Example:**
735     /// ```rust
736     /// let s = [1, 2, 3, 4, 5];
737     /// let s2: Vec<isize> = s[..].iter().cloned().collect();
738     /// ```
739     /// The better use would be:
740     /// ```rust
741     /// let s = [1, 2, 3, 4, 5];
742     /// let s2: Vec<isize> = s.to_vec();
743     /// ```
744     pub ITER_CLONED_COLLECT,
745     style,
746     "using `.cloned().collect()` on slice to create a `Vec`"
747 }
748
749 declare_clippy_lint! {
750     /// **What it does:** Checks for usage of `.chars().last()` or
751     /// `.chars().next_back()` on a `str` to check if it ends with a given char.
752     ///
753     /// **Why is this bad?** Readability, this can be written more concisely as
754     /// `_.ends_with(_)`.
755     ///
756     /// **Known problems:** None.
757     ///
758     /// **Example:**
759     /// ```ignore
760     /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
761     /// ```
762     pub CHARS_LAST_CMP,
763     style,
764     "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
765 }
766
767 declare_clippy_lint! {
768     /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
769     /// types before and after the call are the same.
770     ///
771     /// **Why is this bad?** The call is unnecessary.
772     ///
773     /// **Known problems:** None.
774     ///
775     /// **Example:**
776     /// ```rust
777     /// # fn do_stuff(x: &[i32]) {}
778     /// let x: &[i32] = &[1, 2, 3, 4, 5];
779     /// do_stuff(x.as_ref());
780     /// ```
781     /// The correct use would be:
782     /// ```rust
783     /// # fn do_stuff(x: &[i32]) {}
784     /// let x: &[i32] = &[1, 2, 3, 4, 5];
785     /// do_stuff(x);
786     /// ```
787     pub USELESS_ASREF,
788     complexity,
789     "using `as_ref` where the types before and after the call are the same"
790 }
791
792 declare_clippy_lint! {
793     /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
794     /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
795     /// `sum` or `product`.
796     ///
797     /// **Why is this bad?** Readability.
798     ///
799     /// **Known problems:** False positive in pattern guards. Will be resolved once
800     /// non-lexical lifetimes are stable.
801     ///
802     /// **Example:**
803     /// ```rust
804     /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
805     /// ```
806     /// This could be written as:
807     /// ```rust
808     /// let _ = (0..3).any(|x| x > 2);
809     /// ```
810     pub UNNECESSARY_FOLD,
811     style,
812     "using `fold` when a more succinct alternative exists"
813 }
814
815 declare_clippy_lint! {
816     /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
817     /// More specifically it checks if the closure provided is only performing one of the
818     /// filter or map operations and suggests the appropriate option.
819     ///
820     /// **Why is this bad?** Complexity. The intent is also clearer if only a single
821     /// operation is being performed.
822     ///
823     /// **Known problems:** None
824     ///
825     /// **Example:**
826     /// ```rust
827     /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
828     /// ```
829     /// As there is no transformation of the argument this could be written as:
830     /// ```rust
831     /// let _ = (0..3).filter(|&x| x > 2);
832     /// ```
833     ///
834     /// ```rust
835     /// let _ = (0..4).filter_map(i32::checked_abs);
836     /// ```
837     /// As there is no conditional check on the argument this could be written as:
838     /// ```rust
839     /// let _ = (0..4).map(i32::checked_abs);
840     /// ```
841     pub UNNECESSARY_FILTER_MAP,
842     complexity,
843     "using `filter_map` when a more succinct alternative exists"
844 }
845
846 declare_clippy_lint! {
847     /// **What it does:** Checks for `into_iter` calls on types which should be replaced by `iter` or
848     /// `iter_mut`.
849     ///
850     /// **Why is this bad?** Arrays and `PathBuf` do not yet have an `into_iter` method which move out
851     /// their content into an iterator. Auto-referencing resolves the `into_iter` call to its reference
852     /// instead, like `<&[T; N] as IntoIterator>::into_iter`, which just iterates over item references
853     /// like calling `iter` would. Furthermore, when the standard library actually
854     /// [implements the `into_iter` method](https://github.com/rust-lang/rust/issues/25725) which moves
855     /// the content out of the array, the original use of `into_iter` got inferred with the wrong type
856     /// and the code will be broken.
857     ///
858     /// **Known problems:** None
859     ///
860     /// **Example:**
861     ///
862     /// ```rust
863     /// let _ = [1, 2, 3].into_iter().map(|x| *x).collect::<Vec<u32>>();
864     /// ```
865     pub INTO_ITER_ON_ARRAY,
866     correctness,
867     "using `.into_iter()` on an array"
868 }
869
870 declare_clippy_lint! {
871     /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
872     /// or `iter_mut`.
873     ///
874     /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
875     /// content into the resulting iterator, which is confusing. It is better just call `iter` or
876     /// `iter_mut` directly.
877     ///
878     /// **Known problems:** None
879     ///
880     /// **Example:**
881     ///
882     /// ```rust
883     /// let _ = (&vec![3, 4, 5]).into_iter();
884     /// ```
885     pub INTO_ITER_ON_REF,
886     style,
887     "using `.into_iter()` on a reference"
888 }
889
890 declare_lint_pass!(Methods => [
891     OPTION_UNWRAP_USED,
892     RESULT_UNWRAP_USED,
893     SHOULD_IMPLEMENT_TRAIT,
894     WRONG_SELF_CONVENTION,
895     WRONG_PUB_SELF_CONVENTION,
896     OK_EXPECT,
897     OPTION_MAP_UNWRAP_OR,
898     OPTION_MAP_UNWRAP_OR_ELSE,
899     RESULT_MAP_UNWRAP_OR_ELSE,
900     OPTION_MAP_OR_NONE,
901     OR_FUN_CALL,
902     EXPECT_FUN_CALL,
903     CHARS_NEXT_CMP,
904     CHARS_LAST_CMP,
905     CLONE_ON_COPY,
906     CLONE_ON_REF_PTR,
907     CLONE_DOUBLE_REF,
908     NEW_RET_NO_SELF,
909     SINGLE_CHAR_PATTERN,
910     SEARCH_IS_SOME,
911     TEMPORARY_CSTRING_AS_PTR,
912     FILTER_NEXT,
913     FILTER_MAP,
914     FILTER_MAP_NEXT,
915     FLAT_MAP_IDENTITY,
916     FIND_MAP,
917     MAP_FLATTEN,
918     ITER_NTH,
919     ITER_SKIP_NEXT,
920     GET_UNWRAP,
921     STRING_EXTEND_CHARS,
922     ITER_CLONED_COLLECT,
923     USELESS_ASREF,
924     UNNECESSARY_FOLD,
925     UNNECESSARY_FILTER_MAP,
926     INTO_ITER_ON_ARRAY,
927     INTO_ITER_ON_REF,
928 ]);
929
930 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
931     #[allow(clippy::cognitive_complexity)]
932     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
933         if in_macro(expr.span) {
934             return;
935         }
936
937         let (method_names, arg_lists) = method_calls(expr, 2);
938         let method_names: Vec<LocalInternedString> = method_names.iter().map(|s| s.as_str()).collect();
939         let method_names: Vec<&str> = method_names.iter().map(std::convert::AsRef::as_ref).collect();
940
941         match method_names.as_slice() {
942             ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
943             ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
944             ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
945             ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
946             ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0]),
947             ["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
948             ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
949             ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
950             ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
951             ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
952             ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
953             ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
954             ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
955             ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
956             ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0]),
957             ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
958             ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0]),
959             ["is_some", "position"] => lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0]),
960             ["is_some", "rposition"] => lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0]),
961             ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
962             ["as_ptr", "unwrap"] | ["as_ptr", "expect"] => {
963                 lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0])
964             },
965             ["nth", "iter"] => lint_iter_nth(cx, expr, arg_lists[1], false),
966             ["nth", "iter_mut"] => lint_iter_nth(cx, expr, arg_lists[1], true),
967             ["next", "skip"] => lint_iter_skip_next(cx, expr),
968             ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
969             ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
970             ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
971             ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0]),
972             ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
973             _ => {},
974         }
975
976         match expr.node {
977             hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
978                 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
979                 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
980
981                 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
982                 if args.len() == 1 && method_call.ident.name == sym!(clone) {
983                     lint_clone_on_copy(cx, expr, &args[0], self_ty);
984                     lint_clone_on_ref_ptr(cx, expr, &args[0]);
985                 }
986
987                 match self_ty.sty {
988                     ty::Ref(_, ty, _) if ty.sty == ty::Str => {
989                         for &(method, pos) in &PATTERN_METHODS {
990                             if method_call.ident.name.as_str() == method && args.len() > pos {
991                                 lint_single_char_pattern(cx, expr, &args[pos]);
992                             }
993                         }
994                     },
995                     ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
996                         lint_into_iter(cx, expr, self_ty, *method_span);
997                     },
998                     _ => (),
999                 }
1000             },
1001             hir::ExprKind::Binary(op, ref lhs, ref rhs)
1002                 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1003             {
1004                 let mut info = BinaryExprInfo {
1005                     expr,
1006                     chain: lhs,
1007                     other: rhs,
1008                     eq: op.node == hir::BinOpKind::Eq,
1009                 };
1010                 lint_binary_expr_with_method_call(cx, &mut info);
1011             }
1012             _ => (),
1013         }
1014     }
1015
1016     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
1017         if in_external_macro(cx.sess(), implitem.span) {
1018             return;
1019         }
1020         let name = implitem.ident.name.as_str();
1021         let parent = cx.tcx.hir().get_parent_item(implitem.hir_id);
1022         let item = cx.tcx.hir().expect_item(parent);
1023         let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1024         let ty = cx.tcx.type_of(def_id);
1025         if_chain! {
1026             if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
1027             if let Some(first_arg_ty) = sig.decl.inputs.get(0);
1028             if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1029             if let hir::ItemKind::Impl(_, _, _, _, None, ref self_ty, _) = item.node;
1030             then {
1031                 if cx.access_levels.is_exported(implitem.hir_id) {
1032                 // check missing trait implementations
1033                     for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
1034                         if name == method_name &&
1035                         sig.decl.inputs.len() == n_args &&
1036                         out_type.matches(cx, &sig.decl.output) &&
1037                         self_kind.matches(cx, first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
1038                             span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
1039                                 "defining a method called `{}` on this type; consider implementing \
1040                                 the `{}` trait or choosing a less ambiguous name", name, trait_name));
1041                         }
1042                     }
1043                 }
1044
1045                 // check conventions w.r.t. conversion method names and predicates
1046                 let is_copy = is_copy(cx, ty);
1047                 for &(ref conv, self_kinds) in &CONVENTIONS {
1048                     if conv.check(&name) {
1049                         if !self_kinds
1050                                 .iter()
1051                                 .any(|k| k.matches(cx, first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics)) {
1052                             let lint = if item.vis.node.is_pub() {
1053                                 WRONG_PUB_SELF_CONVENTION
1054                             } else {
1055                                 WRONG_SELF_CONVENTION
1056                             };
1057                             span_lint(cx,
1058                                       lint,
1059                                       first_arg.pat.span,
1060                                       &format!("methods called `{}` usually take {}; consider choosing a less \
1061                                                 ambiguous name",
1062                                                conv,
1063                                                &self_kinds.iter()
1064                                                           .map(|k| k.description())
1065                                                           .collect::<Vec<_>>()
1066                                                           .join(" or ")));
1067                         }
1068
1069                         // Only check the first convention to match (CONVENTIONS should be listed from most to least
1070                         // specific)
1071                         break;
1072                     }
1073                 }
1074             }
1075         }
1076
1077         if let hir::ImplItemKind::Method(_, _) = implitem.node {
1078             let ret_ty = return_ty(cx, implitem.hir_id);
1079
1080             // walk the return type and check for Self (this does not check associated types)
1081             for inner_type in ret_ty.walk() {
1082                 if same_tys(cx, ty, inner_type) {
1083                     return;
1084                 }
1085             }
1086
1087             // if return type is impl trait, check the associated types
1088             if let ty::Opaque(def_id, _) = ret_ty.sty {
1089                 // one of the associated types must be Self
1090                 for predicate in &cx.tcx.predicates_of(def_id).predicates {
1091                     match predicate {
1092                         (Predicate::Projection(poly_projection_predicate), _) => {
1093                             let binder = poly_projection_predicate.ty();
1094                             let associated_type = binder.skip_binder();
1095                             let associated_type_is_self_type = same_tys(cx, ty, associated_type);
1096
1097                             // if the associated type is self, early return and do not trigger lint
1098                             if associated_type_is_self_type {
1099                                 return;
1100                             }
1101                         },
1102                         (_, _) => {},
1103                     }
1104                 }
1105             }
1106
1107             if name == "new" && !same_tys(cx, ret_ty, ty) {
1108                 span_lint(
1109                     cx,
1110                     NEW_RET_NO_SELF,
1111                     implitem.span,
1112                     "methods called `new` usually return `Self`",
1113                 );
1114             }
1115         }
1116     }
1117 }
1118
1119 /// Checks for the `OR_FUN_CALL` lint.
1120 #[allow(clippy::too_many_lines)]
1121 fn lint_or_fun_call<'a, 'tcx>(
1122     cx: &LateContext<'a, 'tcx>,
1123     expr: &hir::Expr,
1124     method_span: Span,
1125     name: &str,
1126     args: &'tcx [hir::Expr],
1127 ) {
1128     // Searches an expression for method calls or function calls that aren't ctors
1129     struct FunCallFinder<'a, 'tcx> {
1130         cx: &'a LateContext<'a, 'tcx>,
1131         found: bool,
1132     }
1133
1134     impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1135         fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
1136             let call_found = match &expr.node {
1137                 // ignore enum and struct constructors
1138                 hir::ExprKind::Call(..) => !is_ctor_function(self.cx, expr),
1139                 hir::ExprKind::MethodCall(..) => true,
1140                 _ => false,
1141             };
1142
1143             if call_found {
1144                 // don't lint for constant values
1145                 let owner_def = self.cx.tcx.hir().get_parent_did(expr.hir_id);
1146                 let promotable = self
1147                     .cx
1148                     .tcx
1149                     .rvalue_promotable_map(owner_def)
1150                     .contains(&expr.hir_id.local_id);
1151                 if !promotable {
1152                     self.found |= true;
1153                 }
1154             }
1155
1156             if !self.found {
1157                 intravisit::walk_expr(self, expr);
1158             }
1159         }
1160
1161         fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1162             intravisit::NestedVisitorMap::None
1163         }
1164     }
1165
1166     /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1167     fn check_unwrap_or_default(
1168         cx: &LateContext<'_, '_>,
1169         name: &str,
1170         fun: &hir::Expr,
1171         self_expr: &hir::Expr,
1172         arg: &hir::Expr,
1173         or_has_args: bool,
1174         span: Span,
1175     ) -> bool {
1176         if or_has_args {
1177             return false;
1178         }
1179
1180         if name == "unwrap_or" {
1181             if let hir::ExprKind::Path(ref qpath) = fun.node {
1182                 let path = &*last_path_segment(qpath).ident.as_str();
1183
1184                 if ["default", "new"].contains(&path) {
1185                     let arg_ty = cx.tables.expr_ty(arg);
1186                     let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
1187                         default_trait_id
1188                     } else {
1189                         return false;
1190                     };
1191
1192                     if implements_trait(cx, arg_ty, default_trait_id, &[]) {
1193                         let mut applicability = Applicability::MachineApplicable;
1194                         span_lint_and_sugg(
1195                             cx,
1196                             OR_FUN_CALL,
1197                             span,
1198                             &format!("use of `{}` followed by a call to `{}`", name, path),
1199                             "try this",
1200                             format!(
1201                                 "{}.unwrap_or_default()",
1202                                 snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1203                             ),
1204                             applicability,
1205                         );
1206                         return true;
1207                     }
1208                 }
1209             }
1210         }
1211
1212         false
1213     }
1214
1215     /// Checks for `*or(foo())`.
1216     #[allow(clippy::too_many_arguments)]
1217     fn check_general_case<'a, 'tcx>(
1218         cx: &LateContext<'a, 'tcx>,
1219         name: &str,
1220         method_span: Span,
1221         fun_span: Span,
1222         self_expr: &hir::Expr,
1223         arg: &'tcx hir::Expr,
1224         or_has_args: bool,
1225         span: Span,
1226     ) {
1227         // (path, fn_has_argument, methods, suffix)
1228         let know_types: &[(&[_], _, &[_], _)] = &[
1229             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1230             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1231             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1232             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1233         ];
1234
1235         // early check if the name is one we care about
1236         if know_types.iter().all(|k| !k.2.contains(&name)) {
1237             return;
1238         }
1239
1240         let mut finder = FunCallFinder { cx: &cx, found: false };
1241         finder.visit_expr(&arg);
1242         if !finder.found {
1243             return;
1244         }
1245
1246         let self_ty = cx.tables.expr_ty(self_expr);
1247
1248         let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
1249             know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
1250         {
1251             (fn_has_arguments, poss, suffix)
1252         } else {
1253             return;
1254         };
1255
1256         if !poss.contains(&name) {
1257             return;
1258         }
1259
1260         let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1261             (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1262             (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1263             (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1264         };
1265         let span_replace_word = method_span.with_hi(span.hi());
1266         span_lint_and_sugg(
1267             cx,
1268             OR_FUN_CALL,
1269             span_replace_word,
1270             &format!("use of `{}` followed by a function call", name),
1271             "try this",
1272             format!("{}_{}({})", name, suffix, sugg),
1273             Applicability::HasPlaceholders,
1274         );
1275     }
1276
1277     if args.len() == 2 {
1278         match args[1].node {
1279             hir::ExprKind::Call(ref fun, ref or_args) => {
1280                 let or_has_args = !or_args.is_empty();
1281                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1282                     check_general_case(
1283                         cx,
1284                         name,
1285                         method_span,
1286                         fun.span,
1287                         &args[0],
1288                         &args[1],
1289                         or_has_args,
1290                         expr.span,
1291                     );
1292                 }
1293             },
1294             hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1295                 cx,
1296                 name,
1297                 method_span,
1298                 span,
1299                 &args[0],
1300                 &args[1],
1301                 !or_args.is_empty(),
1302                 expr.span,
1303             ),
1304             _ => {},
1305         }
1306     }
1307 }
1308
1309 /// Checks for the `EXPECT_FUN_CALL` lint.
1310 #[allow(clippy::too_many_lines)]
1311 fn lint_expect_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
1312     // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1313     // `&str`
1314     fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr) -> &'a hir::Expr {
1315         let mut arg_root = arg;
1316         loop {
1317             arg_root = match &arg_root.node {
1318                 hir::ExprKind::AddrOf(_, expr) => expr,
1319                 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1320                     if call_args.len() == 1
1321                         && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1322                         && {
1323                             let arg_type = cx.tables.expr_ty(&call_args[0]);
1324                             let base_type = walk_ptrs_ty(arg_type);
1325                             base_type.sty == ty::Str || match_type(cx, base_type, &paths::STRING)
1326                         }
1327                     {
1328                         &call_args[0]
1329                     } else {
1330                         break;
1331                     }
1332                 },
1333                 _ => break,
1334             };
1335         }
1336         arg_root
1337     }
1338
1339     // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1340     // converted to string.
1341     fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr) -> bool {
1342         let arg_ty = cx.tables.expr_ty(arg);
1343         if match_type(cx, arg_ty, &paths::STRING) {
1344             return false;
1345         }
1346         if let ty::Ref(ty::ReStatic, ty, ..) = arg_ty.sty {
1347             if ty.sty == ty::Str {
1348                 return false;
1349             }
1350         };
1351         true
1352     }
1353
1354     fn generate_format_arg_snippet(
1355         cx: &LateContext<'_, '_>,
1356         a: &hir::Expr,
1357         applicability: &mut Applicability,
1358     ) -> Vec<String> {
1359         if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
1360             if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
1361                 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
1362                     return format_arg_expr_tup
1363                         .iter()
1364                         .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1365                         .collect();
1366                 }
1367             }
1368         };
1369
1370         unreachable!()
1371     }
1372
1373     fn is_call(node: &hir::ExprKind) -> bool {
1374         match node {
1375             hir::ExprKind::AddrOf(_, expr) => {
1376                 is_call(&expr.node)
1377             },
1378             hir::ExprKind::Call(..)
1379             | hir::ExprKind::MethodCall(..)
1380             // These variants are debatable or require further examination
1381             | hir::ExprKind::Match(..)
1382             | hir::ExprKind::Block{ .. } => true,
1383             _ => false,
1384         }
1385     }
1386
1387     if args.len() != 2 || name != "expect" || !is_call(&args[1].node) {
1388         return;
1389     }
1390
1391     let receiver_type = cx.tables.expr_ty(&args[0]);
1392     let closure_args = if match_type(cx, receiver_type, &paths::OPTION) {
1393         "||"
1394     } else if match_type(cx, receiver_type, &paths::RESULT) {
1395         "|_|"
1396     } else {
1397         return;
1398     };
1399
1400     let arg_root = get_arg_root(cx, &args[1]);
1401
1402     let span_replace_word = method_span.with_hi(expr.span.hi());
1403
1404     let mut applicability = Applicability::MachineApplicable;
1405
1406     //Special handling for `format!` as arg_root
1407     if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.node {
1408         if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1 {
1409             if let hir::ExprKind::Call(_, format_args) = &inner_args[0].node {
1410                 let fmt_spec = &format_args[0];
1411                 let fmt_args = &format_args[1];
1412
1413                 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1414
1415                 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1416
1417                 let sugg = args.join(", ");
1418
1419                 span_lint_and_sugg(
1420                     cx,
1421                     EXPECT_FUN_CALL,
1422                     span_replace_word,
1423                     &format!("use of `{}` followed by a function call", name),
1424                     "try this",
1425                     format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1426                     applicability,
1427                 );
1428
1429                 return;
1430             }
1431         }
1432     }
1433
1434     let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1435     if requires_to_string(cx, arg_root) {
1436         arg_root_snippet.to_mut().push_str(".to_string()");
1437     }
1438
1439     span_lint_and_sugg(
1440         cx,
1441         EXPECT_FUN_CALL,
1442         span_replace_word,
1443         &format!("use of `{}` followed by a function call", name),
1444         "try this",
1445         format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1446         applicability,
1447     );
1448 }
1449
1450 /// Checks for the `CLONE_ON_COPY` lint.
1451 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty<'_>) {
1452     let ty = cx.tables.expr_ty(expr);
1453     if let ty::Ref(_, inner, _) = arg_ty.sty {
1454         if let ty::Ref(_, innermost, _) = inner.sty {
1455             span_lint_and_then(
1456                 cx,
1457                 CLONE_DOUBLE_REF,
1458                 expr.span,
1459                 "using `clone` on a double-reference; \
1460                  this will copy the reference instead of cloning the inner type",
1461                 |db| {
1462                     if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1463                         let mut ty = innermost;
1464                         let mut n = 0;
1465                         while let ty::Ref(_, inner, _) = ty.sty {
1466                             ty = inner;
1467                             n += 1;
1468                         }
1469                         let refs: String = iter::repeat('&').take(n + 1).collect();
1470                         let derefs: String = iter::repeat('*').take(n).collect();
1471                         let explicit = format!("{}{}::clone({})", refs, ty, snip);
1472                         db.span_suggestion(
1473                             expr.span,
1474                             "try dereferencing it",
1475                             format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1476                             Applicability::MaybeIncorrect,
1477                         );
1478                         db.span_suggestion(
1479                             expr.span,
1480                             "or try being explicit about what type to clone",
1481                             explicit,
1482                             Applicability::MaybeIncorrect,
1483                         );
1484                     }
1485                 },
1486             );
1487             return; // don't report clone_on_copy
1488         }
1489     }
1490
1491     if is_copy(cx, ty) {
1492         let snip;
1493         if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1494             // x.clone() might have dereferenced x, possibly through Deref impls
1495             if cx.tables.expr_ty(arg) == ty {
1496                 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1497             } else {
1498                 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1499                 match cx.tcx.hir().get(parent) {
1500                     hir::Node::Expr(parent) => match parent.node {
1501                         // &*x is a nop, &x.clone() is not
1502                         hir::ExprKind::AddrOf(..) |
1503                         // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1504                         hir::ExprKind::MethodCall(..) => return,
1505                         _ => {},
1506                     },
1507                     hir::Node::Stmt(stmt) => {
1508                         if let hir::StmtKind::Local(ref loc) = stmt.node {
1509                             if let hir::PatKind::Ref(..) = loc.pat.node {
1510                                 // let ref y = *x borrows x, let ref y = x.clone() does not
1511                                 return;
1512                             }
1513                         }
1514                     },
1515                     _ => {},
1516                 }
1517
1518                 let deref_count = cx
1519                     .tables
1520                     .expr_adjustments(arg)
1521                     .iter()
1522                     .filter(|adj| {
1523                         if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1524                             true
1525                         } else {
1526                             false
1527                         }
1528                     })
1529                     .count();
1530                 let derefs: String = iter::repeat('*').take(deref_count).collect();
1531                 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1532             }
1533         } else {
1534             snip = None;
1535         }
1536         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1537             if let Some((text, snip)) = snip {
1538                 db.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1539             }
1540         });
1541     }
1542 }
1543
1544 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr) {
1545     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1546
1547     if let ty::Adt(_, subst) = obj_ty.sty {
1548         let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1549             "Rc"
1550         } else if match_type(cx, obj_ty, &paths::ARC) {
1551             "Arc"
1552         } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1553             "Weak"
1554         } else {
1555             return;
1556         };
1557
1558         span_lint_and_sugg(
1559             cx,
1560             CLONE_ON_REF_PTR,
1561             expr.span,
1562             "using '.clone()' on a ref-counted pointer",
1563             "try this",
1564             format!(
1565                 "{}::<{}>::clone(&{})",
1566                 caller_type,
1567                 subst.type_at(0),
1568                 snippet(cx, arg.span, "_")
1569             ),
1570             Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
1571         );
1572     }
1573 }
1574
1575 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1576     let arg = &args[1];
1577     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1578         let target = &arglists[0][0];
1579         let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1580         let ref_str = if self_ty.sty == ty::Str {
1581             ""
1582         } else if match_type(cx, self_ty, &paths::STRING) {
1583             "&"
1584         } else {
1585             return;
1586         };
1587
1588         let mut applicability = Applicability::MachineApplicable;
1589         span_lint_and_sugg(
1590             cx,
1591             STRING_EXTEND_CHARS,
1592             expr.span,
1593             "calling `.extend(_.chars())`",
1594             "try this",
1595             format!(
1596                 "{}.push_str({}{})",
1597                 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
1598                 ref_str,
1599                 snippet_with_applicability(cx, target.span, "_", &mut applicability)
1600             ),
1601             applicability,
1602         );
1603     }
1604 }
1605
1606 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1607     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
1608     if match_type(cx, obj_ty, &paths::STRING) {
1609         lint_string_extend(cx, expr, args);
1610     }
1611 }
1612
1613 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1614     if_chain! {
1615         if let hir::ExprKind::Call(ref fun, ref args) = new.node;
1616         if args.len() == 1;
1617         if let hir::ExprKind::Path(ref path) = fun.node;
1618         if let Res::Def(DefKind::Method, did) = cx.tables.qpath_res(path, fun.hir_id);
1619         if match_def_path(cx, did, &paths::CSTRING_NEW);
1620         then {
1621             span_lint_and_then(
1622                 cx,
1623                 TEMPORARY_CSTRING_AS_PTR,
1624                 expr.span,
1625                 "you are getting the inner pointer of a temporary `CString`",
1626                 |db| {
1627                     db.note("that pointer will be invalid outside this expression");
1628                     db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1629                 });
1630         }
1631     }
1632 }
1633
1634 fn lint_iter_cloned_collect<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr, iter_args: &'tcx [hir::Expr]) {
1635     if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC) {
1636         if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])) {
1637             if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite()) {
1638                 span_lint_and_sugg(
1639                     cx,
1640                     ITER_CLONED_COLLECT,
1641                     to_replace,
1642                     "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1643                      more readable",
1644                     "try",
1645                     ".to_vec()".to_string(),
1646                     Applicability::MachineApplicable,
1647                 );
1648             }
1649         }
1650     }
1651 }
1652
1653 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1654     fn check_fold_with_op(
1655         cx: &LateContext<'_, '_>,
1656         fold_args: &[hir::Expr],
1657         op: hir::BinOpKind,
1658         replacement_method_name: &str,
1659         replacement_has_args: bool,
1660     ) {
1661         if_chain! {
1662             // Extract the body of the closure passed to fold
1663             if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].node;
1664             let closure_body = cx.tcx.hir().body(body_id);
1665             let closure_expr = remove_blocks(&closure_body.value);
1666
1667             // Check if the closure body is of the form `acc <op> some_expr(x)`
1668             if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1669             if bin_op.node == op;
1670
1671             // Extract the names of the two arguments to the closure
1672             if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1673             if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1674
1675             if match_var(&*left_expr, first_arg_ident);
1676             if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1677
1678             then {
1679                 // Span containing `.fold(...)`
1680                 let next_point = cx.sess().source_map().next_point(fold_args[0].span);
1681                 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1682
1683                 let mut applicability = Applicability::MachineApplicable;
1684                 let sugg = if replacement_has_args {
1685                     format!(
1686                         ".{replacement}(|{s}| {r})",
1687                         replacement = replacement_method_name,
1688                         s = second_arg_ident,
1689                         r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
1690                     )
1691                 } else {
1692                     format!(
1693                         ".{replacement}()",
1694                         replacement = replacement_method_name,
1695                     )
1696                 };
1697
1698                 span_lint_and_sugg(
1699                     cx,
1700                     UNNECESSARY_FOLD,
1701                     fold_span,
1702                     // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
1703                     "this `.fold` can be written more succinctly using another method",
1704                     "try",
1705                     sugg,
1706                     applicability,
1707                 );
1708             }
1709         }
1710     }
1711
1712     // Check that this is a call to Iterator::fold rather than just some function called fold
1713     if !match_trait_method(cx, expr, &paths::ITERATOR) {
1714         return;
1715     }
1716
1717     assert!(
1718         fold_args.len() == 3,
1719         "Expected fold_args to have three entries - the receiver, the initial value and the closure"
1720     );
1721
1722     // Check if the first argument to .fold is a suitable literal
1723     if let hir::ExprKind::Lit(ref lit) = fold_args[1].node {
1724         match lit.node {
1725             ast::LitKind::Bool(false) => check_fold_with_op(cx, fold_args, hir::BinOpKind::Or, "any", true),
1726             ast::LitKind::Bool(true) => check_fold_with_op(cx, fold_args, hir::BinOpKind::And, "all", true),
1727             ast::LitKind::Int(0, _) => check_fold_with_op(cx, fold_args, hir::BinOpKind::Add, "sum", false),
1728             ast::LitKind::Int(1, _) => check_fold_with_op(cx, fold_args, hir::BinOpKind::Mul, "product", false),
1729             _ => (),
1730         }
1731     }
1732 }
1733
1734 fn lint_iter_nth<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr, iter_args: &'tcx [hir::Expr], is_mut: bool) {
1735     let mut_str = if is_mut { "_mut" } else { "" };
1736     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1737         "slice"
1738     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1739         "Vec"
1740     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1741         "VecDeque"
1742     } else {
1743         return; // caller is not a type that we want to lint
1744     };
1745
1746     span_lint(
1747         cx,
1748         ITER_NTH,
1749         expr.span,
1750         &format!(
1751             "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1752             mut_str, caller_type
1753         ),
1754     );
1755 }
1756
1757 fn lint_get_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr, get_args: &'tcx [hir::Expr], is_mut: bool) {
1758     // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1759     // because they do not implement `IndexMut`
1760     let mut applicability = Applicability::MachineApplicable;
1761     let expr_ty = cx.tables.expr_ty(&get_args[0]);
1762     let get_args_str = if get_args.len() > 1 {
1763         snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
1764     } else {
1765         return; // not linting on a .get().unwrap() chain or variant
1766     };
1767     let mut needs_ref;
1768     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1769         needs_ref = get_args_str.parse::<usize>().is_ok();
1770         "slice"
1771     } else if match_type(cx, expr_ty, &paths::VEC) {
1772         needs_ref = get_args_str.parse::<usize>().is_ok();
1773         "Vec"
1774     } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1775         needs_ref = get_args_str.parse::<usize>().is_ok();
1776         "VecDeque"
1777     } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1778         needs_ref = true;
1779         "HashMap"
1780     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1781         needs_ref = true;
1782         "BTreeMap"
1783     } else {
1784         return; // caller is not a type that we want to lint
1785     };
1786
1787     let mut span = expr.span;
1788
1789     // Handle the case where the result is immediately dereferenced
1790     // by not requiring ref and pulling the dereference into the
1791     // suggestion.
1792     if_chain! {
1793         if needs_ref;
1794         if let Some(parent) = get_parent_expr(cx, expr);
1795         if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.node;
1796         then {
1797             needs_ref = false;
1798             span = parent.span;
1799         }
1800     }
1801
1802     let mut_str = if is_mut { "_mut" } else { "" };
1803     let borrow_str = if !needs_ref {
1804         ""
1805     } else if is_mut {
1806         "&mut "
1807     } else {
1808         "&"
1809     };
1810
1811     span_lint_and_sugg(
1812         cx,
1813         GET_UNWRAP,
1814         span,
1815         &format!(
1816             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1817             mut_str, caller_type
1818         ),
1819         "try this",
1820         format!(
1821             "{}{}[{}]",
1822             borrow_str,
1823             snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
1824             get_args_str
1825         ),
1826         applicability,
1827     );
1828 }
1829
1830 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr) {
1831     // lint if caller of skip is an Iterator
1832     if match_trait_method(cx, expr, &paths::ITERATOR) {
1833         span_lint(
1834             cx,
1835             ITER_SKIP_NEXT,
1836             expr.span,
1837             "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1838         );
1839     }
1840 }
1841
1842 fn derefs_to_slice<'a, 'tcx>(
1843     cx: &LateContext<'a, 'tcx>,
1844     expr: &'tcx hir::Expr,
1845     ty: Ty<'tcx>,
1846 ) -> Option<&'tcx hir::Expr> {
1847     fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
1848         match ty.sty {
1849             ty::Slice(_) => true,
1850             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1851             ty::Adt(..) => match_type(cx, ty, &paths::VEC),
1852             ty::Array(_, size) => size.eval_usize(cx.tcx, cx.param_env) < 32,
1853             ty::Ref(_, inner, _) => may_slice(cx, inner),
1854             _ => false,
1855         }
1856     }
1857
1858     if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.node {
1859         if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1860             Some(&args[0])
1861         } else {
1862             None
1863         }
1864     } else {
1865         match ty.sty {
1866             ty::Slice(_) => Some(expr),
1867             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
1868             ty::Ref(_, inner, _) => {
1869                 if may_slice(cx, inner) {
1870                     Some(expr)
1871                 } else {
1872                     None
1873                 }
1874             },
1875             _ => None,
1876         }
1877     }
1878 }
1879
1880 /// lint use of `unwrap()` for `Option`s and `Result`s
1881 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1882     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
1883
1884     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1885         Some((OPTION_UNWRAP_USED, "an Option", "None"))
1886     } else if match_type(cx, obj_ty, &paths::RESULT) {
1887         Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1888     } else {
1889         None
1890     };
1891
1892     if let Some((lint, kind, none_value)) = mess {
1893         span_lint(
1894             cx,
1895             lint,
1896             expr.span,
1897             &format!(
1898                 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1899                  using expect() to provide a better panic \
1900                  message",
1901                 kind, none_value
1902             ),
1903         );
1904     }
1905 }
1906
1907 /// lint use of `ok().expect()` for `Result`s
1908 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1909     // lint if the caller of `ok()` is a `Result`
1910     if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1911         let result_type = cx.tables.expr_ty(&ok_args[0]);
1912         if let Some(error_type) = get_error_type(cx, result_type) {
1913             if has_debug_impl(error_type, cx) {
1914                 span_lint(
1915                     cx,
1916                     OK_EXPECT,
1917                     expr.span,
1918                     "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1919                 );
1920             }
1921         }
1922     }
1923 }
1924
1925 /// lint use of `map().flatten()` for `Iterators`
1926 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_args: &'tcx [hir::Expr]) {
1927     // lint if caller of `.map().flatten()` is an Iterator
1928     if match_trait_method(cx, expr, &paths::ITERATOR) {
1929         let msg = "called `map(..).flatten()` on an `Iterator`. \
1930                    This is more succinctly expressed by calling `.flat_map(..)`";
1931         let self_snippet = snippet(cx, map_args[0].span, "..");
1932         let func_snippet = snippet(cx, map_args[1].span, "..");
1933         let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
1934         span_lint_and_then(cx, MAP_FLATTEN, expr.span, msg, |db| {
1935             db.span_suggestion(
1936                 expr.span,
1937                 "try using flat_map instead",
1938                 hint,
1939                 Applicability::MachineApplicable,
1940             );
1941         });
1942     }
1943 }
1944
1945 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1946 fn lint_map_unwrap_or_else<'a, 'tcx>(
1947     cx: &LateContext<'a, 'tcx>,
1948     expr: &'tcx hir::Expr,
1949     map_args: &'tcx [hir::Expr],
1950     unwrap_args: &'tcx [hir::Expr],
1951 ) {
1952     // lint if the caller of `map()` is an `Option`
1953     let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1954     let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1955
1956     if is_option || is_result {
1957         // Don't make a suggestion that may fail to compile due to mutably borrowing
1958         // the same variable twice.
1959         let map_mutated_vars = mutated_variables(&map_args[0], cx);
1960         let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
1961         if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
1962             if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
1963                 return;
1964             }
1965         } else {
1966             return;
1967         }
1968
1969         // lint message
1970         let msg = if is_option {
1971             "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1972              `map_or_else(g, f)` instead"
1973         } else {
1974             "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1975              `ok().map_or_else(g, f)` instead"
1976         };
1977         // get snippets for args to map() and unwrap_or_else()
1978         let map_snippet = snippet(cx, map_args[1].span, "..");
1979         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1980         // lint, with note if neither arg is > 1 line and both map() and
1981         // unwrap_or_else() have the same span
1982         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1983         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1984         if same_span && !multiline {
1985             span_note_and_lint(
1986                 cx,
1987                 if is_option {
1988                     OPTION_MAP_UNWRAP_OR_ELSE
1989                 } else {
1990                     RESULT_MAP_UNWRAP_OR_ELSE
1991                 },
1992                 expr.span,
1993                 msg,
1994                 expr.span,
1995                 &format!(
1996                     "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1997                     map_snippet,
1998                     unwrap_snippet,
1999                     if is_result { "ok()." } else { "" }
2000                 ),
2001             );
2002         } else if same_span && multiline {
2003             span_lint(
2004                 cx,
2005                 if is_option {
2006                     OPTION_MAP_UNWRAP_OR_ELSE
2007                 } else {
2008                     RESULT_MAP_UNWRAP_OR_ELSE
2009                 },
2010                 expr.span,
2011                 msg,
2012             );
2013         };
2014     }
2015 }
2016
2017 /// lint use of `_.map_or(None, _)` for `Option`s
2018 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
2019     if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
2020         // check if the first non-self argument to map_or() is None
2021         let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].node {
2022             match_qpath(qpath, &paths::OPTION_NONE)
2023         } else {
2024             false
2025         };
2026
2027         if map_or_arg_is_none {
2028             // lint message
2029             let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
2030                        `and_then(f)` instead";
2031             let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
2032             let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
2033             let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
2034             span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
2035                 db.span_suggestion(
2036                     expr.span,
2037                     "try using and_then instead",
2038                     hint,
2039                     Applicability::MachineApplicable, // snippet
2040                 );
2041             });
2042         }
2043     }
2044 }
2045
2046 /// lint use of `filter().next()` for `Iterators`
2047 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
2048     // lint if caller of `.filter().next()` is an Iterator
2049     if match_trait_method(cx, expr, &paths::ITERATOR) {
2050         let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2051                    `.find(p)` instead.";
2052         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2053         if filter_snippet.lines().count() <= 1 {
2054             // add note if not multi-line
2055             span_note_and_lint(
2056                 cx,
2057                 FILTER_NEXT,
2058                 expr.span,
2059                 msg,
2060                 expr.span,
2061                 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2062             );
2063         } else {
2064             span_lint(cx, FILTER_NEXT, expr.span, msg);
2065         }
2066     }
2067 }
2068
2069 /// lint use of `filter().map()` for `Iterators`
2070 fn lint_filter_map<'a, 'tcx>(
2071     cx: &LateContext<'a, 'tcx>,
2072     expr: &'tcx hir::Expr,
2073     _filter_args: &'tcx [hir::Expr],
2074     _map_args: &'tcx [hir::Expr],
2075 ) {
2076     // lint if caller of `.filter().map()` is an Iterator
2077     if match_trait_method(cx, expr, &paths::ITERATOR) {
2078         let msg = "called `filter(p).map(q)` on an `Iterator`. \
2079                    This is more succinctly expressed by calling `.filter_map(..)` instead.";
2080         span_lint(cx, FILTER_MAP, expr.span, msg);
2081     }
2082 }
2083
2084 /// lint use of `filter_map().next()` for `Iterators`
2085 fn lint_filter_map_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
2086     if match_trait_method(cx, expr, &paths::ITERATOR) {
2087         let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2088                    `.find_map(p)` instead.";
2089         let filter_snippet = snippet(cx, filter_args[1].span, "..");
2090         if filter_snippet.lines().count() <= 1 {
2091             span_note_and_lint(
2092                 cx,
2093                 FILTER_MAP_NEXT,
2094                 expr.span,
2095                 msg,
2096                 expr.span,
2097                 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2098             );
2099         } else {
2100             span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2101         }
2102     }
2103 }
2104
2105 /// lint use of `find().map()` for `Iterators`
2106 fn lint_find_map<'a, 'tcx>(
2107     cx: &LateContext<'a, 'tcx>,
2108     expr: &'tcx hir::Expr,
2109     _find_args: &'tcx [hir::Expr],
2110     map_args: &'tcx [hir::Expr],
2111 ) {
2112     // lint if caller of `.filter().map()` is an Iterator
2113     if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2114         let msg = "called `find(p).map(q)` on an `Iterator`. \
2115                    This is more succinctly expressed by calling `.find_map(..)` instead.";
2116         span_lint(cx, FIND_MAP, expr.span, msg);
2117     }
2118 }
2119
2120 /// lint use of `filter().map()` for `Iterators`
2121 fn lint_filter_map_map<'a, 'tcx>(
2122     cx: &LateContext<'a, 'tcx>,
2123     expr: &'tcx hir::Expr,
2124     _filter_args: &'tcx [hir::Expr],
2125     _map_args: &'tcx [hir::Expr],
2126 ) {
2127     // lint if caller of `.filter().map()` is an Iterator
2128     if match_trait_method(cx, expr, &paths::ITERATOR) {
2129         let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
2130                    This is more succinctly expressed by only calling `.filter_map(..)` instead.";
2131         span_lint(cx, FILTER_MAP, expr.span, msg);
2132     }
2133 }
2134
2135 /// lint use of `filter().flat_map()` for `Iterators`
2136 fn lint_filter_flat_map<'a, 'tcx>(
2137     cx: &LateContext<'a, 'tcx>,
2138     expr: &'tcx hir::Expr,
2139     _filter_args: &'tcx [hir::Expr],
2140     _map_args: &'tcx [hir::Expr],
2141 ) {
2142     // lint if caller of `.filter().flat_map()` is an Iterator
2143     if match_trait_method(cx, expr, &paths::ITERATOR) {
2144         let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
2145                    This is more succinctly expressed by calling `.flat_map(..)` \
2146                    and filtering by returning an empty Iterator.";
2147         span_lint(cx, FILTER_MAP, expr.span, msg);
2148     }
2149 }
2150
2151 /// lint use of `filter_map().flat_map()` for `Iterators`
2152 fn lint_filter_map_flat_map<'a, 'tcx>(
2153     cx: &LateContext<'a, 'tcx>,
2154     expr: &'tcx hir::Expr,
2155     _filter_args: &'tcx [hir::Expr],
2156     _map_args: &'tcx [hir::Expr],
2157 ) {
2158     // lint if caller of `.filter_map().flat_map()` is an Iterator
2159     if match_trait_method(cx, expr, &paths::ITERATOR) {
2160         let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
2161                    This is more succinctly expressed by calling `.flat_map(..)` \
2162                    and filtering by returning an empty Iterator.";
2163         span_lint(cx, FILTER_MAP, expr.span, msg);
2164     }
2165 }
2166
2167 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2168 fn lint_flat_map_identity<'a, 'tcx>(
2169     cx: &LateContext<'a, 'tcx>,
2170     expr: &'tcx hir::Expr,
2171     flat_map_args: &'tcx [hir::Expr],
2172 ) {
2173     if_chain! {
2174         if match_trait_method(cx, expr, &paths::ITERATOR);
2175
2176         if flat_map_args.len() == 2;
2177         if let hir::ExprKind::Closure(_, _, body_id, _, _) = flat_map_args[1].node;
2178         let body = cx.tcx.hir().body(body_id);
2179
2180         if body.arguments.len() == 1;
2181         if let hir::PatKind::Binding(_, _, binding_ident, _) = body.arguments[0].pat.node;
2182         if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.node;
2183
2184         if path.segments.len() == 1;
2185         if path.segments[0].ident.as_str() == binding_ident.as_str();
2186
2187         then {
2188             let msg = "called `flat_map(|x| x)` on an `Iterator`. \
2189                        This can be simplified by calling `flatten().`";
2190             span_lint(cx, FLAT_MAP_IDENTITY, expr.span, msg);
2191         }
2192     }
2193
2194     if_chain! {
2195         if match_trait_method(cx, expr, &paths::ITERATOR);
2196
2197         if flat_map_args.len() == 2;
2198
2199         let expr = &flat_map_args[1];
2200
2201         if let hir::ExprKind::Path(ref qpath) = expr.node;
2202
2203         if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2204
2205         then {
2206             let msg = "called `flat_map(std::convert::identity)` on an `Iterator`. \
2207                        This can be simplified by calling `flatten().`";
2208             span_lint(cx, FLAT_MAP_IDENTITY, expr.span, msg);
2209         }
2210     }
2211 }
2212
2213 /// lint searching an Iterator followed by `is_some()`
2214 fn lint_search_is_some<'a, 'tcx>(
2215     cx: &LateContext<'a, 'tcx>,
2216     expr: &'tcx hir::Expr,
2217     search_method: &str,
2218     search_args: &'tcx [hir::Expr],
2219     is_some_args: &'tcx [hir::Expr],
2220 ) {
2221     // lint if caller of search is an Iterator
2222     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2223         let msg = format!(
2224             "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2225              expressed by calling `any()`.",
2226             search_method
2227         );
2228         let search_snippet = snippet(cx, search_args[1].span, "..");
2229         if search_snippet.lines().count() <= 1 {
2230             // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2231             let any_search_snippet = if_chain! {
2232                 if search_method == "find";
2233                 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].node;
2234                 let closure_body = cx.tcx.hir().body(body_id);
2235                 if let Some(closure_arg) = closure_body.arguments.get(0);
2236                 if let hir::PatKind::Ref(..) = closure_arg.pat.node;
2237                 then {
2238                     Some(search_snippet.replacen('&', "", 1))
2239                 } else {
2240                     None
2241                 }
2242             };
2243             // add note if not multi-line
2244             span_note_and_lint(
2245                 cx,
2246                 SEARCH_IS_SOME,
2247                 expr.span,
2248                 &msg,
2249                 expr.span,
2250                 &format!(
2251                     "replace `{0}({1}).is_some()` with `any({2})`",
2252                     search_method,
2253                     search_snippet,
2254                     any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2255                 ),
2256             );
2257         } else {
2258             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2259         }
2260     }
2261 }
2262
2263 /// Used for `lint_binary_expr_with_method_call`.
2264 #[derive(Copy, Clone)]
2265 struct BinaryExprInfo<'a> {
2266     expr: &'a hir::Expr,
2267     chain: &'a hir::Expr,
2268     other: &'a hir::Expr,
2269     eq: bool,
2270 }
2271
2272 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2273 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2274     macro_rules! lint_with_both_lhs_and_rhs {
2275         ($func:ident, $cx:expr, $info:ident) => {
2276             if !$func($cx, $info) {
2277                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2278                 if $func($cx, $info) {
2279                     return;
2280                 }
2281             }
2282         };
2283     }
2284
2285     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2286     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2287     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2288     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2289 }
2290
2291 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2292 fn lint_chars_cmp(
2293     cx: &LateContext<'_, '_>,
2294     info: &BinaryExprInfo<'_>,
2295     chain_methods: &[&str],
2296     lint: &'static Lint,
2297     suggest: &str,
2298 ) -> bool {
2299     if_chain! {
2300         if let Some(args) = method_chain_args(info.chain, chain_methods);
2301         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.node;
2302         if arg_char.len() == 1;
2303         if let hir::ExprKind::Path(ref qpath) = fun.node;
2304         if let Some(segment) = single_segment_path(qpath);
2305         if segment.ident.name == sym!(Some);
2306         then {
2307             let mut applicability = Applicability::MachineApplicable;
2308             let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2309
2310             if self_ty.sty != ty::Str {
2311                 return false;
2312             }
2313
2314             span_lint_and_sugg(
2315                 cx,
2316                 lint,
2317                 info.expr.span,
2318                 &format!("you should use the `{}` method", suggest),
2319                 "like this",
2320                 format!("{}{}.{}({})",
2321                         if info.eq { "" } else { "!" },
2322                         snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2323                         suggest,
2324                         snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2325                 applicability,
2326             );
2327
2328             return true;
2329         }
2330     }
2331
2332     false
2333 }
2334
2335 /// Checks for the `CHARS_NEXT_CMP` lint.
2336 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2337     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2338 }
2339
2340 /// Checks for the `CHARS_LAST_CMP` lint.
2341 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2342     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2343         true
2344     } else {
2345         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2346     }
2347 }
2348
2349 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2350 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2351     cx: &LateContext<'a, 'tcx>,
2352     info: &BinaryExprInfo<'_>,
2353     chain_methods: &[&str],
2354     lint: &'static Lint,
2355     suggest: &str,
2356 ) -> bool {
2357     if_chain! {
2358         if let Some(args) = method_chain_args(info.chain, chain_methods);
2359         if let hir::ExprKind::Lit(ref lit) = info.other.node;
2360         if let ast::LitKind::Char(c) = lit.node;
2361         then {
2362             let mut applicability = Applicability::MachineApplicable;
2363             span_lint_and_sugg(
2364                 cx,
2365                 lint,
2366                 info.expr.span,
2367                 &format!("you should use the `{}` method", suggest),
2368                 "like this",
2369                 format!("{}{}.{}('{}')",
2370                         if info.eq { "" } else { "!" },
2371                         snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2372                         suggest,
2373                         c),
2374                 applicability,
2375             );
2376
2377             return true;
2378         }
2379     }
2380
2381     false
2382 }
2383
2384 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2385 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2386     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2387 }
2388
2389 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2390 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2391     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2392         true
2393     } else {
2394         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
2395     }
2396 }
2397
2398 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
2399 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, _expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
2400     if_chain! {
2401         if let hir::ExprKind::Lit(lit) = &arg.node;
2402         if let ast::LitKind::Str(r, style) = lit.node;
2403         if r.as_str().len() == 1;
2404         then {
2405             let mut applicability = Applicability::MachineApplicable;
2406             let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
2407             let ch = if let ast::StrStyle::Raw(nhash) = style {
2408                 let nhash = nhash as usize;
2409                 // for raw string: r##"a"##
2410                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
2411             } else {
2412                 // for regular string: "a"
2413                 &snip[1..(snip.len() - 1)]
2414             };
2415             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
2416             span_lint_and_sugg(
2417                 cx,
2418                 SINGLE_CHAR_PATTERN,
2419                 arg.span,
2420                 "single-character string constant used as pattern",
2421                 "try using a char instead",
2422                 hint,
2423                 applicability,
2424             );
2425         }
2426     }
2427 }
2428
2429 /// Checks for the `USELESS_ASREF` lint.
2430 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
2431     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
2432     // check if the call is to the actual `AsRef` or `AsMut` trait
2433     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
2434         // check if the type after `as_ref` or `as_mut` is the same as before
2435         let recvr = &as_ref_args[0];
2436         let rcv_ty = cx.tables.expr_ty(recvr);
2437         let res_ty = cx.tables.expr_ty(expr);
2438         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
2439         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
2440         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
2441             // allow the `as_ref` or `as_mut` if it is followed by another method call
2442             if_chain! {
2443                 if let Some(parent) = get_parent_expr(cx, expr);
2444                 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.node;
2445                 if span != &expr.span;
2446                 then {
2447                     return;
2448                 }
2449             }
2450
2451             let mut applicability = Applicability::MachineApplicable;
2452             span_lint_and_sugg(
2453                 cx,
2454                 USELESS_ASREF,
2455                 expr.span,
2456                 &format!("this call to `{}` does nothing", call_name),
2457                 "try this",
2458                 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
2459                 applicability,
2460             );
2461         }
2462     }
2463 }
2464
2465 fn ty_has_iter_method(
2466     cx: &LateContext<'_, '_>,
2467     self_ref_ty: Ty<'_>,
2468 ) -> Option<(&'static Lint, &'static str, &'static str)> {
2469     if let Some(ty_name) = has_iter_method(cx, self_ref_ty) {
2470         let lint = if ty_name == "array" || ty_name == "PathBuf" {
2471             INTO_ITER_ON_ARRAY
2472         } else {
2473             INTO_ITER_ON_REF
2474         };
2475         let mutbl = match self_ref_ty.sty {
2476             ty::Ref(_, _, mutbl) => mutbl,
2477             _ => unreachable!(),
2478         };
2479         let method_name = match mutbl {
2480             hir::MutImmutable => "iter",
2481             hir::MutMutable => "iter_mut",
2482         };
2483         Some((lint, ty_name, method_name))
2484     } else {
2485         None
2486     }
2487 }
2488
2489 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr, self_ref_ty: Ty<'_>, method_span: Span) {
2490     if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
2491         return;
2492     }
2493     if let Some((lint, kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
2494         span_lint_and_sugg(
2495             cx,
2496             lint,
2497             method_span,
2498             &format!(
2499                 "this .into_iter() call is equivalent to .{}() and will not move the {}",
2500                 method_name, kind,
2501             ),
2502             "call directly",
2503             method_name.to_string(),
2504             Applicability::MachineApplicable,
2505         );
2506     }
2507 }
2508
2509 /// Given a `Result<T, E>` type, return its error type (`E`).
2510 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
2511     if let ty::Adt(_, substs) = ty.sty {
2512         if match_type(cx, ty, &paths::RESULT) {
2513             substs.types().nth(1)
2514         } else {
2515             None
2516         }
2517     } else {
2518         None
2519     }
2520 }
2521
2522 /// This checks whether a given type is known to implement Debug.
2523 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
2524     match cx.tcx.lang_items().debug_trait() {
2525         Some(debug) => implements_trait(cx, ty, debug, &[]),
2526         None => false,
2527     }
2528 }
2529
2530 enum Convention {
2531     Eq(&'static str),
2532     StartsWith(&'static str),
2533 }
2534
2535 #[rustfmt::skip]
2536 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
2537     (Convention::Eq("new"), &[SelfKind::No]),
2538     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
2539     (Convention::StartsWith("from_"), &[SelfKind::No]),
2540     (Convention::StartsWith("into_"), &[SelfKind::Value]),
2541     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
2542     (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
2543     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
2544 ];
2545
2546 #[rustfmt::skip]
2547 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
2548     ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
2549     ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
2550     ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
2551     ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
2552     ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
2553     ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
2554     ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
2555     ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
2556     ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
2557     ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
2558     ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
2559     ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
2560     ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
2561     ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
2562     ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
2563     ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
2564     ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
2565     ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
2566     ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
2567     ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
2568     ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
2569     ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
2570     ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
2571     ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
2572     ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
2573     ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
2574     ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
2575     ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
2576     ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
2577     ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
2578 ];
2579
2580 #[rustfmt::skip]
2581 const PATTERN_METHODS: [(&str, usize); 17] = [
2582     ("contains", 1),
2583     ("starts_with", 1),
2584     ("ends_with", 1),
2585     ("find", 1),
2586     ("rfind", 1),
2587     ("split", 1),
2588     ("rsplit", 1),
2589     ("split_terminator", 1),
2590     ("rsplit_terminator", 1),
2591     ("splitn", 2),
2592     ("rsplitn", 2),
2593     ("matches", 1),
2594     ("rmatches", 1),
2595     ("match_indices", 1),
2596     ("rmatch_indices", 1),
2597     ("trim_start_matches", 1),
2598     ("trim_end_matches", 1),
2599 ];
2600
2601 #[derive(Clone, Copy, PartialEq, Debug)]
2602 enum SelfKind {
2603     Value,
2604     Ref,
2605     RefMut,
2606     No,
2607 }
2608
2609 impl SelfKind {
2610     fn matches(
2611         self,
2612         cx: &LateContext<'_, '_>,
2613         ty: &hir::Ty,
2614         arg: &hir::Arg,
2615         self_ty: &hir::Ty,
2616         allow_value_for_ref: bool,
2617         generics: &hir::Generics,
2618     ) -> bool {
2619         // Self types in the HIR are desugared to explicit self types. So it will
2620         // always be `self:
2621         // SomeType`,
2622         // where SomeType can be `Self` or an explicit impl self type (e.g., `Foo` if
2623         // the impl is on `Foo`)
2624         // Thus, we only need to test equality against the impl self type or if it is
2625         // an explicit
2626         // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
2627         // `Self`, `&mut Self`,
2628         // and `Box<Self>`, including the equivalent types with `Foo`.
2629
2630         let is_actually_self = |ty| is_self_ty(ty) || SpanlessEq::new(cx).eq_ty(ty, self_ty);
2631         if is_self(arg) {
2632             match self {
2633                 Self::Value => is_actually_self(ty),
2634                 Self::Ref | Self::RefMut => {
2635                     if allow_value_for_ref && is_actually_self(ty) {
2636                         return true;
2637                     }
2638                     match ty.node {
2639                         hir::TyKind::Rptr(_, ref mt_ty) => {
2640                             let mutability_match = if self == Self::Ref {
2641                                 mt_ty.mutbl == hir::MutImmutable
2642                             } else {
2643                                 mt_ty.mutbl == hir::MutMutable
2644                             };
2645                             is_actually_self(&mt_ty.ty) && mutability_match
2646                         },
2647                         _ => false,
2648                     }
2649                 },
2650                 _ => false,
2651             }
2652         } else {
2653             match self {
2654                 Self::Value => false,
2655                 Self::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
2656                 Self::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
2657                 Self::No => true,
2658             }
2659         }
2660     }
2661
2662     fn description(self) -> &'static str {
2663         match self {
2664             Self::Value => "self by value",
2665             Self::Ref => "self by reference",
2666             Self::RefMut => "self by mutable reference",
2667             Self::No => "no self",
2668         }
2669     }
2670 }
2671
2672 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
2673     single_segment_ty(ty).map_or(false, |seg| {
2674         generics.params.iter().any(|param| match param.kind {
2675             hir::GenericParamKind::Type { .. } => {
2676                 param.name.ident().name == seg.ident.name
2677                     && param.bounds.iter().any(|bound| {
2678                         if let hir::GenericBound::Trait(ref ptr, ..) = *bound {
2679                             let path = &ptr.trait_ref.path;
2680                             match_path(path, name)
2681                                 && path.segments.last().map_or(false, |s| {
2682                                     if let Some(ref params) = s.args {
2683                                         if params.parenthesized {
2684                                             false
2685                                         } else {
2686                                             // FIXME(flip1995): messy, improve if there is a better option
2687                                             // in the compiler
2688                                             let types: Vec<_> = params
2689                                                 .args
2690                                                 .iter()
2691                                                 .filter_map(|arg| match arg {
2692                                                     hir::GenericArg::Type(ty) => Some(ty),
2693                                                     _ => None,
2694                                                 })
2695                                                 .collect();
2696                                             types.len() == 1 && (is_self_ty(&types[0]) || is_ty(&*types[0], self_ty))
2697                                         }
2698                                     } else {
2699                                         false
2700                                     }
2701                                 })
2702                         } else {
2703                             false
2704                         }
2705                     })
2706             },
2707             _ => false,
2708         })
2709     })
2710 }
2711
2712 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
2713     match (&ty.node, &self_ty.node) {
2714         (
2715             &hir::TyKind::Path(hir::QPath::Resolved(_, ref ty_path)),
2716             &hir::TyKind::Path(hir::QPath::Resolved(_, ref self_ty_path)),
2717         ) => ty_path
2718             .segments
2719             .iter()
2720             .map(|seg| seg.ident.name)
2721             .eq(self_ty_path.segments.iter().map(|seg| seg.ident.name)),
2722         _ => false,
2723     }
2724 }
2725
2726 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2727     if let hir::TyKind::Path(ref path) = ty.node {
2728         single_segment_path(path)
2729     } else {
2730         None
2731     }
2732 }
2733
2734 impl Convention {
2735     fn check(&self, other: &str) -> bool {
2736         match *self {
2737             Self::Eq(this) => this == other,
2738             Self::StartsWith(this) => other.starts_with(this) && this != other,
2739         }
2740     }
2741 }
2742
2743 impl fmt::Display for Convention {
2744     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
2745         match *self {
2746             Self::Eq(this) => this.fmt(f),
2747             Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2748         }
2749     }
2750 }
2751
2752 #[derive(Clone, Copy)]
2753 enum OutType {
2754     Unit,
2755     Bool,
2756     Any,
2757     Ref,
2758 }
2759
2760 impl OutType {
2761     fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FunctionRetTy) -> bool {
2762         let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
2763         match (self, ty) {
2764             (Self::Unit, &hir::DefaultReturn(_)) => true,
2765             (Self::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,
2766             (Self::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2767             (Self::Any, &hir::Return(ref ty)) if !is_unit(ty) => true,
2768             (Self::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyKind::Rptr(_, _)),
2769             _ => false,
2770         }
2771     }
2772 }
2773
2774 fn is_bool(ty: &hir::Ty) -> bool {
2775     if let hir::TyKind::Path(ref p) = ty.node {
2776         match_qpath(p, &["bool"])
2777     } else {
2778         false
2779     }
2780 }