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