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