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