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