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