]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods.rs
Merge pull request #2507 from ordovicia/redundant_field_names_range
[rust.git] / clippy_lints / src / methods.rs
1 use rustc::hir;
2 use rustc::lint::*;
3 use rustc::middle::const_val::ConstVal;
4 use rustc::ty::{self, Ty};
5 use rustc::hir::def::Def;
6 use rustc::ty::subst::Substs;
7 use rustc_const_eval::ConstContext;
8 use std::borrow::Cow;
9 use std::fmt;
10 use std::iter;
11 use syntax::ast;
12 use syntax::codemap::{Span, BytePos};
13 use utils::{get_arg_name, get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_self, is_self_ty,
14             iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
15             match_type, method_chain_args, match_var, return_ty, remove_blocks, same_tys, single_segment_path, snippet,
16             span_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
17 use utils::paths;
18 use utils::sugg;
19 use utils::const_to_u64;
20
21 #[derive(Clone)]
22 pub struct Pass;
23
24 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
25 ///
26 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
27 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
28 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
29 /// `Allow` by default.
30 ///
31 /// **Known problems:** None.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// x.unwrap()
36 /// ```
37 declare_lint! {
38     pub OPTION_UNWRAP_USED,
39     Allow,
40     "using `Option.unwrap()`, which should at least get a better message using `expect()`"
41 }
42
43 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
44 ///
45 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
46 /// values. Normally, you want to implement more sophisticated error handling,
47 /// and propagate errors upwards with `try!`.
48 ///
49 /// Even if you want to panic on errors, not all `Error`s implement good
50 /// messages on display.  Therefore it may be beneficial to look at the places
51 /// where they may get displayed. Activate this lint to do just that.
52 ///
53 /// **Known problems:** None.
54 ///
55 /// **Example:**
56 /// ```rust
57 /// x.unwrap()
58 /// ```
59 declare_lint! {
60     pub RESULT_UNWRAP_USED,
61     Allow,
62     "using `Result.unwrap()`, which might be better handled"
63 }
64
65 /// **What it does:** Checks for methods that should live in a trait
66 /// implementation of a `std` trait (see [llogiq's blog
67 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
68 /// information) instead of an inherent implementation.
69 ///
70 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
71 /// the code, often with very little cost. Also people seeing a `mul(...)`
72 /// method
73 /// may expect `*` to work equally, so you should have good reason to disappoint
74 /// them.
75 ///
76 /// **Known problems:** None.
77 ///
78 /// **Example:**
79 /// ```rust
80 /// struct X;
81 /// impl X {
82 ///    fn add(&self, other: &X) -> X { .. }
83 /// }
84 /// ```
85 declare_lint! {
86     pub SHOULD_IMPLEMENT_TRAIT,
87     Warn,
88     "defining a method that should be implementing a std trait"
89 }
90
91 /// **What it does:** Checks for methods with certain name prefixes and which
92 /// doesn't match how self is taken. The actual rules are:
93 ///
94 /// |Prefix |`self` taken          |
95 /// |-------|----------------------|
96 /// |`as_`  |`&self` or `&mut self`|
97 /// |`from_`| none                 |
98 /// |`into_`|`self`                |
99 /// |`is_`  |`&self` or none       |
100 /// |`to_`  |`&self`               |
101 ///
102 /// **Why is this bad?** Consistency breeds readability. If you follow the
103 /// conventions, your users won't be surprised that they, e.g., need to supply a
104 /// mutable reference to a `as_..` function.
105 ///
106 /// **Known problems:** None.
107 ///
108 /// **Example:**
109 /// ```rust
110 /// impl X {
111 ///     fn as_str(self) -> &str { .. }
112 /// }
113 /// ```
114 declare_lint! {
115     pub WRONG_SELF_CONVENTION,
116     Warn,
117     "defining a method named with an established prefix (like \"into_\") that takes \
118      `self` with the wrong convention"
119 }
120
121 /// **What it does:** This is the same as
122 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
123 ///
124 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
125 ///
126 /// **Known problems:** Actually *renaming* the function may break clients if
127 /// the function is part of the public interface. In that case, be mindful of
128 /// the stability guarantees you've given your users.
129 ///
130 /// **Example:**
131 /// ```rust
132 /// impl X {
133 ///     pub fn as_str(self) -> &str { .. }
134 /// }
135 /// ```
136 declare_lint! {
137     pub WRONG_PUB_SELF_CONVENTION,
138     Allow,
139     "defining a public method named with an established prefix (like \"into_\") that takes \
140      `self` with the wrong convention"
141 }
142
143 /// **What it does:** Checks for usage of `ok().expect(..)`.
144 ///
145 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
146 /// directly to get a better error message.
147 ///
148 /// **Known problems:** None.
149 ///
150 /// **Example:**
151 /// ```rust
152 /// x.ok().expect("why did I do this again?")
153 /// ```
154 declare_lint! {
155     pub OK_EXPECT,
156     Warn,
157     "using `ok().expect()`, which gives worse error messages than \
158      calling `expect` directly on the Result"
159 }
160
161 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
162 ///
163 /// **Why is this bad?** Readability, this can be written more concisely as
164 /// `_.map_or(_, _)`.
165 ///
166 /// **Known problems:** None.
167 ///
168 /// **Example:**
169 /// ```rust
170 /// x.map(|a| a + 1).unwrap_or(0)
171 /// ```
172 declare_lint! {
173     pub OPTION_MAP_UNWRAP_OR,
174     Allow,
175     "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
176      `map_or(a, f)`"
177 }
178
179 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
180 ///
181 /// **Why is this bad?** Readability, this can be written more concisely as
182 /// `_.map_or_else(_, _)`.
183 ///
184 /// **Known problems:** None.
185 ///
186 /// **Example:**
187 /// ```rust
188 /// x.map(|a| a + 1).unwrap_or_else(some_function)
189 /// ```
190 declare_lint! {
191     pub OPTION_MAP_UNWRAP_OR_ELSE,
192     Allow,
193     "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
194      `map_or_else(g, f)`"
195 }
196
197 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
198 ///
199 /// **Why is this bad?** Readability, this can be written more concisely as
200 /// `result.ok().map_or_else(_, _)`.
201 ///
202 /// **Known problems:** None.
203 ///
204 /// **Example:**
205 /// ```rust
206 /// x.map(|a| a + 1).unwrap_or_else(some_function)
207 /// ```
208 declare_lint! {
209     pub RESULT_MAP_UNWRAP_OR_ELSE,
210     Allow,
211     "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
212      `.ok().map_or_else(g, f)`"
213 }
214
215 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
216 ///
217 /// **Why is this bad?** Readability, this can be written more concisely as
218 /// `_.and_then(_)`.
219 ///
220 /// **Known problems:** None.
221 ///
222 /// **Example:**
223 /// ```rust
224 /// opt.map_or(None, |a| a + 1)
225 /// ```
226 declare_lint! {
227     pub OPTION_MAP_OR_NONE,
228     Warn,
229     "using `Option.map_or(None, f)`, which is more succinctly expressed as \
230      `and_then(f)`"
231 }
232
233 /// **What it does:** Checks for usage of `_.filter(_).next()`.
234 ///
235 /// **Why is this bad?** Readability, this can be written more concisely as
236 /// `_.find(_)`.
237 ///
238 /// **Known problems:** None.
239 ///
240 /// **Example:**
241 /// ```rust
242 /// iter.filter(|x| x == 0).next()
243 /// ```
244 declare_lint! {
245     pub FILTER_NEXT,
246     Warn,
247     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
248 }
249
250 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
251 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
252 ///
253 /// **Why is this bad?** Readability, this can be written more concisely as a
254 /// single method call.
255 ///
256 /// **Known problems:** Often requires a condition + Option/Iterator creation
257 /// inside the closure.
258 ///
259 /// **Example:**
260 /// ```rust
261 /// iter.filter(|x| x == 0).map(|x| x * 2)
262 /// ```
263 declare_lint! {
264     pub FILTER_MAP,
265     Allow,
266     "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
267      usually be written as a single method call"
268 }
269
270 /// **What it does:** Checks for an iterator search (such as `find()`,
271 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
272 ///
273 /// **Why is this bad?** Readability, this can be written more concisely as
274 /// `_.any(_)`.
275 ///
276 /// **Known problems:** None.
277 ///
278 /// **Example:**
279 /// ```rust
280 /// iter.find(|x| x == 0).is_some()
281 /// ```
282 declare_lint! {
283     pub SEARCH_IS_SOME,
284     Warn,
285     "using an iterator search followed by `is_some()`, which is more succinctly \
286      expressed as a call to `any()`"
287 }
288
289 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
290 /// if it starts with a given char.
291 ///
292 /// **Why is this bad?** Readability, this can be written more concisely as
293 /// `_.starts_with(_)`.
294 ///
295 /// **Known problems:** None.
296 ///
297 /// **Example:**
298 /// ```rust
299 /// name.chars().next() == Some('_')
300 /// ```
301 declare_lint! {
302     pub CHARS_NEXT_CMP,
303     Warn,
304     "using `.chars().next()` to check if a string starts with a char"
305 }
306
307 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
308 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
309 /// `unwrap_or_default` instead.
310 ///
311 /// **Why is this bad?** The function will always be called and potentially
312 /// allocate an object acting as the default.
313 ///
314 /// **Known problems:** If the function has side-effects, not calling it will
315 /// change the semantic of the program, but you shouldn't rely on that anyway.
316 ///
317 /// **Example:**
318 /// ```rust
319 /// foo.unwrap_or(String::new())
320 /// ```
321 /// this can instead be written:
322 /// ```rust
323 /// foo.unwrap_or_else(String::new)
324 /// ```
325 /// or
326 /// ```rust
327 /// foo.unwrap_or_default()
328 /// ```
329 declare_lint! {
330     pub OR_FUN_CALL,
331     Warn,
332     "using any `*or` method with a function call, which suggests `*or_else`"
333 }
334
335 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
336 ///
337 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
338 /// generics, not for using the `clone` method on a concrete type.
339 ///
340 /// **Known problems:** None.
341 ///
342 /// **Example:**
343 /// ```rust
344 /// 42u64.clone()
345 /// ```
346 declare_lint! {
347     pub CLONE_ON_COPY,
348     Warn,
349     "using `clone` on a `Copy` type"
350 }
351
352 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
353 /// (Rc, Arc, rc::Weak, or sync::Weak), and suggests calling Clone on
354 /// the corresponding trait instead.
355 ///
356 /// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
357 /// can obscure the fact that only the pointer is being cloned, not the underlying
358 /// data.
359 ///
360 /// **Example:**
361 /// ```rust
362 /// x.clone()
363 /// ```
364 declare_restriction_lint! {
365     pub CLONE_ON_REF_PTR,
366     "using 'clone' on a ref-counted pointer"
367 }
368
369 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
370 ///
371 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
372 /// cloning the underlying `T`.
373 ///
374 /// **Known problems:** None.
375 ///
376 /// **Example:**
377 /// ```rust
378 /// fn main() {
379 ///    let x = vec![1];
380 ///    let y = &&x;
381 ///    let z = y.clone();
382 ///    println!("{:p} {:p}",*y, z); // prints out the same pointer
383 /// }
384 /// ```
385 declare_lint! {
386     pub CLONE_DOUBLE_REF,
387     Warn,
388     "using `clone` on `&&T`"
389 }
390
391 /// **What it does:** Checks for `new` not returning `Self`.
392 ///
393 /// **Why is this bad?** As a convention, `new` methods are used to make a new
394 /// instance of a type.
395 ///
396 /// **Known problems:** None.
397 ///
398 /// **Example:**
399 /// ```rust
400 /// impl Foo {
401 ///     fn new(..) -> NotAFoo {
402 ///     }
403 /// }
404 /// ```
405 declare_lint! {
406     pub NEW_RET_NO_SELF,
407     Warn,
408     "not returning `Self` in a `new` method"
409 }
410
411 /// **What it does:** Checks for string methods that receive a single-character
412 /// `str` as an argument, e.g. `_.split("x")`.
413 ///
414 /// **Why is this bad?** Performing these methods using a `char` is faster than
415 /// using a `str`.
416 ///
417 /// **Known problems:** Does not catch multi-byte unicode characters.
418 ///
419 /// **Example:**
420 /// `_.split("x")` could be `_.split('x')
421 declare_lint! {
422     pub SINGLE_CHAR_PATTERN,
423     Warn,
424     "using a single-character str where a char could be used, e.g. \
425      `_.split(\"x\")`"
426 }
427
428 /// **What it does:** Checks for getting the inner pointer of a temporary
429 /// `CString`.
430 ///
431 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
432 /// as the `CString` is alive.
433 ///
434 /// **Known problems:** None.
435 ///
436 /// **Example:**
437 /// ```rust,ignore
438 /// let c_str = CString::new("foo").unwrap().as_ptr();
439 /// unsafe {
440 /// call_some_ffi_func(c_str);
441 /// }
442 /// ```
443 /// Here `c_str` point to a freed address. The correct use would be:
444 /// ```rust,ignore
445 /// let c_str = CString::new("foo").unwrap();
446 /// unsafe {
447 ///     call_some_ffi_func(c_str.as_ptr());
448 /// }
449 /// ```
450 declare_lint! {
451     pub TEMPORARY_CSTRING_AS_PTR,
452     Warn,
453     "getting the inner pointer of a temporary `CString`"
454 }
455
456 /// **What it does:** Checks for use of `.iter().nth()` (and the related
457 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
458 ///
459 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
460 /// readable.
461 ///
462 /// **Known problems:** None.
463 ///
464 /// **Example:**
465 /// ```rust
466 /// let some_vec = vec![0, 1, 2, 3];
467 /// let bad_vec = some_vec.iter().nth(3);
468 /// let bad_slice = &some_vec[..].iter().nth(3);
469 /// ```
470 /// The correct use would be:
471 /// ```rust
472 /// let some_vec = vec![0, 1, 2, 3];
473 /// let bad_vec = some_vec.get(3);
474 /// let bad_slice = &some_vec[..].get(3);
475 /// ```
476 declare_lint! {
477     pub ITER_NTH,
478     Warn,
479     "using `.iter().nth()` on a standard library type with O(1) element access"
480 }
481
482 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
483 ///
484 /// **Why is this bad?** `.nth(x)` is cleaner
485 ///
486 /// **Known problems:** None.
487 ///
488 /// **Example:**
489 /// ```rust
490 /// let some_vec = vec![0, 1, 2, 3];
491 /// let bad_vec = some_vec.iter().skip(3).next();
492 /// let bad_slice = &some_vec[..].iter().skip(3).next();
493 /// ```
494 /// The correct use would be:
495 /// ```rust
496 /// let some_vec = vec![0, 1, 2, 3];
497 /// let bad_vec = some_vec.iter().nth(3);
498 /// let bad_slice = &some_vec[..].iter().nth(3);
499 /// ```
500 declare_lint! {
501     pub ITER_SKIP_NEXT,
502     Warn,
503     "using `.skip(x).next()` on an iterator"
504 }
505
506 /// **What it does:** Checks for use of `.get().unwrap()` (or
507 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
508 ///
509 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
510 /// concise.
511 ///
512 /// **Known problems:** None.
513 ///
514 /// **Example:**
515 /// ```rust
516 /// let some_vec = vec![0, 1, 2, 3];
517 /// let last = some_vec.get(3).unwrap();
518 /// *some_vec.get_mut(0).unwrap() = 1;
519 /// ```
520 /// The correct use would be:
521 /// ```rust
522 /// let some_vec = vec![0, 1, 2, 3];
523 /// let last = some_vec[3];
524 /// some_vec[0] = 1;
525 /// ```
526 declare_lint! {
527     pub GET_UNWRAP,
528     Warn,
529     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
530 }
531
532 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
533 /// `&str` or `String`.
534 ///
535 /// **Why is this bad?** `.push_str(s)` is clearer
536 ///
537 /// **Known problems:** None.
538 ///
539 /// **Example:**
540 /// ```rust
541 /// let abc = "abc";
542 /// let def = String::from("def");
543 /// let mut s = String::new();
544 /// s.extend(abc.chars());
545 /// s.extend(def.chars());
546 /// ```
547 /// The correct use would be:
548 /// ```rust
549 /// let abc = "abc";
550 /// let def = String::from("def");
551 /// let mut s = String::new();
552 /// s.push_str(abc);
553 /// s.push_str(&def));
554 /// ```
555 declare_lint! {
556     pub STRING_EXTEND_CHARS,
557     Warn,
558     "using `x.extend(s.chars())` where s is a `&str` or `String`"
559 }
560
561 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
562 /// create a `Vec`.
563 ///
564 /// **Why is this bad?** `.to_vec()` is clearer
565 ///
566 /// **Known problems:** None.
567 ///
568 /// **Example:**
569 /// ```rust
570 /// let s = [1,2,3,4,5];
571 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
572 /// ```
573 /// The better use would be:
574 /// ```rust
575 /// let s = [1,2,3,4,5];
576 /// let s2 : Vec<isize> = s.to_vec();
577 /// ```
578 declare_lint! {
579     pub ITER_CLONED_COLLECT,
580     Warn,
581     "using `.cloned().collect()` on slice to create a `Vec`"
582 }
583
584 /// **What it does:** Checks for usage of `.chars().last()` or
585 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
586 ///
587 /// **Why is this bad?** Readability, this can be written more concisely as
588 /// `_.ends_with(_)`.
589 ///
590 /// **Known problems:** None.
591 ///
592 /// **Example:**
593 /// ```rust
594 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
595 /// ```
596 declare_lint! {
597     pub CHARS_LAST_CMP,
598     Warn,
599     "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
600 }
601
602 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
603 /// types before and after the call are the same.
604 ///
605 /// **Why is this bad?** The call is unnecessary.
606 ///
607 /// **Known problems:** None.
608 ///
609 /// **Example:**
610 /// ```rust
611 /// let x: &[i32] = &[1,2,3,4,5];
612 /// do_stuff(x.as_ref());
613 /// ```
614 /// The correct use would be:
615 /// ```rust
616 /// let x: &[i32] = &[1,2,3,4,5];
617 /// do_stuff(x);
618 /// ```
619 declare_lint! {
620     pub USELESS_ASREF,
621     Warn,
622     "using `as_ref` where the types before and after the call are the same"
623 }
624
625
626 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
627 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
628 /// `sum` or `product`.
629 ///
630 /// **Why is this bad?** Readability.
631 ///
632 /// **Known problems:** None.
633 ///
634 /// **Example:**
635 /// ```rust
636 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
637 /// ```
638 /// This could be written as:
639 /// ```rust
640 /// let _ = (0..3).any(|x| x > 2);
641 /// ```
642 declare_lint! {
643     pub UNNECESSARY_FOLD,
644     Warn,
645     "using `fold` when a more succinct alternative exists"
646 }
647
648 impl LintPass for Pass {
649     fn get_lints(&self) -> LintArray {
650         lint_array!(
651             OPTION_UNWRAP_USED,
652             RESULT_UNWRAP_USED,
653             SHOULD_IMPLEMENT_TRAIT,
654             WRONG_SELF_CONVENTION,
655             WRONG_PUB_SELF_CONVENTION,
656             OK_EXPECT,
657             OPTION_MAP_UNWRAP_OR,
658             OPTION_MAP_UNWRAP_OR_ELSE,
659             RESULT_MAP_UNWRAP_OR_ELSE,
660             OPTION_MAP_OR_NONE,
661             OR_FUN_CALL,
662             CHARS_NEXT_CMP,
663             CHARS_LAST_CMP,
664             CLONE_ON_COPY,
665             CLONE_ON_REF_PTR,
666             CLONE_DOUBLE_REF,
667             NEW_RET_NO_SELF,
668             SINGLE_CHAR_PATTERN,
669             SEARCH_IS_SOME,
670             TEMPORARY_CSTRING_AS_PTR,
671             FILTER_NEXT,
672             FILTER_MAP,
673             ITER_NTH,
674             ITER_SKIP_NEXT,
675             GET_UNWRAP,
676             STRING_EXTEND_CHARS,
677             ITER_CLONED_COLLECT,
678             USELESS_ASREF,
679             UNNECESSARY_FOLD
680         )
681     }
682 }
683
684 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
685     #[allow(unused_attributes)]
686     // ^ required because `cyclomatic_complexity` attribute shows up as unused
687     #[cyclomatic_complexity = "30"]
688     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
689         if in_macro(expr.span) {
690             return;
691         }
692
693         match expr.node {
694             hir::ExprMethodCall(ref method_call, ref method_span, ref args) => {
695                 // Chain calls
696                 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
697                 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
698                     lint_get_unwrap(cx, expr, arglists[0], false);
699                 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
700                     lint_get_unwrap(cx, expr, arglists[0], true);
701                 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
702                     lint_unwrap(cx, expr, arglists[0]);
703                 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
704                     lint_ok_expect(cx, expr, arglists[0]);
705                 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
706                     lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
707                 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
708                     lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
709                 } else if let Some(arglists) = method_chain_args(expr, &["map_or"]) {
710                     lint_map_or_none(cx, expr, arglists[0]);
711                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
712                     lint_filter_next(cx, expr, arglists[0]);
713                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
714                     lint_filter_map(cx, expr, arglists[0], arglists[1]);
715                 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
716                     lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
717                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
718                     lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
719                 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
720                     lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
721                 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
722                     lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
723                 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
724                     lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
725                 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
726                     lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
727                 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
728                     lint_extend(cx, expr, arglists[0]);
729                 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
730                     lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
731                 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
732                     lint_iter_nth(cx, expr, arglists[0], false);
733                 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
734                     lint_iter_nth(cx, expr, arglists[0], true);
735                 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
736                     lint_iter_skip_next(cx, expr);
737                 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
738                     lint_iter_cloned_collect(cx, expr, arglists[0]);
739                 } else if let Some(arglists) = method_chain_args(expr, &["as_ref"]) {
740                     lint_asref(cx, expr, "as_ref", arglists[0]);
741                 } else if let Some(arglists) = method_chain_args(expr, &["as_mut"]) {
742                     lint_asref(cx, expr, "as_mut", arglists[0]);
743                 } else if let Some(arglists) = method_chain_args(expr, &["fold"]) {
744                     lint_unnecessary_fold(cx, expr, arglists[0]);
745                 }
746
747                 lint_or_fun_call(cx, expr, *method_span, &method_call.name.as_str(), args);
748
749                 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
750                 if args.len() == 1 && method_call.name == "clone" {
751                     lint_clone_on_copy(cx, expr, &args[0], self_ty);
752                     lint_clone_on_ref_ptr(cx, expr, &args[0]);
753                 }
754
755                 match self_ty.sty {
756                     ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
757                         if method_call.name == method && args.len() > pos {
758                             lint_single_char_pattern(cx, expr, &args[pos]);
759                         }
760                     },
761                     _ => (),
762                 }
763             },
764             hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
765                 let mut info = BinaryExprInfo {
766                     expr: expr,
767                     chain: lhs,
768                     other: rhs,
769                     eq: op.node == hir::BiEq,
770                 };
771                 lint_binary_expr_with_method_call(cx, &mut info);
772             },
773             _ => (),
774         }
775     }
776
777     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
778         if in_external_macro(cx, implitem.span) {
779             return;
780         }
781         let name = implitem.name;
782         let parent = cx.tcx.hir.get_parent(implitem.id);
783         let item = cx.tcx.hir.expect_item(parent);
784         if_chain! {
785             if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
786             if let Some(first_arg_ty) = sig.decl.inputs.get(0);
787             if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
788             if let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node;
789             then {
790                 if cx.access_levels.is_exported(implitem.id) {
791                 // check missing trait implementations
792                     for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
793                         if name == method_name &&
794                         sig.decl.inputs.len() == n_args &&
795                         out_type.matches(&sig.decl.output) &&
796                         self_kind.matches(first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
797                             span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
798                                 "defining a method called `{}` on this type; consider implementing \
799                                 the `{}` trait or choosing a less ambiguous name", name, trait_name));
800                         }
801                     }
802                 }
803
804                 // check conventions w.r.t. conversion method names and predicates
805                 let def_id = cx.tcx.hir.local_def_id(item.id);
806                 let ty = cx.tcx.type_of(def_id);
807                 let is_copy = is_copy(cx, ty);
808                 for &(ref conv, self_kinds) in &CONVENTIONS {
809                     if_chain! {
810                         if conv.check(&name.as_str());
811                         if !self_kinds
812                             .iter()
813                             .any(|k| k.matches(first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
814                         then {
815                             let lint = if item.vis == hir::Visibility::Public {
816                                 WRONG_PUB_SELF_CONVENTION
817                             } else {
818                                 WRONG_SELF_CONVENTION
819                             };
820                             span_lint(cx,
821                                       lint,
822                                       first_arg.pat.span,
823                                       &format!("methods called `{}` usually take {}; consider choosing a less \
824                                                 ambiguous name",
825                                                conv,
826                                                &self_kinds.iter()
827                                                           .map(|k| k.description())
828                                                           .collect::<Vec<_>>()
829                                                           .join(" or ")));
830                         }
831                     }
832                 }
833
834                 let ret_ty = return_ty(cx, implitem.id);
835                 if name == "new" &&
836                    !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
837                     span_lint(cx,
838                               NEW_RET_NO_SELF,
839                               implitem.span,
840                               "methods called `new` usually return `Self`");
841                 }
842             }
843         }
844     }
845 }
846
847 /// Checks for the `OR_FUN_CALL` lint.
848 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
849     /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
850     fn check_unwrap_or_default(
851         cx: &LateContext,
852         name: &str,
853         fun: &hir::Expr,
854         self_expr: &hir::Expr,
855         arg: &hir::Expr,
856         or_has_args: bool,
857         span: Span,
858     ) -> bool {
859         if or_has_args {
860             return false;
861         }
862
863         if name == "unwrap_or" {
864             if let hir::ExprPath(ref qpath) = fun.node {
865                 let path = &*last_path_segment(qpath).name.as_str();
866
867                 if ["default", "new"].contains(&path) {
868                     let arg_ty = cx.tables.expr_ty(arg);
869                     let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
870                         default_trait_id
871                     } else {
872                         return false;
873                     };
874
875                     if implements_trait(cx, arg_ty, default_trait_id, &[]) {
876                         span_lint_and_sugg(
877                             cx,
878                             OR_FUN_CALL,
879                             span,
880                             &format!("use of `{}` followed by a call to `{}`", name, path),
881                             "try this",
882                             format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
883                         );
884                         return true;
885                     }
886                 }
887             }
888         }
889
890         false
891     }
892
893     /// Check for `*or(foo())`.
894     fn check_general_case(
895         cx: &LateContext,
896         name: &str,
897         method_span: Span,
898         fun_span: Span,
899         self_expr: &hir::Expr,
900         arg: &hir::Expr,
901         or_has_args: bool,
902         span: Span,
903     ) {
904         // (path, fn_has_argument, methods, suffix)
905         let know_types: &[(&[_], _, &[_], _)] = &[
906             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
907             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
908             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
909             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
910         ];
911
912         // early check if the name is one we care about
913         if know_types.iter().all(|k| !k.2.contains(&name)) {
914             return;
915         }
916
917         // don't lint for constant values
918         let owner_def = cx.tcx.hir.get_parent_did(arg.id);
919         let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
920         if promotable {
921             return;
922         }
923
924         let self_ty = cx.tables.expr_ty(self_expr);
925
926         let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
927             know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
928         {
929             (fn_has_arguments, poss, suffix)
930         } else {
931             return;
932         };
933
934         if !poss.contains(&name) {
935             return;
936         }
937
938         let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
939             (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
940             (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
941             (false, true) => snippet(cx, fun_span, ".."),
942         };
943         let span_replace_word = method_span.with_hi(span.hi());
944         span_lint_and_sugg(
945             cx,
946             OR_FUN_CALL,
947             span_replace_word,
948             &format!("use of `{}` followed by a function call", name),
949             "try this",
950             format!("{}_{}({})", name, suffix, sugg),
951         );
952     }
953
954     if args.len() == 2 {
955         match args[1].node {
956             hir::ExprCall(ref fun, ref or_args) => {
957                 let or_has_args = !or_args.is_empty();
958                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
959                     check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
960                 }
961             },
962             hir::ExprMethodCall(_, span, ref or_args) => {
963                 check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
964             },
965             _ => {},
966         }
967     }
968 }
969
970 /// Checks for the `CLONE_ON_COPY` lint.
971 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
972     let ty = cx.tables.expr_ty(expr);
973     if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
974         if let ty::TyRef(_, ty::TypeAndMut { ty: innermost, .. }) = inner.sty {
975             span_lint_and_then(
976                 cx,
977                 CLONE_DOUBLE_REF,
978                 expr.span,
979                 "using `clone` on a double-reference; \
980                  this will copy the reference instead of cloning the inner type",
981                 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
982                     let mut ty = innermost;
983                     let mut n = 0;
984                     while let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = ty.sty {
985                         ty = inner;
986                         n += 1;
987                     }
988                     let refs: String = iter::repeat('&').take(n + 1).collect();
989                     let derefs: String = iter::repeat('*').take(n).collect();
990                     let explicit = format!("{}{}::clone({})", refs, ty, snip);
991                     db.span_suggestion(expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()));
992                     db.span_suggestion(expr.span, "or try being explicit about what type to clone", explicit);
993                 },
994             );
995             return; // don't report clone_on_copy
996         }
997     }
998
999     if is_copy(cx, ty) {
1000         let snip;
1001         if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1002             if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
1003                 let parent = cx.tcx.hir.get_parent_node(expr.id);
1004                 match cx.tcx.hir.get(parent) {
1005                     hir::map::NodeExpr(parent) => match parent.node {
1006                         // &*x is a nop, &x.clone() is not
1007                         hir::ExprAddrOf(..) |
1008                         // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1009                         hir::ExprMethodCall(..) => return,
1010                         _ => {},
1011                     }
1012                     hir::map::NodeStmt(stmt) => {
1013                         if let hir::StmtDecl(ref decl, _) = stmt.node {
1014                             if let hir::DeclLocal(ref loc) = decl.node {
1015                                 if let hir::PatKind::Ref(..) = loc.pat.node {
1016                                     // let ref y = *x borrows x, let ref y = x.clone() does not
1017                                     return;
1018                                 }
1019                             }
1020                         }
1021                     },
1022                     _ => {},
1023                 }
1024                 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
1025             } else {
1026                 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1027             }
1028         } else {
1029             snip = None;
1030         }
1031         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1032             if let Some((text, snip)) = snip {
1033                 db.span_suggestion(expr.span, text, snip);
1034             }
1035         });
1036     }
1037 }
1038
1039 fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1040     let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(arg));
1041
1042     if let ty::TyAdt(_, subst) = obj_ty.sty {
1043         let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1044             "Rc"
1045         } else if match_type(cx, obj_ty, &paths::ARC) {
1046             "Arc"
1047         } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1048             "Weak"
1049         } else {
1050             return;
1051         };
1052
1053         span_lint_and_sugg(
1054             cx,
1055             CLONE_ON_REF_PTR,
1056             expr.span,
1057             "using '.clone()' on a ref-counted pointer",
1058             "try this",
1059             format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1060         );
1061     }
1062 }
1063
1064
1065 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1066     let arg = &args[1];
1067     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1068         let target = &arglists[0][0];
1069         let (self_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(target));
1070         let ref_str = if self_ty.sty == ty::TyStr {
1071             ""
1072         } else if match_type(cx, self_ty, &paths::STRING) {
1073             "&"
1074         } else {
1075             return;
1076         };
1077
1078         span_lint_and_sugg(
1079             cx,
1080             STRING_EXTEND_CHARS,
1081             expr.span,
1082             "calling `.extend(_.chars())`",
1083             "try this",
1084             format!(
1085                 "{}.push_str({}{})",
1086                 snippet(cx, args[0].span, "_"),
1087                 ref_str,
1088                 snippet(cx, target.span, "_")
1089             ),
1090         );
1091     }
1092 }
1093
1094 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1095     let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&args[0]));
1096     if match_type(cx, obj_ty, &paths::STRING) {
1097         lint_string_extend(cx, expr, args);
1098     }
1099 }
1100
1101 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1102     if_chain! {
1103         if let hir::ExprCall(ref fun, ref args) = new.node;
1104         if args.len() == 1;
1105         if let hir::ExprPath(ref path) = fun.node;
1106         if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1107         if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1108         then {
1109             span_lint_and_then(
1110                 cx,
1111                 TEMPORARY_CSTRING_AS_PTR,
1112                 expr.span,
1113                 "you are getting the inner pointer of a temporary `CString`",
1114                 |db| {
1115                     db.note("that pointer will be invalid outside this expression");
1116                     db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1117                 });
1118         }
1119     }
1120 }
1121
1122 fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1123     if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1124         && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1125     {
1126         span_lint(
1127             cx,
1128             ITER_CLONED_COLLECT,
1129             expr.span,
1130             "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1131              more readable",
1132         );
1133     }
1134 }
1135
1136 fn lint_unnecessary_fold(cx: &LateContext, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1137     // Check that this is a call to Iterator::fold rather than just some function called fold
1138     if !match_trait_method(cx, expr, &paths::ITERATOR) {
1139         return;
1140     }
1141
1142     assert!(fold_args.len() == 3,
1143         "Expected fold_args to have three entries - the receiver, the initial value and the closure");
1144
1145     fn check_fold_with_op(
1146         cx: &LateContext,
1147         fold_args: &[hir::Expr],
1148         op: hir::BinOp_,
1149         replacement_method_name: &str,
1150         replacement_has_args: bool) {
1151
1152         if_chain! {
1153             // Extract the body of the closure passed to fold
1154             if let hir::ExprClosure(_, _, body_id, _, _) = fold_args[2].node;
1155             let closure_body = cx.tcx.hir.body(body_id);
1156             let closure_expr = remove_blocks(&closure_body.value);
1157
1158             // Check if the closure body is of the form `acc <op> some_expr(x)`
1159             if let hir::ExprBinary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1160             if bin_op.node == op;
1161
1162             // Extract the names of the two arguments to the closure
1163             if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1164             if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1165
1166             if match_var(&*left_expr, first_arg_ident);
1167             if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1168
1169             then {
1170                 // Span containing `.fold(...)`
1171                 let next_point = cx.sess().codemap().next_point(fold_args[0].span);
1172                 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1173
1174                 let sugg = if replacement_has_args {
1175                     format!(
1176                         ".{replacement}(|{s}| {r})",
1177                         replacement = replacement_method_name,
1178                         s = second_arg_ident,
1179                         r = snippet(cx, right_expr.span, "EXPR"),
1180                     )
1181                 } else {
1182                     format!(
1183                         ".{replacement}()",
1184                         replacement = replacement_method_name,
1185                     )
1186                 };
1187
1188                 span_lint_and_sugg(
1189                     cx,
1190                     UNNECESSARY_FOLD,
1191                     fold_span,
1192                     // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
1193                     "this `.fold` can be written more succinctly using another method",
1194                     "try",
1195                     sugg,
1196                 );
1197             }
1198         }
1199     }
1200
1201     // Check if the first argument to .fold is a suitable literal
1202     match fold_args[1].node {
1203         hir::ExprLit(ref lit) => {
1204             match lit.node {
1205                 ast::LitKind::Bool(false) => check_fold_with_op(
1206                     cx, fold_args, hir::BinOp_::BiOr, "any", true
1207                 ),
1208                 ast::LitKind::Bool(true) => check_fold_with_op(
1209                     cx, fold_args, hir::BinOp_::BiAnd, "all", true
1210                 ),
1211                 ast::LitKind::Int(0, _) => check_fold_with_op(
1212                     cx, fold_args, hir::BinOp_::BiAdd, "sum", false
1213                 ),
1214                 ast::LitKind::Int(1, _) => check_fold_with_op(
1215                     cx, fold_args, hir::BinOp_::BiMul, "product", false
1216                 ),
1217                 _ => return
1218             }
1219         }
1220         _ => return
1221     };
1222 }
1223
1224 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1225     let mut_str = if is_mut { "_mut" } else { "" };
1226     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1227         "slice"
1228     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1229         "Vec"
1230     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1231         "VecDeque"
1232     } else {
1233         return; // caller is not a type that we want to lint
1234     };
1235
1236     span_lint(
1237         cx,
1238         ITER_NTH,
1239         expr.span,
1240         &format!(
1241             "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1242             mut_str,
1243             caller_type
1244         ),
1245     );
1246 }
1247
1248 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1249     // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1250     // because they do not implement `IndexMut`
1251     let expr_ty = cx.tables.expr_ty(&get_args[0]);
1252     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1253         "slice"
1254     } else if match_type(cx, expr_ty, &paths::VEC) {
1255         "Vec"
1256     } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1257         "VecDeque"
1258     } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1259         "HashMap"
1260     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1261         "BTreeMap"
1262     } else {
1263         return; // caller is not a type that we want to lint
1264     };
1265
1266     let mut_str = if is_mut { "_mut" } else { "" };
1267     let borrow_str = if is_mut { "&mut " } else { "&" };
1268     span_lint_and_sugg(
1269         cx,
1270         GET_UNWRAP,
1271         expr.span,
1272         &format!(
1273             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1274             mut_str,
1275             caller_type
1276         ),
1277         "try this",
1278         format!(
1279             "{}{}[{}]",
1280             borrow_str,
1281             snippet(cx, get_args[0].span, "_"),
1282             snippet(cx, get_args[1].span, "_")
1283         ),
1284     );
1285 }
1286
1287 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
1288     // lint if caller of skip is an Iterator
1289     if match_trait_method(cx, expr, &paths::ITERATOR) {
1290         span_lint(
1291             cx,
1292             ITER_SKIP_NEXT,
1293             expr.span,
1294             "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1295         );
1296     }
1297 }
1298
1299 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
1300     fn may_slice(cx: &LateContext, ty: Ty) -> bool {
1301         match ty.sty {
1302             ty::TySlice(_) => true,
1303             ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1304             ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1305             ty::TyArray(_, size) => const_to_u64(size) < 32,
1306             ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => may_slice(cx, inner),
1307             _ => false,
1308         }
1309     }
1310
1311     if let hir::ExprMethodCall(ref path, _, ref args) = expr.node {
1312         if path.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1313             sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1314         } else {
1315             None
1316         }
1317     } else {
1318         match ty.sty {
1319             ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1320             ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1321             ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => if may_slice(cx, inner) {
1322                 sugg::Sugg::hir_opt(cx, expr)
1323             } else {
1324                 None
1325             },
1326             _ => None,
1327         }
1328     }
1329 }
1330
1331 /// lint use of `unwrap()` for `Option`s and `Result`s
1332 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1333     let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&unwrap_args[0]));
1334
1335     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1336         Some((OPTION_UNWRAP_USED, "an Option", "None"))
1337     } else if match_type(cx, obj_ty, &paths::RESULT) {
1338         Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1339     } else {
1340         None
1341     };
1342
1343     if let Some((lint, kind, none_value)) = mess {
1344         span_lint(
1345             cx,
1346             lint,
1347             expr.span,
1348             &format!(
1349                 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1350                  using expect() to provide a better panic \
1351                  message",
1352                 kind,
1353                 none_value
1354             ),
1355         );
1356     }
1357 }
1358
1359 /// lint use of `ok().expect()` for `Result`s
1360 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1361     // lint if the caller of `ok()` is a `Result`
1362     if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1363         let result_type = cx.tables.expr_ty(&ok_args[0]);
1364         if let Some(error_type) = get_error_type(cx, result_type) {
1365             if has_debug_impl(error_type, cx) {
1366                 span_lint(
1367                     cx,
1368                     OK_EXPECT,
1369                     expr.span,
1370                     "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1371                 );
1372             }
1373         }
1374     }
1375 }
1376
1377 /// lint use of `map().unwrap_or()` for `Option`s
1378 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1379     // lint if the caller of `map()` is an `Option`
1380     if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1381         // get snippets for args to map() and unwrap_or()
1382         let map_snippet = snippet(cx, map_args[1].span, "..");
1383         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1384         // lint message
1385         // comparing the snippet from source to raw text ("None") below is safe
1386         // because we already have checked the type.
1387         let arg = if unwrap_snippet == "None" {
1388             "None"
1389         } else {
1390             "a"
1391         };
1392         let suggest = if unwrap_snippet == "None" {
1393             "and_then(f)"
1394         } else {
1395             "map_or(a, f)"
1396         };
1397         let msg = &format!(
1398             "called `map(f).unwrap_or({})` on an Option value. \
1399              This can be done more directly by calling `{}` instead",
1400             arg,
1401             suggest
1402         );
1403         // lint, with note if neither arg is > 1 line and both map() and
1404         // unwrap_or() have the same span
1405         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1406         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1407         if same_span && !multiline {
1408             let suggest = if unwrap_snippet == "None" {
1409                 format!("and_then({})", map_snippet)
1410             } else {
1411                 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1412             };
1413             let note = format!(
1414                 "replace `map({}).unwrap_or({})` with `{}`",
1415                 map_snippet,
1416                 unwrap_snippet,
1417                 suggest
1418             );
1419             span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, &note);
1420         } else if same_span && multiline {
1421             span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1422         };
1423     }
1424 }
1425
1426 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1427 fn lint_map_unwrap_or_else<'a, 'tcx>(
1428     cx: &LateContext<'a, 'tcx>,
1429     expr: &'tcx hir::Expr,
1430     map_args: &'tcx [hir::Expr],
1431     unwrap_args: &'tcx [hir::Expr],
1432 ) {
1433     // lint if the caller of `map()` is an `Option`
1434     let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1435     let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1436     if is_option || is_result {
1437         // lint message
1438         let msg = if is_option {
1439             "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1440              `map_or_else(g, f)` instead"
1441         } else {
1442             "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1443              `ok().map_or_else(g, f)` instead"
1444         };
1445         // get snippets for args to map() and unwrap_or_else()
1446         let map_snippet = snippet(cx, map_args[1].span, "..");
1447         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1448         // lint, with note if neither arg is > 1 line and both map() and
1449         // unwrap_or_else() have the same span
1450         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1451         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1452         if same_span && !multiline {
1453             span_note_and_lint(
1454                 cx,
1455                 if is_option {
1456                     OPTION_MAP_UNWRAP_OR_ELSE
1457                 } else {
1458                     RESULT_MAP_UNWRAP_OR_ELSE
1459                 },
1460                 expr.span,
1461                 msg,
1462                 expr.span,
1463                 &format!(
1464                     "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1465                     map_snippet,
1466                     unwrap_snippet,
1467                     if is_result { "ok()." } else { "" }
1468                 ),
1469             );
1470         } else if same_span && multiline {
1471             span_lint(
1472                 cx,
1473                 if is_option {
1474                     OPTION_MAP_UNWRAP_OR_ELSE
1475                 } else {
1476                     RESULT_MAP_UNWRAP_OR_ELSE
1477                 },
1478                 expr.span,
1479                 msg,
1480             );
1481         };
1482     }
1483 }
1484
1485 /// lint use of `_.map_or(None, _)` for `Option`s
1486 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1487     if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1488         // check if the first non-self argument to map_or() is None
1489         let map_or_arg_is_none = if let hir::Expr_::ExprPath(ref qpath) = map_or_args[1].node {
1490             match_qpath(qpath, &paths::OPTION_NONE)
1491         } else {
1492             false
1493         };
1494
1495         if map_or_arg_is_none {
1496             // lint message
1497             let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1498                        `and_then(f)` instead";
1499             let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1500             let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1501             let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1502             span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1503                 db.span_suggestion(expr.span, "try using and_then instead", hint);
1504             });
1505         }
1506     }
1507 }
1508
1509 /// lint use of `filter().next()` for `Iterators`
1510 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1511     // lint if caller of `.filter().next()` is an Iterator
1512     if match_trait_method(cx, expr, &paths::ITERATOR) {
1513         let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1514                    `.find(p)` instead.";
1515         let filter_snippet = snippet(cx, filter_args[1].span, "..");
1516         if filter_snippet.lines().count() <= 1 {
1517             // add note if not multi-line
1518             span_note_and_lint(
1519                 cx,
1520                 FILTER_NEXT,
1521                 expr.span,
1522                 msg,
1523                 expr.span,
1524                 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1525             );
1526         } else {
1527             span_lint(cx, FILTER_NEXT, expr.span, msg);
1528         }
1529     }
1530 }
1531
1532 /// lint use of `filter().map()` for `Iterators`
1533 fn lint_filter_map<'a, 'tcx>(
1534     cx: &LateContext<'a, 'tcx>,
1535     expr: &'tcx hir::Expr,
1536     _filter_args: &'tcx [hir::Expr],
1537     _map_args: &'tcx [hir::Expr],
1538 ) {
1539     // lint if caller of `.filter().map()` is an Iterator
1540     if match_trait_method(cx, expr, &paths::ITERATOR) {
1541         let msg = "called `filter(p).map(q)` on an `Iterator`. \
1542                    This is more succinctly expressed by calling `.filter_map(..)` instead.";
1543         span_lint(cx, FILTER_MAP, expr.span, msg);
1544     }
1545 }
1546
1547 /// lint use of `filter().map()` for `Iterators`
1548 fn lint_filter_map_map<'a, 'tcx>(
1549     cx: &LateContext<'a, 'tcx>,
1550     expr: &'tcx hir::Expr,
1551     _filter_args: &'tcx [hir::Expr],
1552     _map_args: &'tcx [hir::Expr],
1553 ) {
1554     // lint if caller of `.filter().map()` is an Iterator
1555     if match_trait_method(cx, expr, &paths::ITERATOR) {
1556         let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1557                    This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1558         span_lint(cx, FILTER_MAP, expr.span, msg);
1559     }
1560 }
1561
1562 /// lint use of `filter().flat_map()` for `Iterators`
1563 fn lint_filter_flat_map<'a, 'tcx>(
1564     cx: &LateContext<'a, 'tcx>,
1565     expr: &'tcx hir::Expr,
1566     _filter_args: &'tcx [hir::Expr],
1567     _map_args: &'tcx [hir::Expr],
1568 ) {
1569     // lint if caller of `.filter().flat_map()` is an Iterator
1570     if match_trait_method(cx, expr, &paths::ITERATOR) {
1571         let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1572                    This is more succinctly expressed by calling `.flat_map(..)` \
1573                    and filtering by returning an empty Iterator.";
1574         span_lint(cx, FILTER_MAP, expr.span, msg);
1575     }
1576 }
1577
1578 /// lint use of `filter_map().flat_map()` for `Iterators`
1579 fn lint_filter_map_flat_map<'a, 'tcx>(
1580     cx: &LateContext<'a, 'tcx>,
1581     expr: &'tcx hir::Expr,
1582     _filter_args: &'tcx [hir::Expr],
1583     _map_args: &'tcx [hir::Expr],
1584 ) {
1585     // lint if caller of `.filter_map().flat_map()` is an Iterator
1586     if match_trait_method(cx, expr, &paths::ITERATOR) {
1587         let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1588                    This is more succinctly expressed by calling `.flat_map(..)` \
1589                    and filtering by returning an empty Iterator.";
1590         span_lint(cx, FILTER_MAP, expr.span, msg);
1591     }
1592 }
1593
1594 /// lint searching an Iterator followed by `is_some()`
1595 fn lint_search_is_some<'a, 'tcx>(
1596     cx: &LateContext<'a, 'tcx>,
1597     expr: &'tcx hir::Expr,
1598     search_method: &str,
1599     search_args: &'tcx [hir::Expr],
1600     is_some_args: &'tcx [hir::Expr],
1601 ) {
1602     // lint if caller of search is an Iterator
1603     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1604         let msg = format!(
1605             "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1606              expressed by calling `any()`.",
1607             search_method
1608         );
1609         let search_snippet = snippet(cx, search_args[1].span, "..");
1610         if search_snippet.lines().count() <= 1 {
1611             // add note if not multi-line
1612             span_note_and_lint(
1613                 cx,
1614                 SEARCH_IS_SOME,
1615                 expr.span,
1616                 &msg,
1617                 expr.span,
1618                 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1619             );
1620         } else {
1621             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1622         }
1623     }
1624 }
1625
1626 /// Used for `lint_binary_expr_with_method_call`.
1627 #[derive(Copy, Clone)]
1628 struct BinaryExprInfo<'a> {
1629     expr: &'a hir::Expr,
1630     chain: &'a hir::Expr,
1631     other: &'a hir::Expr,
1632     eq: bool,
1633 }
1634
1635 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1636 fn lint_binary_expr_with_method_call<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, info: &mut BinaryExprInfo) {
1637     macro_rules! lint_with_both_lhs_and_rhs {
1638         ($func:ident, $cx:expr, $info:ident) => {
1639             if !$func($cx, $info) {
1640                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1641                 if $func($cx, $info) {
1642                     return;
1643                 }
1644             }
1645         }
1646     }
1647
1648     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1649     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1650     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1651     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1652 }
1653
1654 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1655 fn lint_chars_cmp<'a, 'tcx>(
1656     cx: &LateContext<'a, 'tcx>,
1657     info: &BinaryExprInfo,
1658     chain_methods: &[&str],
1659     lint: &'static Lint,
1660     suggest: &str,
1661 ) -> bool {
1662     if_chain! {
1663         if let Some(args) = method_chain_args(info.chain, chain_methods);
1664         if let hir::ExprCall(ref fun, ref arg_char) = info.other.node;
1665         if arg_char.len() == 1;
1666         if let hir::ExprPath(ref qpath) = fun.node;
1667         if let Some(segment) = single_segment_path(qpath);
1668         if segment.name == "Some";
1669         then {
1670             let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1671
1672             if self_ty.sty != ty::TyStr {
1673                 return false;
1674             }
1675
1676             span_lint_and_sugg(cx,
1677                                lint,
1678                                info.expr.span,
1679                                &format!("you should use the `{}` method", suggest),
1680                                "like this",
1681                                format!("{}{}.{}({})",
1682                                        if info.eq { "" } else { "!" },
1683                                        snippet(cx, args[0][0].span, "_"),
1684                                        suggest,
1685                                        snippet(cx, arg_char[0].span, "_")));
1686
1687             return true;
1688         }
1689     }
1690
1691     false
1692 }
1693
1694 /// Checks for the `CHARS_NEXT_CMP` lint.
1695 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1696     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1697 }
1698
1699 /// Checks for the `CHARS_LAST_CMP` lint.
1700 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1701     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1702         true
1703     } else {
1704         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1705     }
1706 }
1707
1708 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1709 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1710     cx: &LateContext<'a, 'tcx>,
1711     info: &BinaryExprInfo,
1712     chain_methods: &[&str],
1713     lint: &'static Lint,
1714     suggest: &str,
1715 ) -> bool {
1716     if_chain! {
1717         if let Some(args) = method_chain_args(info.chain, chain_methods);
1718         if let hir::ExprLit(ref lit) = info.other.node;
1719         if let ast::LitKind::Char(c) = lit.node;
1720         then {
1721             span_lint_and_sugg(
1722                 cx,
1723                 lint,
1724                 info.expr.span,
1725                 &format!("you should use the `{}` method", suggest),
1726                 "like this",
1727                 format!("{}{}.{}('{}')",
1728                         if info.eq { "" } else { "!" },
1729                         snippet(cx, args[0][0].span, "_"),
1730                         suggest,
1731                         c)
1732             );
1733
1734             return true;
1735         }
1736     }
1737
1738     false
1739 }
1740
1741 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
1742 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1743     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
1744 }
1745
1746 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
1747 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1748     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
1749         true
1750     } else {
1751         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
1752     }
1753 }
1754
1755 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1756 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
1757     let parent_item = cx.tcx.hir.get_parent(arg.id);
1758     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1759     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1760     if let Ok(&ty::Const {
1761         val: ConstVal::Str(r),
1762         ..
1763     }) = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(arg)
1764     {
1765         if r.len() == 1 {
1766             let c = r.chars().next().unwrap();
1767             let snip = snippet(cx, expr.span, "..");
1768             let hint = snip.replace(
1769                 &format!("\"{}\"", c.escape_default()),
1770                 &format!("'{}'", c.escape_default()));
1771             span_lint_and_then(
1772                 cx,
1773                 SINGLE_CHAR_PATTERN,
1774                 arg.span,
1775                 "single-character string constant used as pattern",
1776                 |db| {
1777                     db.span_suggestion(expr.span, "try using a char instead", hint);
1778                 },
1779             );
1780         }
1781     }
1782 }
1783
1784 /// Checks for the `USELESS_ASREF` lint.
1785 fn lint_asref(cx: &LateContext, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
1786     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
1787     // check if the call is to the actual `AsRef` or `AsMut` trait
1788     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
1789         // check if the type after `as_ref` or `as_mut` is the same as before
1790         let recvr = &as_ref_args[0];
1791         let rcv_ty = cx.tables.expr_ty(recvr);
1792         let res_ty = cx.tables.expr_ty(expr);
1793         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
1794         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
1795         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
1796             span_lint_and_sugg(
1797                 cx,
1798                 USELESS_ASREF,
1799                 expr.span,
1800                 &format!("this call to `{}` does nothing", call_name),
1801                 "try this",
1802                 snippet(cx, recvr.span, "_").into_owned(),
1803             );
1804         }
1805     }
1806 }
1807
1808 /// Given a `Result<T, E>` type, return its error type (`E`).
1809 fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
1810     if let ty::TyAdt(_, substs) = ty.sty {
1811         if match_type(cx, ty, &paths::RESULT) {
1812             substs.types().nth(1)
1813         } else {
1814             None
1815         }
1816     } else {
1817         None
1818     }
1819 }
1820
1821 /// This checks whether a given type is known to implement Debug.
1822 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1823     match cx.tcx.lang_items().debug_trait() {
1824         Some(debug) => implements_trait(cx, ty, debug, &[]),
1825         None => false,
1826     }
1827 }
1828
1829 enum Convention {
1830     Eq(&'static str),
1831     StartsWith(&'static str),
1832 }
1833
1834 #[cfg_attr(rustfmt, rustfmt_skip)]
1835 const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
1836     (Convention::Eq("new"), &[SelfKind::No]),
1837     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1838     (Convention::StartsWith("from_"), &[SelfKind::No]),
1839     (Convention::StartsWith("into_"), &[SelfKind::Value]),
1840     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1841     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1842 ];
1843
1844 #[cfg_attr(rustfmt, rustfmt_skip)]
1845 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
1846     ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1847     ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1848     ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1849     ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1850     ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1851     ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1852     ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1853     ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1854     ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1855     ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1856     ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1857     ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1858     ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1859     ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1860     ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1861     ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1862     ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1863     ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1864     ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1865     ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1866     ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1867     ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1868     ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1869     ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1870     ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1871     ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1872     ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1873     ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1874     ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1875     ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1876 ];
1877
1878 #[cfg_attr(rustfmt, rustfmt_skip)]
1879 const PATTERN_METHODS: [(&str, usize); 17] = [
1880     ("contains", 1),
1881     ("starts_with", 1),
1882     ("ends_with", 1),
1883     ("find", 1),
1884     ("rfind", 1),
1885     ("split", 1),
1886     ("rsplit", 1),
1887     ("split_terminator", 1),
1888     ("rsplit_terminator", 1),
1889     ("splitn", 2),
1890     ("rsplitn", 2),
1891     ("matches", 1),
1892     ("rmatches", 1),
1893     ("match_indices", 1),
1894     ("rmatch_indices", 1),
1895     ("trim_left_matches", 1),
1896     ("trim_right_matches", 1),
1897 ];
1898
1899
1900 #[derive(Clone, Copy, PartialEq, Debug)]
1901 enum SelfKind {
1902     Value,
1903     Ref,
1904     RefMut,
1905     No,
1906 }
1907
1908 impl SelfKind {
1909     fn matches(
1910         self,
1911         ty: &hir::Ty,
1912         arg: &hir::Arg,
1913         self_ty: &hir::Ty,
1914         allow_value_for_ref: bool,
1915         generics: &hir::Generics,
1916     ) -> bool {
1917         // Self types in the HIR are desugared to explicit self types. So it will
1918         // always be `self:
1919         // SomeType`,
1920         // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
1921         // the impl is on `Foo`)
1922         // Thus, we only need to test equality against the impl self type or if it is
1923         // an explicit
1924         // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
1925         // `Self`, `&mut Self`,
1926         // and `Box<Self>`, including the equivalent types with `Foo`.
1927
1928         let is_actually_self = |ty| is_self_ty(ty) || ty == self_ty;
1929         if is_self(arg) {
1930             match self {
1931                 SelfKind::Value => is_actually_self(ty),
1932                 SelfKind::Ref | SelfKind::RefMut => {
1933                     if allow_value_for_ref && is_actually_self(ty) {
1934                         return true;
1935                     }
1936                     match ty.node {
1937                         hir::TyRptr(_, ref mt_ty) => {
1938                             let mutability_match = if self == SelfKind::Ref {
1939                                 mt_ty.mutbl == hir::MutImmutable
1940                             } else {
1941                                 mt_ty.mutbl == hir::MutMutable
1942                             };
1943                             is_actually_self(&mt_ty.ty) && mutability_match
1944                         },
1945                         _ => false,
1946                     }
1947                 },
1948                 _ => false,
1949             }
1950         } else {
1951             match self {
1952                 SelfKind::Value => false,
1953                 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
1954                 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
1955                 SelfKind::No => true,
1956             }
1957         }
1958     }
1959
1960     fn description(&self) -> &'static str {
1961         match *self {
1962             SelfKind::Value => "self by value",
1963             SelfKind::Ref => "self by reference",
1964             SelfKind::RefMut => "self by mutable reference",
1965             SelfKind::No => "no self",
1966         }
1967     }
1968 }
1969
1970 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
1971     single_segment_ty(ty).map_or(false, |seg| {
1972         generics.ty_params().any(|param| {
1973             param.name == seg.name && param.bounds.iter().any(|bound| {
1974                 if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
1975                     let path = &ptr.trait_ref.path;
1976                     match_path(path, name) && path.segments.last().map_or(false, |s| {
1977                         if let Some(ref params) = s.parameters {
1978                             if params.parenthesized {
1979                                 false
1980                             } else {
1981                                 params.types.len() == 1
1982                                     && (is_self_ty(&params.types[0]) || is_ty(&*params.types[0], self_ty))
1983                             }
1984                         } else {
1985                             false
1986                         }
1987                     })
1988                 } else {
1989                     false
1990                 }
1991             })
1992         })
1993     })
1994 }
1995
1996 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
1997     match (&ty.node, &self_ty.node) {
1998         (
1999             &hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
2000             &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path)),
2001         ) => ty_path
2002             .segments
2003             .iter()
2004             .map(|seg| seg.name)
2005             .eq(self_ty_path.segments.iter().map(|seg| seg.name)),
2006         _ => false,
2007     }
2008 }
2009
2010 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2011     if let hir::TyPath(ref path) = ty.node {
2012         single_segment_path(path)
2013     } else {
2014         None
2015     }
2016 }
2017
2018 impl Convention {
2019     fn check(&self, other: &str) -> bool {
2020         match *self {
2021             Convention::Eq(this) => this == other,
2022             Convention::StartsWith(this) => other.starts_with(this) && this != other,
2023         }
2024     }
2025 }
2026
2027 impl fmt::Display for Convention {
2028     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2029         match *self {
2030             Convention::Eq(this) => this.fmt(f),
2031             Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2032         }
2033     }
2034 }
2035
2036 #[derive(Clone, Copy)]
2037 enum OutType {
2038     Unit,
2039     Bool,
2040     Any,
2041     Ref,
2042 }
2043
2044 impl OutType {
2045     fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
2046         match (self, ty) {
2047             (&OutType::Unit, &hir::DefaultReturn(_)) => true,
2048             (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
2049             (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2050             (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
2051             (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
2052             _ => false,
2053         }
2054     }
2055 }
2056
2057 fn is_bool(ty: &hir::Ty) -> bool {
2058     if let hir::TyPath(ref p) = ty.node {
2059         match_qpath(p, &["bool"])
2060     } else {
2061         false
2062     }
2063 }