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