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