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