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