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