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