]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
new_ret_no_self added positive test cases
[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         let ret_ty = return_ty(cx, implitem.id);
935         if name == "new" &&
936             !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
937             span_lint(cx,
938                       NEW_RET_NO_SELF,
939                       implitem.span,
940                       "methods called `new` usually return `Self`");
941         }
942     }
943 }
944
945 /// Checks for the `OR_FUN_CALL` lint.
946 fn lint_or_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
947     /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
948     fn check_unwrap_or_default(
949         cx: &LateContext<'_, '_>,
950         name: &str,
951         fun: &hir::Expr,
952         self_expr: &hir::Expr,
953         arg: &hir::Expr,
954         or_has_args: bool,
955         span: Span,
956     ) -> bool {
957         if or_has_args {
958             return false;
959         }
960
961         if name == "unwrap_or" {
962             if let hir::ExprKind::Path(ref qpath) = fun.node {
963                 let path = &*last_path_segment(qpath).ident.as_str();
964
965                 if ["default", "new"].contains(&path) {
966                     let arg_ty = cx.tables.expr_ty(arg);
967                     let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
968                         default_trait_id
969                     } else {
970                         return false;
971                     };
972
973                     if implements_trait(cx, arg_ty, default_trait_id, &[]) {
974                         span_lint_and_sugg(
975                             cx,
976                             OR_FUN_CALL,
977                             span,
978                             &format!("use of `{}` followed by a call to `{}`", name, path),
979                             "try this",
980                             format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
981                         );
982                         return true;
983                     }
984                 }
985             }
986         }
987
988         false
989     }
990
991     /// Check for `*or(foo())`.
992     #[allow(clippy::too_many_arguments)]
993     fn check_general_case(
994         cx: &LateContext<'_, '_>,
995         name: &str,
996         method_span: Span,
997         fun_span: Span,
998         self_expr: &hir::Expr,
999         arg: &hir::Expr,
1000         or_has_args: bool,
1001         span: Span,
1002     ) {
1003         // (path, fn_has_argument, methods, suffix)
1004         let know_types: &[(&[_], _, &[_], _)] = &[
1005             (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1006             (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1007             (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1008             (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1009         ];
1010
1011         // early check if the name is one we care about
1012         if know_types.iter().all(|k| !k.2.contains(&name)) {
1013             return;
1014         }
1015
1016         // don't lint for constant values
1017         let owner_def = cx.tcx.hir.get_parent_did(arg.id);
1018         let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
1019         if promotable {
1020             return;
1021         }
1022
1023         let self_ty = cx.tables.expr_ty(self_expr);
1024
1025         let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
1026             know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
1027         {
1028             (fn_has_arguments, poss, suffix)
1029         } else {
1030             return;
1031         };
1032
1033         if !poss.contains(&name) {
1034             return;
1035         }
1036
1037         let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1038             (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
1039             (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
1040             (false, true) => snippet(cx, fun_span, ".."),
1041         };
1042         let span_replace_word = method_span.with_hi(span.hi());
1043         span_lint_and_sugg(
1044             cx,
1045             OR_FUN_CALL,
1046             span_replace_word,
1047             &format!("use of `{}` followed by a function call", name),
1048             "try this",
1049             format!("{}_{}({})", name, suffix, sugg),
1050         );
1051     }
1052
1053     if args.len() == 2 {
1054         match args[1].node {
1055             hir::ExprKind::Call(ref fun, ref or_args) => {
1056                 let or_has_args = !or_args.is_empty();
1057                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1058                     check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
1059                 }
1060             },
1061             hir::ExprKind::MethodCall(_, span, ref or_args) => {
1062                 check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
1063             },
1064             _ => {},
1065         }
1066     }
1067 }
1068
1069 /// Checks for the `EXPECT_FUN_CALL` lint.
1070 fn lint_expect_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
1071     fn extract_format_args(arg: &hir::Expr) -> Option<&hir::HirVec<hir::Expr>> {
1072         let arg  = match &arg.node {
1073             hir::ExprKind::AddrOf(_, expr)=> expr,
1074             hir::ExprKind::MethodCall(method_name, _, args)
1075                 if method_name.ident.name == "as_str" ||
1076                    method_name.ident.name == "as_ref"
1077                 => &args[0],
1078             _ => arg,
1079         };
1080
1081         if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg.node {
1082             if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1 {
1083                 if let hir::ExprKind::Call(_, ref format_args) = inner_args[0].node {
1084                     return Some(format_args);
1085                 }
1086             }
1087         }
1088
1089         None
1090     }
1091
1092     fn generate_format_arg_snippet(cx: &LateContext<'_, '_>, a: &hir::Expr) -> String {
1093         if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
1094             if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
1095                 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
1096                     return snippet(cx, format_arg_expr_tup[0].span, "..").into_owned();
1097                 }
1098             }
1099         };
1100
1101         snippet(cx, a.span, "..").into_owned()
1102     }
1103
1104     fn check_general_case(
1105         cx: &LateContext<'_, '_>,
1106         name: &str,
1107         method_span: Span,
1108         self_expr: &hir::Expr,
1109         arg: &hir::Expr,
1110         span: Span,
1111     ) {
1112         fn is_call(node: &hir::ExprKind) -> bool {
1113             match node {
1114                 hir::ExprKind::AddrOf(_, expr) => {
1115                     is_call(&expr.node)
1116                 },
1117                 hir::ExprKind::Call(..)
1118                 | hir::ExprKind::MethodCall(..)
1119                 // These variants are debatable or require further examination
1120                 | hir::ExprKind::If(..)
1121                 | hir::ExprKind::Match(..)
1122                 | hir::ExprKind::Block{ .. } => true,
1123                 _ => false,
1124             }
1125         }
1126
1127         if name != "expect" {
1128             return;
1129         }
1130
1131         let self_type = cx.tables.expr_ty(self_expr);
1132         let known_types = &[&paths::OPTION, &paths::RESULT];
1133
1134         // if not a known type, return early
1135         if known_types.iter().all(|&k| !match_type(cx, self_type, k)) {
1136             return;
1137         }
1138
1139         if !is_call(&arg.node) {
1140             return;
1141         }
1142
1143         let closure = if match_type(cx, self_type, &paths::OPTION) { "||" } else { "|_|" };
1144         let span_replace_word = method_span.with_hi(span.hi());
1145
1146         if let Some(format_args) = extract_format_args(arg) {
1147             let args_len = format_args.len();
1148             let args: Vec<String> = format_args
1149                 .into_iter()
1150                 .take(args_len - 1)
1151                 .map(|a| generate_format_arg_snippet(cx, a))
1152                 .collect();
1153
1154             let sugg = args.join(", ");
1155
1156             span_lint_and_sugg(
1157                 cx,
1158                 EXPECT_FUN_CALL,
1159                 span_replace_word,
1160                 &format!("use of `{}` followed by a function call", name),
1161                 "try this",
1162                 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1163             );
1164
1165             return;
1166         }
1167
1168         let sugg: Cow<'_, _> = snippet(cx, arg.span, "..");
1169
1170         span_lint_and_sugg(
1171             cx,
1172             EXPECT_FUN_CALL,
1173             span_replace_word,
1174             &format!("use of `{}` followed by a function call", name),
1175             "try this",
1176             format!("unwrap_or_else({} {{ let msg = {}; panic!(msg) }}))", closure, sugg),
1177         );
1178     }
1179
1180     if args.len() == 2 {
1181         match args[1].node {
1182             hir::ExprKind::Lit(_) => {},
1183             _ => check_general_case(cx, name, method_span, &args[0], &args[1], expr.span),
1184         }
1185     }
1186 }
1187
1188 /// Checks for the `CLONE_ON_COPY` lint.
1189 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty<'_>) {
1190     let ty = cx.tables.expr_ty(expr);
1191     if let ty::Ref(_, inner, _) = arg_ty.sty {
1192         if let ty::Ref(_, innermost, _) = inner.sty {
1193             span_lint_and_then(
1194                 cx,
1195                 CLONE_DOUBLE_REF,
1196                 expr.span,
1197                 "using `clone` on a double-reference; \
1198                  this will copy the reference instead of cloning the inner type",
1199                 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1200                     let mut ty = innermost;
1201                     let mut n = 0;
1202                     while let ty::Ref(_, inner, _) = ty.sty {
1203                         ty = inner;
1204                         n += 1;
1205                     }
1206                     let refs: String = iter::repeat('&').take(n + 1).collect();
1207                     let derefs: String = iter::repeat('*').take(n).collect();
1208                     let explicit = format!("{}{}::clone({})", refs, ty, snip);
1209                     db.span_suggestion_with_applicability(
1210                         expr.span,
1211                         "try dereferencing it",
1212                         format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1213                         Applicability::MaybeIncorrect,
1214                     );
1215                     db.span_suggestion_with_applicability(
1216                         expr.span,
1217                         "or try being explicit about what type to clone",
1218                         explicit,
1219                         Applicability::MaybeIncorrect,
1220                     );
1221                 },
1222             );
1223             return; // don't report clone_on_copy
1224         }
1225     }
1226
1227     if is_copy(cx, ty) {
1228         let snip;
1229         if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1230             if let ty::Ref(..) = cx.tables.expr_ty(arg).sty {
1231                 let parent = cx.tcx.hir.get_parent_node(expr.id);
1232                 match cx.tcx.hir.get(parent) {
1233                     hir::Node::Expr(parent) => match parent.node {
1234                         // &*x is a nop, &x.clone() is not
1235                         hir::ExprKind::AddrOf(..) |
1236                         // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1237                         hir::ExprKind::MethodCall(..) => return,
1238                         _ => {},
1239                     }
1240                     hir::Node::Stmt(stmt) => {
1241                         if let hir::StmtKind::Decl(ref decl, _) = stmt.node {
1242                             if let hir::DeclKind::Local(ref loc) = decl.node {
1243                                 if let hir::PatKind::Ref(..) = loc.pat.node {
1244                                     // let ref y = *x borrows x, let ref y = x.clone() does not
1245                                     return;
1246                                 }
1247                             }
1248                         }
1249                     },
1250                     _ => {},
1251                 }
1252                 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
1253             } else {
1254                 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1255             }
1256         } else {
1257             snip = None;
1258         }
1259         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1260             if let Some((text, snip)) = snip {
1261                 db.span_suggestion_with_applicability(
1262                     expr.span,
1263                     text,
1264                     snip,
1265                     Applicability::Unspecified,
1266                 );
1267             }
1268         });
1269     }
1270 }
1271
1272 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr) {
1273     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1274
1275     if let ty::Adt(_, subst) = obj_ty.sty {
1276         let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1277             "Rc"
1278         } else if match_type(cx, obj_ty, &paths::ARC) {
1279             "Arc"
1280         } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1281             "Weak"
1282         } else {
1283             return;
1284         };
1285
1286         span_lint_and_sugg(
1287             cx,
1288             CLONE_ON_REF_PTR,
1289             expr.span,
1290             "using '.clone()' on a ref-counted pointer",
1291             "try this",
1292             format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1293         );
1294     }
1295 }
1296
1297
1298 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1299     let arg = &args[1];
1300     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1301         let target = &arglists[0][0];
1302         let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1303         let ref_str = if self_ty.sty == ty::Str {
1304             ""
1305         } else if match_type(cx, self_ty, &paths::STRING) {
1306             "&"
1307         } else {
1308             return;
1309         };
1310
1311         span_lint_and_sugg(
1312             cx,
1313             STRING_EXTEND_CHARS,
1314             expr.span,
1315             "calling `.extend(_.chars())`",
1316             "try this",
1317             format!(
1318                 "{}.push_str({}{})",
1319                 snippet(cx, args[0].span, "_"),
1320                 ref_str,
1321                 snippet(cx, target.span, "_")
1322             ),
1323         );
1324     }
1325 }
1326
1327 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1328     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
1329     if match_type(cx, obj_ty, &paths::STRING) {
1330         lint_string_extend(cx, expr, args);
1331     }
1332 }
1333
1334 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1335     if_chain! {
1336         if let hir::ExprKind::Call(ref fun, ref args) = new.node;
1337         if args.len() == 1;
1338         if let hir::ExprKind::Path(ref path) = fun.node;
1339         if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1340         if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1341         then {
1342             span_lint_and_then(
1343                 cx,
1344                 TEMPORARY_CSTRING_AS_PTR,
1345                 expr.span,
1346                 "you are getting the inner pointer of a temporary `CString`",
1347                 |db| {
1348                     db.note("that pointer will be invalid outside this expression");
1349                     db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1350                 });
1351         }
1352     }
1353 }
1354
1355 fn lint_iter_cloned_collect(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1356     if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1357         && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1358     {
1359         span_lint(
1360             cx,
1361             ITER_CLONED_COLLECT,
1362             expr.span,
1363             "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1364              more readable",
1365         );
1366     }
1367 }
1368
1369 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1370     fn check_fold_with_op(
1371         cx: &LateContext<'_, '_>,
1372         fold_args: &[hir::Expr],
1373         op: hir::BinOpKind,
1374         replacement_method_name: &str,
1375         replacement_has_args: bool) {
1376
1377         if_chain! {
1378             // Extract the body of the closure passed to fold
1379             if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].node;
1380             let closure_body = cx.tcx.hir.body(body_id);
1381             let closure_expr = remove_blocks(&closure_body.value);
1382
1383             // Check if the closure body is of the form `acc <op> some_expr(x)`
1384             if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1385             if bin_op.node == op;
1386
1387             // Extract the names of the two arguments to the closure
1388             if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1389             if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1390
1391             if match_var(&*left_expr, first_arg_ident);
1392             if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1393
1394             then {
1395                 // Span containing `.fold(...)`
1396                 let next_point = cx.sess().source_map().next_point(fold_args[0].span);
1397                 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1398
1399                 let sugg = if replacement_has_args {
1400                     format!(
1401                         ".{replacement}(|{s}| {r})",
1402                         replacement = replacement_method_name,
1403                         s = second_arg_ident,
1404                         r = snippet(cx, right_expr.span, "EXPR"),
1405                     )
1406                 } else {
1407                     format!(
1408                         ".{replacement}()",
1409                         replacement = replacement_method_name,
1410                     )
1411                 };
1412
1413                 span_lint_and_sugg(
1414                     cx,
1415                     UNNECESSARY_FOLD,
1416                     fold_span,
1417                     // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
1418                     "this `.fold` can be written more succinctly using another method",
1419                     "try",
1420                     sugg,
1421                 );
1422             }
1423         }
1424     }
1425
1426     // Check that this is a call to Iterator::fold rather than just some function called fold
1427     if !match_trait_method(cx, expr, &paths::ITERATOR) {
1428         return;
1429     }
1430
1431     assert!(fold_args.len() == 3,
1432         "Expected fold_args to have three entries - the receiver, the initial value and the closure");
1433
1434     // Check if the first argument to .fold is a suitable literal
1435     match fold_args[1].node {
1436         hir::ExprKind::Lit(ref lit) => {
1437             match lit.node {
1438                 ast::LitKind::Bool(false) => check_fold_with_op(
1439                     cx, fold_args, hir::BinOpKind::Or, "any", true
1440                 ),
1441                 ast::LitKind::Bool(true) => check_fold_with_op(
1442                     cx, fold_args, hir::BinOpKind::And, "all", true
1443                 ),
1444                 ast::LitKind::Int(0, _) => check_fold_with_op(
1445                     cx, fold_args, hir::BinOpKind::Add, "sum", false
1446                 ),
1447                 ast::LitKind::Int(1, _) => check_fold_with_op(
1448                     cx, fold_args, hir::BinOpKind::Mul, "product", false
1449                 ),
1450                 _ => return
1451             }
1452         }
1453         _ => return
1454     };
1455 }
1456
1457 fn lint_iter_nth(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1458     let mut_str = if is_mut { "_mut" } else { "" };
1459     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1460         "slice"
1461     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1462         "Vec"
1463     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1464         "VecDeque"
1465     } else {
1466         return; // caller is not a type that we want to lint
1467     };
1468
1469     span_lint(
1470         cx,
1471         ITER_NTH,
1472         expr.span,
1473         &format!(
1474             "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1475             mut_str,
1476             caller_type
1477         ),
1478     );
1479 }
1480
1481 fn lint_get_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1482     // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1483     // because they do not implement `IndexMut`
1484     let expr_ty = cx.tables.expr_ty(&get_args[0]);
1485     let get_args_str = if get_args.len() > 1 {
1486         snippet(cx, get_args[1].span, "_")
1487     } else {
1488         return; // not linting on a .get().unwrap() chain or variant
1489     };
1490     let needs_ref;
1491     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1492         needs_ref = get_args_str.parse::<usize>().is_ok();
1493         "slice"
1494     } else if match_type(cx, expr_ty, &paths::VEC) {
1495         needs_ref = get_args_str.parse::<usize>().is_ok();
1496         "Vec"
1497     } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1498         needs_ref = get_args_str.parse::<usize>().is_ok();
1499         "VecDeque"
1500     } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1501         needs_ref = true;
1502         "HashMap"
1503     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1504         needs_ref = true;
1505         "BTreeMap"
1506     } else {
1507         return; // caller is not a type that we want to lint
1508     };
1509
1510     let mut_str = if is_mut { "_mut" } else { "" };
1511     let borrow_str = if !needs_ref { "" } else if is_mut { "&mut " } else { "&" };
1512     span_lint_and_sugg(
1513         cx,
1514         GET_UNWRAP,
1515         expr.span,
1516         &format!(
1517             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1518             mut_str,
1519             caller_type
1520         ),
1521         "try this",
1522         format!(
1523             "{}{}[{}]",
1524             borrow_str,
1525             snippet(cx, get_args[0].span, "_"),
1526             get_args_str
1527         ),
1528     );
1529 }
1530
1531 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr) {
1532     // lint if caller of skip is an Iterator
1533     if match_trait_method(cx, expr, &paths::ITERATOR) {
1534         span_lint(
1535             cx,
1536             ITER_SKIP_NEXT,
1537             expr.span,
1538             "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1539         );
1540     }
1541 }
1542
1543 fn derefs_to_slice(cx: &LateContext<'_, '_>, expr: &hir::Expr, ty: Ty<'_>) -> Option<sugg::Sugg<'static>> {
1544     fn may_slice(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1545         match ty.sty {
1546             ty::Slice(_) => true,
1547             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1548             ty::Adt(..) => match_type(cx, ty, &paths::VEC),
1549             ty::Array(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
1550             ty::Ref(_, inner, _) => may_slice(cx, inner),
1551             _ => false,
1552         }
1553     }
1554
1555     if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.node {
1556         if path.ident.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1557             sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1558         } else {
1559             None
1560         }
1561     } else {
1562         match ty.sty {
1563             ty::Slice(_) => sugg::Sugg::hir_opt(cx, expr),
1564             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1565             ty::Ref(_, inner, _) => if may_slice(cx, inner) {
1566                 sugg::Sugg::hir_opt(cx, expr)
1567             } else {
1568                 None
1569             },
1570             _ => None,
1571         }
1572     }
1573 }
1574
1575 /// lint use of `unwrap()` for `Option`s and `Result`s
1576 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1577     let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
1578
1579     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1580         Some((OPTION_UNWRAP_USED, "an Option", "None"))
1581     } else if match_type(cx, obj_ty, &paths::RESULT) {
1582         Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1583     } else {
1584         None
1585     };
1586
1587     if let Some((lint, kind, none_value)) = mess {
1588         span_lint(
1589             cx,
1590             lint,
1591             expr.span,
1592             &format!(
1593                 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1594                  using expect() to provide a better panic \
1595                  message",
1596                 kind,
1597                 none_value
1598             ),
1599         );
1600     }
1601 }
1602
1603 /// lint use of `ok().expect()` for `Result`s
1604 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1605     // lint if the caller of `ok()` is a `Result`
1606     if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1607         let result_type = cx.tables.expr_ty(&ok_args[0]);
1608         if let Some(error_type) = get_error_type(cx, result_type) {
1609             if has_debug_impl(error_type, cx) {
1610                 span_lint(
1611                     cx,
1612                     OK_EXPECT,
1613                     expr.span,
1614                     "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1615                 );
1616             }
1617         }
1618     }
1619 }
1620
1621 /// lint use of `map().unwrap_or()` for `Option`s
1622 fn lint_map_unwrap_or(cx: &LateContext<'_, '_>, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1623     // lint if the caller of `map()` is an `Option`
1624     if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1625         // get snippets for args to map() and unwrap_or()
1626         let map_snippet = snippet(cx, map_args[1].span, "..");
1627         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1628         // lint message
1629         // comparing the snippet from source to raw text ("None") below is safe
1630         // because we already have checked the type.
1631         let arg = if unwrap_snippet == "None" {
1632             "None"
1633         } else {
1634             "a"
1635         };
1636         let suggest = if unwrap_snippet == "None" {
1637             "and_then(f)"
1638         } else {
1639             "map_or(a, f)"
1640         };
1641         let msg = &format!(
1642             "called `map(f).unwrap_or({})` on an Option value. \
1643              This can be done more directly by calling `{}` instead",
1644             arg,
1645             suggest
1646         );
1647         // lint, with note if neither arg is > 1 line and both map() and
1648         // unwrap_or() have the same span
1649         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1650         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1651         if same_span && !multiline {
1652             let suggest = if unwrap_snippet == "None" {
1653                 format!("and_then({})", map_snippet)
1654             } else {
1655                 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1656             };
1657             let note = format!(
1658                 "replace `map({}).unwrap_or({})` with `{}`",
1659                 map_snippet,
1660                 unwrap_snippet,
1661                 suggest
1662             );
1663             span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, &note);
1664         } else if same_span && multiline {
1665             span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1666         };
1667     }
1668 }
1669
1670 /// lint use of `map().flatten()` for `Iterators`
1671 fn lint_map_flatten<'a, 'tcx>(
1672     cx: &LateContext<'a, 'tcx>,
1673     expr: &'tcx hir::Expr,
1674     map_args: &'tcx [hir::Expr],
1675 ) {
1676     // lint if caller of `.map().flatten()` is an Iterator
1677     if match_trait_method(cx, expr, &paths::ITERATOR) {
1678         let msg = "called `map(..).flatten()` on an `Iterator`. \
1679                    This is more succinctly expressed by calling `.flat_map(..)`";
1680         let self_snippet = snippet(cx, map_args[0].span, "..");
1681         let func_snippet = snippet(cx, map_args[1].span, "..");
1682         let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
1683         span_lint_and_then(cx, MAP_FLATTEN, expr.span, msg, |db| {
1684             db.span_suggestion_with_applicability(
1685                 expr.span,
1686                 "try using flat_map instead",
1687                 hint,
1688                 Applicability::MachineApplicable,
1689             );
1690         });
1691     }
1692 }
1693
1694 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1695 fn lint_map_unwrap_or_else<'a, 'tcx>(
1696     cx: &LateContext<'a, 'tcx>,
1697     expr: &'tcx hir::Expr,
1698     map_args: &'tcx [hir::Expr],
1699     unwrap_args: &'tcx [hir::Expr],
1700 ) {
1701     // lint if the caller of `map()` is an `Option`
1702     let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1703     let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1704     if is_option || is_result {
1705         // lint message
1706         let msg = if is_option {
1707             "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1708              `map_or_else(g, f)` instead"
1709         } else {
1710             "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1711              `ok().map_or_else(g, f)` instead"
1712         };
1713         // get snippets for args to map() and unwrap_or_else()
1714         let map_snippet = snippet(cx, map_args[1].span, "..");
1715         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1716         // lint, with note if neither arg is > 1 line and both map() and
1717         // unwrap_or_else() have the same span
1718         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1719         let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1720         if same_span && !multiline {
1721             span_note_and_lint(
1722                 cx,
1723                 if is_option {
1724                     OPTION_MAP_UNWRAP_OR_ELSE
1725                 } else {
1726                     RESULT_MAP_UNWRAP_OR_ELSE
1727                 },
1728                 expr.span,
1729                 msg,
1730                 expr.span,
1731                 &format!(
1732                     "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1733                     map_snippet,
1734                     unwrap_snippet,
1735                     if is_result { "ok()." } else { "" }
1736                 ),
1737             );
1738         } else if same_span && multiline {
1739             span_lint(
1740                 cx,
1741                 if is_option {
1742                     OPTION_MAP_UNWRAP_OR_ELSE
1743                 } else {
1744                     RESULT_MAP_UNWRAP_OR_ELSE
1745                 },
1746                 expr.span,
1747                 msg,
1748             );
1749         };
1750     }
1751 }
1752
1753 /// lint use of `_.map_or(None, _)` for `Option`s
1754 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1755     if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1756         // check if the first non-self argument to map_or() is None
1757         let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].node {
1758             match_qpath(qpath, &paths::OPTION_NONE)
1759         } else {
1760             false
1761         };
1762
1763         if map_or_arg_is_none {
1764             // lint message
1765             let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1766                        `and_then(f)` instead";
1767             let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1768             let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1769             let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1770             span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1771                 db.span_suggestion_with_applicability(
1772                     expr.span,
1773                     "try using and_then instead",
1774                     hint,
1775                     Applicability::MachineApplicable, // snippet
1776                 );
1777             });
1778         }
1779     }
1780 }
1781
1782 /// lint use of `filter().next()` for `Iterators`
1783 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1784     // lint if caller of `.filter().next()` is an Iterator
1785     if match_trait_method(cx, expr, &paths::ITERATOR) {
1786         let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1787                    `.find(p)` instead.";
1788         let filter_snippet = snippet(cx, filter_args[1].span, "..");
1789         if filter_snippet.lines().count() <= 1 {
1790             // add note if not multi-line
1791             span_note_and_lint(
1792                 cx,
1793                 FILTER_NEXT,
1794                 expr.span,
1795                 msg,
1796                 expr.span,
1797                 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1798             );
1799         } else {
1800             span_lint(cx, FILTER_NEXT, expr.span, msg);
1801         }
1802     }
1803 }
1804
1805 /// lint use of `filter().map()` for `Iterators`
1806 fn lint_filter_map<'a, 'tcx>(
1807     cx: &LateContext<'a, 'tcx>,
1808     expr: &'tcx hir::Expr,
1809     _filter_args: &'tcx [hir::Expr],
1810     _map_args: &'tcx [hir::Expr],
1811 ) {
1812     // lint if caller of `.filter().map()` is an Iterator
1813     if match_trait_method(cx, expr, &paths::ITERATOR) {
1814         let msg = "called `filter(p).map(q)` on an `Iterator`. \
1815                    This is more succinctly expressed by calling `.filter_map(..)` instead.";
1816         span_lint(cx, FILTER_MAP, expr.span, msg);
1817     }
1818 }
1819
1820 /// lint use of `filter().map()` for `Iterators`
1821 fn lint_filter_map_map<'a, 'tcx>(
1822     cx: &LateContext<'a, 'tcx>,
1823     expr: &'tcx hir::Expr,
1824     _filter_args: &'tcx [hir::Expr],
1825     _map_args: &'tcx [hir::Expr],
1826 ) {
1827     // lint if caller of `.filter().map()` is an Iterator
1828     if match_trait_method(cx, expr, &paths::ITERATOR) {
1829         let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1830                    This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1831         span_lint(cx, FILTER_MAP, expr.span, msg);
1832     }
1833 }
1834
1835 /// lint use of `filter().flat_map()` for `Iterators`
1836 fn lint_filter_flat_map<'a, 'tcx>(
1837     cx: &LateContext<'a, 'tcx>,
1838     expr: &'tcx hir::Expr,
1839     _filter_args: &'tcx [hir::Expr],
1840     _map_args: &'tcx [hir::Expr],
1841 ) {
1842     // lint if caller of `.filter().flat_map()` is an Iterator
1843     if match_trait_method(cx, expr, &paths::ITERATOR) {
1844         let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1845                    This is more succinctly expressed by calling `.flat_map(..)` \
1846                    and filtering by returning an empty Iterator.";
1847         span_lint(cx, FILTER_MAP, expr.span, msg);
1848     }
1849 }
1850
1851 /// lint use of `filter_map().flat_map()` for `Iterators`
1852 fn lint_filter_map_flat_map<'a, 'tcx>(
1853     cx: &LateContext<'a, 'tcx>,
1854     expr: &'tcx hir::Expr,
1855     _filter_args: &'tcx [hir::Expr],
1856     _map_args: &'tcx [hir::Expr],
1857 ) {
1858     // lint if caller of `.filter_map().flat_map()` is an Iterator
1859     if match_trait_method(cx, expr, &paths::ITERATOR) {
1860         let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1861                    This is more succinctly expressed by calling `.flat_map(..)` \
1862                    and filtering by returning an empty Iterator.";
1863         span_lint(cx, FILTER_MAP, expr.span, msg);
1864     }
1865 }
1866
1867 /// lint searching an Iterator followed by `is_some()`
1868 fn lint_search_is_some<'a, 'tcx>(
1869     cx: &LateContext<'a, 'tcx>,
1870     expr: &'tcx hir::Expr,
1871     search_method: &str,
1872     search_args: &'tcx [hir::Expr],
1873     is_some_args: &'tcx [hir::Expr],
1874 ) {
1875     // lint if caller of search is an Iterator
1876     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1877         let msg = format!(
1878             "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1879              expressed by calling `any()`.",
1880             search_method
1881         );
1882         let search_snippet = snippet(cx, search_args[1].span, "..");
1883         if search_snippet.lines().count() <= 1 {
1884             // add note if not multi-line
1885             span_note_and_lint(
1886                 cx,
1887                 SEARCH_IS_SOME,
1888                 expr.span,
1889                 &msg,
1890                 expr.span,
1891                 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1892             );
1893         } else {
1894             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1895         }
1896     }
1897 }
1898
1899 /// Used for `lint_binary_expr_with_method_call`.
1900 #[derive(Copy, Clone)]
1901 struct BinaryExprInfo<'a> {
1902     expr: &'a hir::Expr,
1903     chain: &'a hir::Expr,
1904     other: &'a hir::Expr,
1905     eq: bool,
1906 }
1907
1908 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1909 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
1910     macro_rules! lint_with_both_lhs_and_rhs {
1911         ($func:ident, $cx:expr, $info:ident) => {
1912             if !$func($cx, $info) {
1913                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1914                 if $func($cx, $info) {
1915                     return;
1916                 }
1917             }
1918         }
1919     }
1920
1921     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1922     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1923     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1924     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1925 }
1926
1927 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1928 fn lint_chars_cmp(
1929     cx: &LateContext<'_, '_>,
1930     info: &BinaryExprInfo<'_>,
1931     chain_methods: &[&str],
1932     lint: &'static Lint,
1933     suggest: &str,
1934 ) -> bool {
1935     if_chain! {
1936         if let Some(args) = method_chain_args(info.chain, chain_methods);
1937         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.node;
1938         if arg_char.len() == 1;
1939         if let hir::ExprKind::Path(ref qpath) = fun.node;
1940         if let Some(segment) = single_segment_path(qpath);
1941         if segment.ident.name == "Some";
1942         then {
1943             let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1944
1945             if self_ty.sty != ty::Str {
1946                 return false;
1947             }
1948
1949             span_lint_and_sugg(cx,
1950                                lint,
1951                                info.expr.span,
1952                                &format!("you should use the `{}` method", suggest),
1953                                "like this",
1954                                format!("{}{}.{}({})",
1955                                        if info.eq { "" } else { "!" },
1956                                        snippet(cx, args[0][0].span, "_"),
1957                                        suggest,
1958                                        snippet(cx, arg_char[0].span, "_")));
1959
1960             return true;
1961         }
1962     }
1963
1964     false
1965 }
1966
1967 /// Checks for the `CHARS_NEXT_CMP` lint.
1968 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1969     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1970 }
1971
1972 /// Checks for the `CHARS_LAST_CMP` lint.
1973 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1974     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1975         true
1976     } else {
1977         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1978     }
1979 }
1980
1981 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1982 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1983     cx: &LateContext<'a, 'tcx>,
1984     info: &BinaryExprInfo<'_>,
1985     chain_methods: &[&str],
1986     lint: &'static Lint,
1987     suggest: &str,
1988 ) -> bool {
1989     if_chain! {
1990         if let Some(args) = method_chain_args(info.chain, chain_methods);
1991         if let hir::ExprKind::Lit(ref lit) = info.other.node;
1992         if let ast::LitKind::Char(c) = lit.node;
1993         then {
1994             span_lint_and_sugg(
1995                 cx,
1996                 lint,
1997                 info.expr.span,
1998                 &format!("you should use the `{}` method", suggest),
1999                 "like this",
2000                 format!("{}{}.{}('{}')",
2001                         if info.eq { "" } else { "!" },
2002                         snippet(cx, args[0][0].span, "_"),
2003                         suggest,
2004                         c)
2005             );
2006
2007             return true;
2008         }
2009     }
2010
2011     false
2012 }
2013
2014 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2015 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2016     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2017 }
2018
2019 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2020 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2021     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2022         true
2023     } else {
2024         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
2025     }
2026 }
2027
2028 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
2029 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, _expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
2030     if_chain! {
2031         if let hir::ExprKind::Lit(lit) = &arg.node;
2032         if let ast::LitKind::Str(r, _) = lit.node;
2033         if r.as_str().len() == 1;
2034         then {
2035             let snip = snippet(cx, arg.span, "..");
2036             let hint = format!("'{}'", &snip[1..snip.len() - 1]);
2037             span_lint_and_sugg(
2038                 cx,
2039                 SINGLE_CHAR_PATTERN,
2040                 arg.span,
2041                 "single-character string constant used as pattern",
2042                 "try using a char instead",
2043                 hint,
2044             );
2045         }
2046     }
2047 }
2048
2049 /// Checks for the `USELESS_ASREF` lint.
2050 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
2051     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
2052     // check if the call is to the actual `AsRef` or `AsMut` trait
2053     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
2054         // check if the type after `as_ref` or `as_mut` is the same as before
2055         let recvr = &as_ref_args[0];
2056         let rcv_ty = cx.tables.expr_ty(recvr);
2057         let res_ty = cx.tables.expr_ty(expr);
2058         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
2059         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
2060         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
2061             span_lint_and_sugg(
2062                 cx,
2063                 USELESS_ASREF,
2064                 expr.span,
2065                 &format!("this call to `{}` does nothing", call_name),
2066                 "try this",
2067                 snippet(cx, recvr.span, "_").into_owned(),
2068             );
2069         }
2070     }
2071 }
2072
2073 /// Given a `Result<T, E>` type, return its error type (`E`).
2074 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
2075     if let ty::Adt(_, substs) = ty.sty {
2076         if match_type(cx, ty, &paths::RESULT) {
2077             substs.types().nth(1)
2078         } else {
2079             None
2080         }
2081     } else {
2082         None
2083     }
2084 }
2085
2086 /// This checks whether a given type is known to implement Debug.
2087 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
2088     match cx.tcx.lang_items().debug_trait() {
2089         Some(debug) => implements_trait(cx, ty, debug, &[]),
2090         None => false,
2091     }
2092 }
2093
2094 enum Convention {
2095     Eq(&'static str),
2096     StartsWith(&'static str),
2097 }
2098
2099 #[rustfmt::skip]
2100 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
2101     (Convention::Eq("new"), &[SelfKind::No]),
2102     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
2103     (Convention::StartsWith("from_"), &[SelfKind::No]),
2104     (Convention::StartsWith("into_"), &[SelfKind::Value]),
2105     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
2106     (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
2107     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
2108 ];
2109
2110 #[rustfmt::skip]
2111 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
2112     ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
2113     ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
2114     ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
2115     ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
2116     ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
2117     ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
2118     ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
2119     ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
2120     ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
2121     ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
2122     ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
2123     ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
2124     ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
2125     ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
2126     ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
2127     ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
2128     ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
2129     ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
2130     ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
2131     ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
2132     ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
2133     ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
2134     ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
2135     ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
2136     ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
2137     ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
2138     ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
2139     ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
2140     ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
2141     ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
2142 ];
2143
2144 #[rustfmt::skip]
2145 const PATTERN_METHODS: [(&str, usize); 17] = [
2146     ("contains", 1),
2147     ("starts_with", 1),
2148     ("ends_with", 1),
2149     ("find", 1),
2150     ("rfind", 1),
2151     ("split", 1),
2152     ("rsplit", 1),
2153     ("split_terminator", 1),
2154     ("rsplit_terminator", 1),
2155     ("splitn", 2),
2156     ("rsplitn", 2),
2157     ("matches", 1),
2158     ("rmatches", 1),
2159     ("match_indices", 1),
2160     ("rmatch_indices", 1),
2161     ("trim_left_matches", 1),
2162     ("trim_right_matches", 1),
2163 ];
2164
2165
2166 #[derive(Clone, Copy, PartialEq, Debug)]
2167 enum SelfKind {
2168     Value,
2169     Ref,
2170     RefMut,
2171     No,
2172 }
2173
2174 impl SelfKind {
2175     fn matches(
2176         self,
2177         cx: &LateContext<'_, '_>,
2178         ty: &hir::Ty,
2179         arg: &hir::Arg,
2180         self_ty: &hir::Ty,
2181         allow_value_for_ref: bool,
2182         generics: &hir::Generics,
2183     ) -> bool {
2184         // Self types in the HIR are desugared to explicit self types. So it will
2185         // always be `self:
2186         // SomeType`,
2187         // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
2188         // the impl is on `Foo`)
2189         // Thus, we only need to test equality against the impl self type or if it is
2190         // an explicit
2191         // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
2192         // `Self`, `&mut Self`,
2193         // and `Box<Self>`, including the equivalent types with `Foo`.
2194
2195         let is_actually_self = |ty| is_self_ty(ty) || SpanlessEq::new(cx).eq_ty(ty, self_ty);
2196         if is_self(arg) {
2197             match self {
2198                 SelfKind::Value => is_actually_self(ty),
2199                 SelfKind::Ref | SelfKind::RefMut => {
2200                     if allow_value_for_ref && is_actually_self(ty) {
2201                         return true;
2202                     }
2203                     match ty.node {
2204                         hir::TyKind::Rptr(_, ref mt_ty) => {
2205                             let mutability_match = if self == SelfKind::Ref {
2206                                 mt_ty.mutbl == hir::MutImmutable
2207                             } else {
2208                                 mt_ty.mutbl == hir::MutMutable
2209                             };
2210                             is_actually_self(&mt_ty.ty) && mutability_match
2211                         },
2212                         _ => false,
2213                     }
2214                 },
2215                 _ => false,
2216             }
2217         } else {
2218             match self {
2219                 SelfKind::Value => false,
2220                 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
2221                 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
2222                 SelfKind::No => true,
2223             }
2224         }
2225     }
2226
2227     fn description(self) -> &'static str {
2228         match self {
2229             SelfKind::Value => "self by value",
2230             SelfKind::Ref => "self by reference",
2231             SelfKind::RefMut => "self by mutable reference",
2232             SelfKind::No => "no self",
2233         }
2234     }
2235 }
2236
2237 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
2238     single_segment_ty(ty).map_or(false, |seg| {
2239         generics.params.iter().any(|param| match param.kind {
2240             hir::GenericParamKind::Type { .. } => {
2241                 param.name.ident().name == seg.ident.name && param.bounds.iter().any(|bound| {
2242                     if let hir::GenericBound::Trait(ref ptr, ..) = *bound {
2243                         let path = &ptr.trait_ref.path;
2244                         match_path(path, name) && path.segments.last().map_or(false, |s| {
2245                             if let Some(ref params) = s.args {
2246                                 if params.parenthesized {
2247                                     false
2248                                 } else {
2249                                     // FIXME(flip1995): messy, improve if there is a better option
2250                                     // in the compiler
2251                                     let types: Vec<_> = params.args.iter().filter_map(|arg| match arg {
2252                                         hir::GenericArg::Type(ty) => Some(ty),
2253                                         _ => None,
2254                                     }).collect();
2255                                     types.len() == 1
2256                                         && (is_self_ty(&types[0]) || is_ty(&*types[0], self_ty))
2257                                 }
2258                             } else {
2259                                 false
2260                             }
2261                         })
2262                     } else {
2263                         false
2264                     }
2265                 })
2266             },
2267             _ => false,
2268         })
2269     })
2270 }
2271
2272 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
2273     match (&ty.node, &self_ty.node) {
2274         (
2275             &hir::TyKind::Path(hir::QPath::Resolved(_, ref ty_path)),
2276             &hir::TyKind::Path(hir::QPath::Resolved(_, ref self_ty_path)),
2277         ) => ty_path
2278             .segments
2279             .iter()
2280             .map(|seg| seg.ident.name)
2281             .eq(self_ty_path.segments.iter().map(|seg| seg.ident.name)),
2282         _ => false,
2283     }
2284 }
2285
2286 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2287     if let hir::TyKind::Path(ref path) = ty.node {
2288         single_segment_path(path)
2289     } else {
2290         None
2291     }
2292 }
2293
2294 impl Convention {
2295     fn check(&self, other: &str) -> bool {
2296         match *self {
2297             Convention::Eq(this) => this == other,
2298             Convention::StartsWith(this) => other.starts_with(this) && this != other,
2299         }
2300     }
2301 }
2302
2303 impl fmt::Display for Convention {
2304     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
2305         match *self {
2306             Convention::Eq(this) => this.fmt(f),
2307             Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2308         }
2309     }
2310 }
2311
2312 #[derive(Clone, Copy)]
2313 enum OutType {
2314     Unit,
2315     Bool,
2316     Any,
2317     Ref,
2318 }
2319
2320 impl OutType {
2321     fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FunctionRetTy) -> bool {
2322         let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
2323         match (self, ty) {
2324             (OutType::Unit, &hir::DefaultReturn(_)) => true,
2325             (OutType::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,
2326             (OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2327             (OutType::Any, &hir::Return(ref ty)) if !is_unit(ty) => true,
2328             (OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyKind::Rptr(_, _)),
2329             _ => false,
2330         }
2331     }
2332 }
2333
2334 fn is_bool(ty: &hir::Ty) -> bool {
2335     if let hir::TyKind::Path(ref p) = ty.node {
2336         match_qpath(p, &["bool"])
2337     } else {
2338         false
2339     }
2340 }