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