]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/mod.rs
Don't re-export clippy_utils::*
[rust.git] / clippy_lints / src / methods / mod.rs
1 mod bind_instead_of_map;
2 mod bytes_nth;
3 mod clone_on_copy;
4 mod clone_on_ref_ptr;
5 mod expect_fun_call;
6 mod expect_used;
7 mod filetype_is_file;
8 mod filter_flat_map;
9 mod filter_map;
10 mod filter_map_flat_map;
11 mod filter_map_identity;
12 mod filter_map_map;
13 mod filter_map_next;
14 mod filter_next;
15 mod flat_map_identity;
16 mod from_iter_instead_of_collect;
17 mod get_unwrap;
18 mod implicit_clone;
19 mod inefficient_to_string;
20 mod inspect_for_each;
21 mod into_iter_on_ref;
22 mod iter_cloned_collect;
23 mod iter_count;
24 mod iter_next_slice;
25 mod iter_nth;
26 mod iter_nth_zero;
27 mod iter_skip_next;
28 mod iterator_step_by_zero;
29 mod manual_saturating_arithmetic;
30 mod map_collect_result_unit;
31 mod map_flatten;
32 mod map_unwrap_or;
33 mod ok_expect;
34 mod option_as_ref_deref;
35 mod option_map_or_none;
36 mod option_map_unwrap_or;
37 mod or_fun_call;
38 mod search_is_some;
39 mod single_char_insert_string;
40 mod single_char_pattern;
41 mod single_char_push_string;
42 mod skip_while_next;
43 mod string_extend_chars;
44 mod suspicious_map;
45 mod uninit_assumed_init;
46 mod unnecessary_filter_map;
47 mod unnecessary_fold;
48 mod unnecessary_lazy_eval;
49 mod unwrap_used;
50 mod useless_asref;
51 mod wrong_self_convention;
52 mod zst_offset;
53
54 use bind_instead_of_map::BindInsteadOfMap;
55 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg};
56 use clippy_utils::source::snippet_with_applicability;
57 use clippy_utils::ty::{contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
58 use clippy_utils::{
59     contains_return, get_trait_def_id, in_macro, iter_input_pats, match_def_path, match_qpath, method_calls,
60     method_chain_args, paths, return_ty, single_segment_path, SpanlessEq,
61 };
62 use if_chain::if_chain;
63 use rustc_ast::ast;
64 use rustc_errors::Applicability;
65 use rustc_hir as hir;
66 use rustc_hir::{TraitItem, TraitItemKind};
67 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
68 use rustc_middle::lint::in_external_macro;
69 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
70 use rustc_semver::RustcVersion;
71 use rustc_session::{declare_tool_lint, impl_lint_pass};
72 use rustc_span::symbol::{sym, SymbolStr};
73 use rustc_typeck::hir_ty_to_ty;
74
75 declare_clippy_lint! {
76     /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
77     ///
78     /// **Why is this bad?** It is better to handle the `None` or `Err` case,
79     /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
80     /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
81     /// `Allow` by default.
82     ///
83     /// `result.unwrap()` will let the thread panic on `Err` values.
84     /// Normally, you want to implement more sophisticated error handling,
85     /// and propagate errors upwards with `?` operator.
86     ///
87     /// Even if you want to panic on errors, not all `Error`s implement good
88     /// messages on display. Therefore, it may be beneficial to look at the places
89     /// where they may get displayed. Activate this lint to do just that.
90     ///
91     /// **Known problems:** None.
92     ///
93     /// **Examples:**
94     /// ```rust
95     /// # let opt = Some(1);
96     ///
97     /// // Bad
98     /// opt.unwrap();
99     ///
100     /// // Good
101     /// opt.expect("more helpful message");
102     /// ```
103     ///
104     /// // or
105     ///
106     /// ```rust
107     /// # let res: Result<usize, ()> = Ok(1);
108     ///
109     /// // Bad
110     /// res.unwrap();
111     ///
112     /// // Good
113     /// res.expect("more helpful message");
114     /// ```
115     pub UNWRAP_USED,
116     restriction,
117     "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
118 }
119
120 declare_clippy_lint! {
121     /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
122     ///
123     /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
124     /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
125     /// this lint is `Allow` by default.
126     ///
127     /// `result.expect()` will let the thread panic on `Err`
128     /// values. Normally, you want to implement more sophisticated error handling,
129     /// and propagate errors upwards with `?` operator.
130     ///
131     /// **Known problems:** None.
132     ///
133     /// **Examples:**
134     /// ```rust,ignore
135     /// # let opt = Some(1);
136     ///
137     /// // Bad
138     /// opt.expect("one");
139     ///
140     /// // Good
141     /// let opt = Some(1);
142     /// opt?;
143     /// ```
144     ///
145     /// // or
146     ///
147     /// ```rust
148     /// # let res: Result<usize, ()> = Ok(1);
149     ///
150     /// // Bad
151     /// res.expect("one");
152     ///
153     /// // Good
154     /// res?;
155     /// # Ok::<(), ()>(())
156     /// ```
157     pub EXPECT_USED,
158     restriction,
159     "using `.expect()` on `Result` or `Option`, which might be better handled"
160 }
161
162 declare_clippy_lint! {
163     /// **What it does:** Checks for methods that should live in a trait
164     /// implementation of a `std` trait (see [llogiq's blog
165     /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
166     /// information) instead of an inherent implementation.
167     ///
168     /// **Why is this bad?** Implementing the traits improve ergonomics for users of
169     /// the code, often with very little cost. Also people seeing a `mul(...)`
170     /// method
171     /// may expect `*` to work equally, so you should have good reason to disappoint
172     /// them.
173     ///
174     /// **Known problems:** None.
175     ///
176     /// **Example:**
177     /// ```rust
178     /// struct X;
179     /// impl X {
180     ///     fn add(&self, other: &X) -> X {
181     ///         // ..
182     /// # X
183     ///     }
184     /// }
185     /// ```
186     pub SHOULD_IMPLEMENT_TRAIT,
187     style,
188     "defining a method that should be implementing a std trait"
189 }
190
191 declare_clippy_lint! {
192     /// **What it does:** Checks for methods with certain name prefixes and which
193     /// doesn't match how self is taken. The actual rules are:
194     ///
195     /// |Prefix |Postfix     |`self` taken          |
196     /// |-------|------------|----------------------|
197     /// |`as_`  | none       |`&self` or `&mut self`|
198     /// |`from_`| none       | none                 |
199     /// |`into_`| none       |`self`                |
200     /// |`is_`  | none       |`&self` or none       |
201     /// |`to_`  | `_mut`     |`&mut &self`          |
202     /// |`to_`  | not `_mut` |`&self`               |
203     ///
204     /// **Why is this bad?** Consistency breeds readability. If you follow the
205     /// conventions, your users won't be surprised that they, e.g., need to supply a
206     /// mutable reference to a `as_..` function.
207     ///
208     /// **Known problems:** None.
209     ///
210     /// **Example:**
211     /// ```rust
212     /// # struct X;
213     /// impl X {
214     ///     fn as_str(self) -> &'static str {
215     ///         // ..
216     /// # ""
217     ///     }
218     /// }
219     /// ```
220     pub WRONG_SELF_CONVENTION,
221     style,
222     "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
223 }
224
225 declare_clippy_lint! {
226     /// **What it does:** This is the same as
227     /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
228     ///
229     /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
230     ///
231     /// **Known problems:** Actually *renaming* the function may break clients if
232     /// the function is part of the public interface. In that case, be mindful of
233     /// the stability guarantees you've given your users.
234     ///
235     /// **Example:**
236     /// ```rust
237     /// # struct X;
238     /// impl<'a> X {
239     ///     pub fn as_str(self) -> &'a str {
240     ///         "foo"
241     ///     }
242     /// }
243     /// ```
244     pub WRONG_PUB_SELF_CONVENTION,
245     restriction,
246     "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
247 }
248
249 declare_clippy_lint! {
250     /// **What it does:** Checks for usage of `ok().expect(..)`.
251     ///
252     /// **Why is this bad?** Because you usually call `expect()` on the `Result`
253     /// directly to get a better error message.
254     ///
255     /// **Known problems:** The error type needs to implement `Debug`
256     ///
257     /// **Example:**
258     /// ```rust
259     /// # let x = Ok::<_, ()>(());
260     ///
261     /// // Bad
262     /// x.ok().expect("why did I do this again?");
263     ///
264     /// // Good
265     /// x.expect("why did I do this again?");
266     /// ```
267     pub OK_EXPECT,
268     style,
269     "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
270 }
271
272 declare_clippy_lint! {
273     /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
274     /// `result.map(_).unwrap_or_else(_)`.
275     ///
276     /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
277     /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
278     ///
279     /// **Known problems:** The order of the arguments is not in execution order
280     ///
281     /// **Examples:**
282     /// ```rust
283     /// # let x = Some(1);
284     ///
285     /// // Bad
286     /// x.map(|a| a + 1).unwrap_or(0);
287     ///
288     /// // Good
289     /// x.map_or(0, |a| a + 1);
290     /// ```
291     ///
292     /// // or
293     ///
294     /// ```rust
295     /// # let x: Result<usize, ()> = Ok(1);
296     /// # fn some_function(foo: ()) -> usize { 1 }
297     ///
298     /// // Bad
299     /// x.map(|a| a + 1).unwrap_or_else(some_function);
300     ///
301     /// // Good
302     /// x.map_or_else(some_function, |a| a + 1);
303     /// ```
304     pub MAP_UNWRAP_OR,
305     pedantic,
306     "using `.map(f).unwrap_or(a)` or `.map(f).unwrap_or_else(func)`, which are more succinctly expressed as `map_or(a, f)` or `map_or_else(a, f)`"
307 }
308
309 declare_clippy_lint! {
310     /// **What it does:** Checks for usage of `_.map_or(None, _)`.
311     ///
312     /// **Why is this bad?** Readability, this can be written more concisely as
313     /// `_.and_then(_)`.
314     ///
315     /// **Known problems:** The order of the arguments is not in execution order.
316     ///
317     /// **Example:**
318     /// ```rust
319     /// # let opt = Some(1);
320     ///
321     /// // Bad
322     /// opt.map_or(None, |a| Some(a + 1));
323     ///
324     /// // Good
325     /// opt.and_then(|a| Some(a + 1));
326     /// ```
327     pub OPTION_MAP_OR_NONE,
328     style,
329     "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
330 }
331
332 declare_clippy_lint! {
333     /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
334     ///
335     /// **Why is this bad?** Readability, this can be written more concisely as
336     /// `_.ok()`.
337     ///
338     /// **Known problems:** None.
339     ///
340     /// **Example:**
341     ///
342     /// Bad:
343     /// ```rust
344     /// # let r: Result<u32, &str> = Ok(1);
345     /// assert_eq!(Some(1), r.map_or(None, Some));
346     /// ```
347     ///
348     /// Good:
349     /// ```rust
350     /// # let r: Result<u32, &str> = Ok(1);
351     /// assert_eq!(Some(1), r.ok());
352     /// ```
353     pub RESULT_MAP_OR_INTO_OPTION,
354     style,
355     "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
356 }
357
358 declare_clippy_lint! {
359     /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
360     /// `_.or_else(|x| Err(y))`.
361     ///
362     /// **Why is this bad?** Readability, this can be written more concisely as
363     /// `_.map(|x| y)` or `_.map_err(|x| y)`.
364     ///
365     /// **Known problems:** None
366     ///
367     /// **Example:**
368     ///
369     /// ```rust
370     /// # fn opt() -> Option<&'static str> { Some("42") }
371     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
372     /// let _ = opt().and_then(|s| Some(s.len()));
373     /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
374     /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
375     /// ```
376     ///
377     /// The correct use would be:
378     ///
379     /// ```rust
380     /// # fn opt() -> Option<&'static str> { Some("42") }
381     /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
382     /// let _ = opt().map(|s| s.len());
383     /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
384     /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
385     /// ```
386     pub BIND_INSTEAD_OF_MAP,
387     complexity,
388     "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
389 }
390
391 declare_clippy_lint! {
392     /// **What it does:** Checks for usage of `_.filter(_).next()`.
393     ///
394     /// **Why is this bad?** Readability, this can be written more concisely as
395     /// `_.find(_)`.
396     ///
397     /// **Known problems:** None.
398     ///
399     /// **Example:**
400     /// ```rust
401     /// # let vec = vec![1];
402     /// vec.iter().filter(|x| **x == 0).next();
403     /// ```
404     /// Could be written as
405     /// ```rust
406     /// # let vec = vec![1];
407     /// vec.iter().find(|x| **x == 0);
408     /// ```
409     pub FILTER_NEXT,
410     complexity,
411     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
412 }
413
414 declare_clippy_lint! {
415     /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
416     ///
417     /// **Why is this bad?** Readability, this can be written more concisely as
418     /// `_.find(!condition)`.
419     ///
420     /// **Known problems:** None.
421     ///
422     /// **Example:**
423     /// ```rust
424     /// # let vec = vec![1];
425     /// vec.iter().skip_while(|x| **x == 0).next();
426     /// ```
427     /// Could be written as
428     /// ```rust
429     /// # let vec = vec![1];
430     /// vec.iter().find(|x| **x != 0);
431     /// ```
432     pub SKIP_WHILE_NEXT,
433     complexity,
434     "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
435 }
436
437 declare_clippy_lint! {
438     /// **What it does:** Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
439     ///
440     /// **Why is this bad?** Readability, this can be written more concisely as
441     /// `_.flat_map(_)`
442     ///
443     /// **Known problems:**
444     ///
445     /// **Example:**
446     /// ```rust
447     /// let vec = vec![vec![1]];
448     ///
449     /// // Bad
450     /// vec.iter().map(|x| x.iter()).flatten();
451     ///
452     /// // Good
453     /// vec.iter().flat_map(|x| x.iter());
454     /// ```
455     pub MAP_FLATTEN,
456     pedantic,
457     "using combinations of `flatten` and `map` which can usually be written as a single method call"
458 }
459
460 declare_clippy_lint! {
461     /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
462     /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
463     ///
464     /// **Why is this bad?** Readability, this can be written more concisely as
465     /// `_.filter_map(_)`.
466     ///
467     /// **Known problems:** Often requires a condition + Option/Iterator creation
468     /// inside the closure.
469     ///
470     /// **Example:**
471     /// ```rust
472     /// let vec = vec![1];
473     ///
474     /// // Bad
475     /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
476     ///
477     /// // Good
478     /// vec.iter().filter_map(|x| if *x == 0 {
479     ///     Some(*x * 2)
480     /// } else {
481     ///     None
482     /// });
483     /// ```
484     pub FILTER_MAP,
485     pedantic,
486     "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
487 }
488
489 declare_clippy_lint! {
490     /// **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply
491     /// as `filter_map(_)`.
492     ///
493     /// **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and
494     /// less performant.
495     ///
496     /// **Known problems:** None.
497     ///
498      /// **Example:**
499     /// Bad:
500     /// ```rust
501     /// (0_i32..10)
502     ///     .filter(|n| n.checked_add(1).is_some())
503     ///     .map(|n| n.checked_add(1).unwrap());
504     /// ```
505     ///
506     /// Good:
507     /// ```rust
508     /// (0_i32..10).filter_map(|n| n.checked_add(1));
509     /// ```
510     pub MANUAL_FILTER_MAP,
511     complexity,
512     "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
513 }
514
515 declare_clippy_lint! {
516     /// **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply
517     /// as `find_map(_)`.
518     ///
519     /// **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and
520     /// less performant.
521     ///
522     /// **Known problems:** None.
523     ///
524      /// **Example:**
525     /// Bad:
526     /// ```rust
527     /// (0_i32..10)
528     ///     .find(|n| n.checked_add(1).is_some())
529     ///     .map(|n| n.checked_add(1).unwrap());
530     /// ```
531     ///
532     /// Good:
533     /// ```rust
534     /// (0_i32..10).find_map(|n| n.checked_add(1));
535     /// ```
536     pub MANUAL_FIND_MAP,
537     complexity,
538     "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
539 }
540
541 declare_clippy_lint! {
542     /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
543     ///
544     /// **Why is this bad?** Readability, this can be written more concisely as
545     /// `_.find_map(_)`.
546     ///
547     /// **Known problems:** None
548     ///
549     /// **Example:**
550     /// ```rust
551     ///  (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
552     /// ```
553     /// Can be written as
554     ///
555     /// ```rust
556     ///  (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
557     /// ```
558     pub FILTER_MAP_NEXT,
559     pedantic,
560     "using combination of `filter_map` and `next` which can usually be written as a single method call"
561 }
562
563 declare_clippy_lint! {
564     /// **What it does:** Checks for usage of `flat_map(|x| x)`.
565     ///
566     /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
567     ///
568     /// **Known problems:** None
569     ///
570     /// **Example:**
571     /// ```rust
572     /// # let iter = vec![vec![0]].into_iter();
573     /// iter.flat_map(|x| x);
574     /// ```
575     /// Can be written as
576     /// ```rust
577     /// # let iter = vec![vec![0]].into_iter();
578     /// iter.flatten();
579     /// ```
580     pub FLAT_MAP_IDENTITY,
581     complexity,
582     "call to `flat_map` where `flatten` is sufficient"
583 }
584
585 declare_clippy_lint! {
586     /// **What it does:** Checks for an iterator or string search (such as `find()`,
587     /// `position()`, or `rposition()`) followed by a call to `is_some()`.
588     ///
589     /// **Why is this bad?** Readability, this can be written more concisely as
590     /// `_.any(_)` or `_.contains(_)`.
591     ///
592     /// **Known problems:** None.
593     ///
594     /// **Example:**
595     /// ```rust
596     /// # let vec = vec![1];
597     /// vec.iter().find(|x| **x == 0).is_some();
598     /// ```
599     /// Could be written as
600     /// ```rust
601     /// # let vec = vec![1];
602     /// vec.iter().any(|x| *x == 0);
603     /// ```
604     pub SEARCH_IS_SOME,
605     complexity,
606     "using an iterator or string search followed by `is_some()`, which is more succinctly expressed as a call to `any()` or `contains()`"
607 }
608
609 declare_clippy_lint! {
610     /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
611     /// if it starts with a given char.
612     ///
613     /// **Why is this bad?** Readability, this can be written more concisely as
614     /// `_.starts_with(_)`.
615     ///
616     /// **Known problems:** None.
617     ///
618     /// **Example:**
619     /// ```rust
620     /// let name = "foo";
621     /// if name.chars().next() == Some('_') {};
622     /// ```
623     /// Could be written as
624     /// ```rust
625     /// let name = "foo";
626     /// if name.starts_with('_') {};
627     /// ```
628     pub CHARS_NEXT_CMP,
629     style,
630     "using `.chars().next()` to check if a string starts with a char"
631 }
632
633 declare_clippy_lint! {
634     /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
635     /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
636     /// `unwrap_or_default` instead.
637     ///
638     /// **Why is this bad?** The function will always be called and potentially
639     /// allocate an object acting as the default.
640     ///
641     /// **Known problems:** If the function has side-effects, not calling it will
642     /// change the semantic of the program, but you shouldn't rely on that anyway.
643     ///
644     /// **Example:**
645     /// ```rust
646     /// # let foo = Some(String::new());
647     /// foo.unwrap_or(String::new());
648     /// ```
649     /// this can instead be written:
650     /// ```rust
651     /// # let foo = Some(String::new());
652     /// foo.unwrap_or_else(String::new);
653     /// ```
654     /// or
655     /// ```rust
656     /// # let foo = Some(String::new());
657     /// foo.unwrap_or_default();
658     /// ```
659     pub OR_FUN_CALL,
660     perf,
661     "using any `*or` method with a function call, which suggests `*or_else`"
662 }
663
664 declare_clippy_lint! {
665     /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
666     /// etc., and suggests to use `unwrap_or_else` instead
667     ///
668     /// **Why is this bad?** The function will always be called.
669     ///
670     /// **Known problems:** If the function has side-effects, not calling it will
671     /// change the semantics of the program, but you shouldn't rely on that anyway.
672     ///
673     /// **Example:**
674     /// ```rust
675     /// # let foo = Some(String::new());
676     /// # let err_code = "418";
677     /// # let err_msg = "I'm a teapot";
678     /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
679     /// ```
680     /// or
681     /// ```rust
682     /// # let foo = Some(String::new());
683     /// # let err_code = "418";
684     /// # let err_msg = "I'm a teapot";
685     /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
686     /// ```
687     /// this can instead be written:
688     /// ```rust
689     /// # let foo = Some(String::new());
690     /// # let err_code = "418";
691     /// # let err_msg = "I'm a teapot";
692     /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
693     /// ```
694     pub EXPECT_FUN_CALL,
695     perf,
696     "using any `expect` method with a function call"
697 }
698
699 declare_clippy_lint! {
700     /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
701     ///
702     /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
703     /// generics, not for using the `clone` method on a concrete type.
704     ///
705     /// **Known problems:** None.
706     ///
707     /// **Example:**
708     /// ```rust
709     /// 42u64.clone();
710     /// ```
711     pub CLONE_ON_COPY,
712     complexity,
713     "using `clone` on a `Copy` type"
714 }
715
716 declare_clippy_lint! {
717     /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
718     /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
719     /// function syntax instead (e.g., `Rc::clone(foo)`).
720     ///
721     /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
722     /// can obscure the fact that only the pointer is being cloned, not the underlying
723     /// data.
724     ///
725     /// **Example:**
726     /// ```rust
727     /// # use std::rc::Rc;
728     /// let x = Rc::new(1);
729     ///
730     /// // Bad
731     /// x.clone();
732     ///
733     /// // Good
734     /// Rc::clone(&x);
735     /// ```
736     pub CLONE_ON_REF_PTR,
737     restriction,
738     "using 'clone' on a ref-counted pointer"
739 }
740
741 declare_clippy_lint! {
742     /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
743     ///
744     /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
745     /// cloning the underlying `T`.
746     ///
747     /// **Known problems:** None.
748     ///
749     /// **Example:**
750     /// ```rust
751     /// fn main() {
752     ///     let x = vec![1];
753     ///     let y = &&x;
754     ///     let z = y.clone();
755     ///     println!("{:p} {:p}", *y, z); // prints out the same pointer
756     /// }
757     /// ```
758     pub CLONE_DOUBLE_REF,
759     correctness,
760     "using `clone` on `&&T`"
761 }
762
763 declare_clippy_lint! {
764     /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
765     /// `T` implements `ToString` directly (like `&&str` or `&&String`).
766     ///
767     /// **Why is this bad?** This bypasses the specialized implementation of
768     /// `ToString` and instead goes through the more expensive string formatting
769     /// facilities.
770     ///
771     /// **Known problems:** None.
772     ///
773     /// **Example:**
774     /// ```rust
775     /// // Generic implementation for `T: Display` is used (slow)
776     /// ["foo", "bar"].iter().map(|s| s.to_string());
777     ///
778     /// // OK, the specialized impl is used
779     /// ["foo", "bar"].iter().map(|&s| s.to_string());
780     /// ```
781     pub INEFFICIENT_TO_STRING,
782     pedantic,
783     "using `to_string` on `&&T` where `T: ToString`"
784 }
785
786 declare_clippy_lint! {
787     /// **What it does:** Checks for `new` not returning a type that contains `Self`.
788     ///
789     /// **Why is this bad?** As a convention, `new` methods are used to make a new
790     /// instance of a type.
791     ///
792     /// **Known problems:** None.
793     ///
794     /// **Example:**
795     /// In an impl block:
796     /// ```rust
797     /// # struct Foo;
798     /// # struct NotAFoo;
799     /// impl Foo {
800     ///     fn new() -> NotAFoo {
801     /// # NotAFoo
802     ///     }
803     /// }
804     /// ```
805     ///
806     /// ```rust
807     /// # struct Foo;
808     /// struct Bar(Foo);
809     /// impl Foo {
810     ///     // Bad. The type name must contain `Self`
811     ///     fn new() -> Bar {
812     /// # Bar(Foo)
813     ///     }
814     /// }
815     /// ```
816     ///
817     /// ```rust
818     /// # struct Foo;
819     /// # struct FooError;
820     /// impl Foo {
821     ///     // Good. Return type contains `Self`
822     ///     fn new() -> Result<Foo, FooError> {
823     /// # Ok(Foo)
824     ///     }
825     /// }
826     /// ```
827     ///
828     /// Or in a trait definition:
829     /// ```rust
830     /// pub trait Trait {
831     ///     // Bad. The type name must contain `Self`
832     ///     fn new();
833     /// }
834     /// ```
835     ///
836     /// ```rust
837     /// pub trait Trait {
838     ///     // Good. Return type contains `Self`
839     ///     fn new() -> Self;
840     /// }
841     /// ```
842     pub NEW_RET_NO_SELF,
843     style,
844     "not returning type containing `Self` in a `new` method"
845 }
846
847 declare_clippy_lint! {
848     /// **What it does:** Checks for string methods that receive a single-character
849     /// `str` as an argument, e.g., `_.split("x")`.
850     ///
851     /// **Why is this bad?** Performing these methods using a `char` is faster than
852     /// using a `str`.
853     ///
854     /// **Known problems:** Does not catch multi-byte unicode characters.
855     ///
856     /// **Example:**
857     /// ```rust,ignore
858     /// // Bad
859     /// _.split("x");
860     ///
861     /// // Good
862     /// _.split('x');
863     pub SINGLE_CHAR_PATTERN,
864     perf,
865     "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
866 }
867
868 declare_clippy_lint! {
869     /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
870     ///
871     /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
872     /// actually intend to panic.
873     ///
874     /// **Known problems:** None.
875     ///
876     /// **Example:**
877     /// ```rust,should_panic
878     /// for x in (0..100).step_by(0) {
879     ///     //..
880     /// }
881     /// ```
882     pub ITERATOR_STEP_BY_ZERO,
883     correctness,
884     "using `Iterator::step_by(0)`, which will panic at runtime"
885 }
886
887 declare_clippy_lint! {
888     /// **What it does:** Checks for the use of `iter.nth(0)`.
889     ///
890     /// **Why is this bad?** `iter.next()` is equivalent to
891     /// `iter.nth(0)`, as they both consume the next element,
892     ///  but is more readable.
893     ///
894     /// **Known problems:** None.
895     ///
896     /// **Example:**
897     ///
898     /// ```rust
899     /// # use std::collections::HashSet;
900     /// // Bad
901     /// # let mut s = HashSet::new();
902     /// # s.insert(1);
903     /// let x = s.iter().nth(0);
904     ///
905     /// // Good
906     /// # let mut s = HashSet::new();
907     /// # s.insert(1);
908     /// let x = s.iter().next();
909     /// ```
910     pub ITER_NTH_ZERO,
911     style,
912     "replace `iter.nth(0)` with `iter.next()`"
913 }
914
915 declare_clippy_lint! {
916     /// **What it does:** Checks for use of `.iter().nth()` (and the related
917     /// `.iter_mut().nth()`) on standard library types with O(1) element access.
918     ///
919     /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
920     /// readable.
921     ///
922     /// **Known problems:** None.
923     ///
924     /// **Example:**
925     /// ```rust
926     /// let some_vec = vec![0, 1, 2, 3];
927     /// let bad_vec = some_vec.iter().nth(3);
928     /// let bad_slice = &some_vec[..].iter().nth(3);
929     /// ```
930     /// The correct use would be:
931     /// ```rust
932     /// let some_vec = vec![0, 1, 2, 3];
933     /// let bad_vec = some_vec.get(3);
934     /// let bad_slice = &some_vec[..].get(3);
935     /// ```
936     pub ITER_NTH,
937     perf,
938     "using `.iter().nth()` on a standard library type with O(1) element access"
939 }
940
941 declare_clippy_lint! {
942     /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
943     ///
944     /// **Why is this bad?** `.nth(x)` is cleaner
945     ///
946     /// **Known problems:** None.
947     ///
948     /// **Example:**
949     /// ```rust
950     /// let some_vec = vec![0, 1, 2, 3];
951     /// let bad_vec = some_vec.iter().skip(3).next();
952     /// let bad_slice = &some_vec[..].iter().skip(3).next();
953     /// ```
954     /// The correct use would be:
955     /// ```rust
956     /// let some_vec = vec![0, 1, 2, 3];
957     /// let bad_vec = some_vec.iter().nth(3);
958     /// let bad_slice = &some_vec[..].iter().nth(3);
959     /// ```
960     pub ITER_SKIP_NEXT,
961     style,
962     "using `.skip(x).next()` on an iterator"
963 }
964
965 declare_clippy_lint! {
966     /// **What it does:** Checks for use of `.get().unwrap()` (or
967     /// `.get_mut().unwrap`) on a standard library type which implements `Index`
968     ///
969     /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
970     /// concise.
971     ///
972     /// **Known problems:** Not a replacement for error handling: Using either
973     /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
974     /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
975     /// temporary placeholder for dealing with the `Option` type, then this does
976     /// not mitigate the need for error handling. If there is a chance that `.get()`
977     /// will be `None` in your program, then it is advisable that the `None` case
978     /// is handled in a future refactor instead of using `.unwrap()` or the Index
979     /// trait.
980     ///
981     /// **Example:**
982     /// ```rust
983     /// let mut some_vec = vec![0, 1, 2, 3];
984     /// let last = some_vec.get(3).unwrap();
985     /// *some_vec.get_mut(0).unwrap() = 1;
986     /// ```
987     /// The correct use would be:
988     /// ```rust
989     /// let mut some_vec = vec![0, 1, 2, 3];
990     /// let last = some_vec[3];
991     /// some_vec[0] = 1;
992     /// ```
993     pub GET_UNWRAP,
994     restriction,
995     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
996 }
997
998 declare_clippy_lint! {
999     /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
1000     /// `&str` or `String`.
1001     ///
1002     /// **Why is this bad?** `.push_str(s)` is clearer
1003     ///
1004     /// **Known problems:** None.
1005     ///
1006     /// **Example:**
1007     /// ```rust
1008     /// let abc = "abc";
1009     /// let def = String::from("def");
1010     /// let mut s = String::new();
1011     /// s.extend(abc.chars());
1012     /// s.extend(def.chars());
1013     /// ```
1014     /// The correct use would be:
1015     /// ```rust
1016     /// let abc = "abc";
1017     /// let def = String::from("def");
1018     /// let mut s = String::new();
1019     /// s.push_str(abc);
1020     /// s.push_str(&def);
1021     /// ```
1022     pub STRING_EXTEND_CHARS,
1023     style,
1024     "using `x.extend(s.chars())` where s is a `&str` or `String`"
1025 }
1026
1027 declare_clippy_lint! {
1028     /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
1029     /// create a `Vec`.
1030     ///
1031     /// **Why is this bad?** `.to_vec()` is clearer
1032     ///
1033     /// **Known problems:** None.
1034     ///
1035     /// **Example:**
1036     /// ```rust
1037     /// let s = [1, 2, 3, 4, 5];
1038     /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1039     /// ```
1040     /// The better use would be:
1041     /// ```rust
1042     /// let s = [1, 2, 3, 4, 5];
1043     /// let s2: Vec<isize> = s.to_vec();
1044     /// ```
1045     pub ITER_CLONED_COLLECT,
1046     style,
1047     "using `.cloned().collect()` on slice to create a `Vec`"
1048 }
1049
1050 declare_clippy_lint! {
1051     /// **What it does:** Checks for usage of `_.chars().last()` or
1052     /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1053     ///
1054     /// **Why is this bad?** Readability, this can be written more concisely as
1055     /// `_.ends_with(_)`.
1056     ///
1057     /// **Known problems:** None.
1058     ///
1059     /// **Example:**
1060     /// ```rust
1061     /// # let name = "_";
1062     ///
1063     /// // Bad
1064     /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1065     ///
1066     /// // Good
1067     /// name.ends_with('_') || name.ends_with('-');
1068     /// ```
1069     pub CHARS_LAST_CMP,
1070     style,
1071     "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1072 }
1073
1074 declare_clippy_lint! {
1075     /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1076     /// types before and after the call are the same.
1077     ///
1078     /// **Why is this bad?** The call is unnecessary.
1079     ///
1080     /// **Known problems:** None.
1081     ///
1082     /// **Example:**
1083     /// ```rust
1084     /// # fn do_stuff(x: &[i32]) {}
1085     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1086     /// do_stuff(x.as_ref());
1087     /// ```
1088     /// The correct use would be:
1089     /// ```rust
1090     /// # fn do_stuff(x: &[i32]) {}
1091     /// let x: &[i32] = &[1, 2, 3, 4, 5];
1092     /// do_stuff(x);
1093     /// ```
1094     pub USELESS_ASREF,
1095     complexity,
1096     "using `as_ref` where the types before and after the call are the same"
1097 }
1098
1099 declare_clippy_lint! {
1100     /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1101     /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1102     /// `sum` or `product`.
1103     ///
1104     /// **Why is this bad?** Readability.
1105     ///
1106     /// **Known problems:** None.
1107     ///
1108     /// **Example:**
1109     /// ```rust
1110     /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1111     /// ```
1112     /// This could be written as:
1113     /// ```rust
1114     /// let _ = (0..3).any(|x| x > 2);
1115     /// ```
1116     pub UNNECESSARY_FOLD,
1117     style,
1118     "using `fold` when a more succinct alternative exists"
1119 }
1120
1121 declare_clippy_lint! {
1122     /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1123     /// More specifically it checks if the closure provided is only performing one of the
1124     /// filter or map operations and suggests the appropriate option.
1125     ///
1126     /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1127     /// operation is being performed.
1128     ///
1129     /// **Known problems:** None
1130     ///
1131     /// **Example:**
1132     /// ```rust
1133     /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1134     ///
1135     /// // As there is no transformation of the argument this could be written as:
1136     /// let _ = (0..3).filter(|&x| x > 2);
1137     /// ```
1138     ///
1139     /// ```rust
1140     /// let _ = (0..4).filter_map(|x| Some(x + 1));
1141     ///
1142     /// // As there is no conditional check on the argument this could be written as:
1143     /// let _ = (0..4).map(|x| x + 1);
1144     /// ```
1145     pub UNNECESSARY_FILTER_MAP,
1146     complexity,
1147     "using `filter_map` when a more succinct alternative exists"
1148 }
1149
1150 declare_clippy_lint! {
1151     /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1152     /// or `iter_mut`.
1153     ///
1154     /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1155     /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1156     /// `iter_mut` directly.
1157     ///
1158     /// **Known problems:** None
1159     ///
1160     /// **Example:**
1161     ///
1162     /// ```rust
1163     /// // Bad
1164     /// let _ = (&vec![3, 4, 5]).into_iter();
1165     ///
1166     /// // Good
1167     /// let _ = (&vec![3, 4, 5]).iter();
1168     /// ```
1169     pub INTO_ITER_ON_REF,
1170     style,
1171     "using `.into_iter()` on a reference"
1172 }
1173
1174 declare_clippy_lint! {
1175     /// **What it does:** Checks for calls to `map` followed by a `count`.
1176     ///
1177     /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1178     /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1179     /// drive the iterator to completion, you can just use `for_each` instead.
1180     ///
1181     /// **Known problems:** None
1182     ///
1183     /// **Example:**
1184     ///
1185     /// ```rust
1186     /// let _ = (0..3).map(|x| x + 2).count();
1187     /// ```
1188     pub SUSPICIOUS_MAP,
1189     complexity,
1190     "suspicious usage of map"
1191 }
1192
1193 declare_clippy_lint! {
1194     /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1195     ///
1196     /// **Why is this bad?** For most types, this is undefined behavior.
1197     ///
1198     /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1199     /// of `MaybeUninit`. There may be other types that allow uninitialized
1200     /// data, but those are not yet rigorously defined.
1201     ///
1202     /// **Example:**
1203     ///
1204     /// ```rust
1205     /// // Beware the UB
1206     /// use std::mem::MaybeUninit;
1207     ///
1208     /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1209     /// ```
1210     ///
1211     /// Note that the following is OK:
1212     ///
1213     /// ```rust
1214     /// use std::mem::MaybeUninit;
1215     ///
1216     /// let _: [MaybeUninit<bool>; 5] = unsafe {
1217     ///     MaybeUninit::uninit().assume_init()
1218     /// };
1219     /// ```
1220     pub UNINIT_ASSUMED_INIT,
1221     correctness,
1222     "`MaybeUninit::uninit().assume_init()`"
1223 }
1224
1225 declare_clippy_lint! {
1226     /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1227     ///
1228     /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1229     ///
1230     /// **Example:**
1231     ///
1232     /// ```rust
1233     /// # let y: u32 = 0;
1234     /// # let x: u32 = 100;
1235     /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1236     /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1237     /// ```
1238     ///
1239     /// can be written using dedicated methods for saturating addition/subtraction as:
1240     ///
1241     /// ```rust
1242     /// # let y: u32 = 0;
1243     /// # let x: u32 = 100;
1244     /// let add = x.saturating_add(y);
1245     /// let sub = x.saturating_sub(y);
1246     /// ```
1247     pub MANUAL_SATURATING_ARITHMETIC,
1248     style,
1249     "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1250 }
1251
1252 declare_clippy_lint! {
1253     /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1254     /// zero-sized types
1255     ///
1256     /// **Why is this bad?** This is a no-op, and likely unintended
1257     ///
1258     /// **Known problems:** None
1259     ///
1260     /// **Example:**
1261     /// ```rust
1262     /// unsafe { (&() as *const ()).offset(1) };
1263     /// ```
1264     pub ZST_OFFSET,
1265     correctness,
1266     "Check for offset calculations on raw pointers to zero-sized types"
1267 }
1268
1269 declare_clippy_lint! {
1270     /// **What it does:** Checks for `FileType::is_file()`.
1271     ///
1272     /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1273     /// they are testing whether a path is something they can get bytes from. But
1274     /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1275     /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1276     ///
1277     /// **Example:**
1278     ///
1279     /// ```rust
1280     /// # || {
1281     /// let metadata = std::fs::metadata("foo.txt")?;
1282     /// let filetype = metadata.file_type();
1283     ///
1284     /// if filetype.is_file() {
1285     ///     // read file
1286     /// }
1287     /// # Ok::<_, std::io::Error>(())
1288     /// # };
1289     /// ```
1290     ///
1291     /// should be written as:
1292     ///
1293     /// ```rust
1294     /// # || {
1295     /// let metadata = std::fs::metadata("foo.txt")?;
1296     /// let filetype = metadata.file_type();
1297     ///
1298     /// if !filetype.is_dir() {
1299     ///     // read file
1300     /// }
1301     /// # Ok::<_, std::io::Error>(())
1302     /// # };
1303     /// ```
1304     pub FILETYPE_IS_FILE,
1305     restriction,
1306     "`FileType::is_file` is not recommended to test for readable file type"
1307 }
1308
1309 declare_clippy_lint! {
1310     /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1311     ///
1312     /// **Why is this bad?** Readability, this can be written more concisely as
1313     /// `_.as_deref()`.
1314     ///
1315     /// **Known problems:** None.
1316     ///
1317     /// **Example:**
1318     /// ```rust
1319     /// # let opt = Some("".to_string());
1320     /// opt.as_ref().map(String::as_str)
1321     /// # ;
1322     /// ```
1323     /// Can be written as
1324     /// ```rust
1325     /// # let opt = Some("".to_string());
1326     /// opt.as_deref()
1327     /// # ;
1328     /// ```
1329     pub OPTION_AS_REF_DEREF,
1330     complexity,
1331     "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1332 }
1333
1334 declare_clippy_lint! {
1335     /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1336     ///
1337     /// **Why is this bad?** These can be shortened into `.get()`
1338     ///
1339     /// **Known problems:** None.
1340     ///
1341     /// **Example:**
1342     /// ```rust
1343     /// # let a = [1, 2, 3];
1344     /// # let b = vec![1, 2, 3];
1345     /// a[2..].iter().next();
1346     /// b.iter().next();
1347     /// ```
1348     /// should be written as:
1349     /// ```rust
1350     /// # let a = [1, 2, 3];
1351     /// # let b = vec![1, 2, 3];
1352     /// a.get(2);
1353     /// b.get(0);
1354     /// ```
1355     pub ITER_NEXT_SLICE,
1356     style,
1357     "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1358 }
1359
1360 declare_clippy_lint! {
1361     /// **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal
1362     /// where `push`/`insert` with a `char` would work fine.
1363     ///
1364     /// **Why is this bad?** It's less clear that we are pushing a single character.
1365     ///
1366     /// **Known problems:** None
1367     ///
1368     /// **Example:**
1369     /// ```rust
1370     /// let mut string = String::new();
1371     /// string.insert_str(0, "R");
1372     /// string.push_str("R");
1373     /// ```
1374     /// Could be written as
1375     /// ```rust
1376     /// let mut string = String::new();
1377     /// string.insert(0, 'R');
1378     /// string.push('R');
1379     /// ```
1380     pub SINGLE_CHAR_ADD_STR,
1381     style,
1382     "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1383 }
1384
1385 declare_clippy_lint! {
1386     /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1387     /// lazily evaluated closures on `Option` and `Result`.
1388     ///
1389     /// This lint suggests changing the following functions, when eager evaluation results in
1390     /// simpler code:
1391     ///  - `unwrap_or_else` to `unwrap_or`
1392     ///  - `and_then` to `and`
1393     ///  - `or_else` to `or`
1394     ///  - `get_or_insert_with` to `get_or_insert`
1395     ///  - `ok_or_else` to `ok_or`
1396     ///
1397     /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1398     ///
1399     /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1400     /// side effects. Eagerly evaluating them can change the semantics of the program.
1401     ///
1402     /// **Example:**
1403     ///
1404     /// ```rust
1405     /// // example code where clippy issues a warning
1406     /// let opt: Option<u32> = None;
1407     ///
1408     /// opt.unwrap_or_else(|| 42);
1409     /// ```
1410     /// Use instead:
1411     /// ```rust
1412     /// let opt: Option<u32> = None;
1413     ///
1414     /// opt.unwrap_or(42);
1415     /// ```
1416     pub UNNECESSARY_LAZY_EVALUATIONS,
1417     style,
1418     "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1419 }
1420
1421 declare_clippy_lint! {
1422     /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1423     ///
1424     /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1425     ///
1426     /// **Known problems:** None
1427     ///
1428     /// **Example:**
1429     ///
1430     /// ```rust
1431     /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1432     /// ```
1433     /// Use instead:
1434     /// ```rust
1435     /// (0..3).try_for_each(|t| Err(t));
1436     /// ```
1437     pub MAP_COLLECT_RESULT_UNIT,
1438     style,
1439     "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1440 }
1441
1442 declare_clippy_lint! {
1443     /// **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator`
1444     /// trait.
1445     ///
1446     /// **Why is this bad?** It is recommended style to use collect. See
1447     /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1448     ///
1449     /// **Known problems:** None.
1450     ///
1451     /// **Example:**
1452     ///
1453     /// ```rust
1454     /// use std::iter::FromIterator;
1455     ///
1456     /// let five_fives = std::iter::repeat(5).take(5);
1457     ///
1458     /// let v = Vec::from_iter(five_fives);
1459     ///
1460     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1461     /// ```
1462     /// Use instead:
1463     /// ```rust
1464     /// let five_fives = std::iter::repeat(5).take(5);
1465     ///
1466     /// let v: Vec<i32> = five_fives.collect();
1467     ///
1468     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1469     /// ```
1470     pub FROM_ITER_INSTEAD_OF_COLLECT,
1471     style,
1472     "use `.collect()` instead of `::from_iter()`"
1473 }
1474
1475 declare_clippy_lint! {
1476     /// **What it does:** Checks for usage of `inspect().for_each()`.
1477     ///
1478     /// **Why is this bad?** It is the same as performing the computation
1479     /// inside `inspect` at the beginning of the closure in `for_each`.
1480     ///
1481     /// **Known problems:** None.
1482     ///
1483     /// **Example:**
1484     ///
1485     /// ```rust
1486     /// [1,2,3,4,5].iter()
1487     /// .inspect(|&x| println!("inspect the number: {}", x))
1488     /// .for_each(|&x| {
1489     ///     assert!(x >= 0);
1490     /// });
1491     /// ```
1492     /// Can be written as
1493     /// ```rust
1494     /// [1,2,3,4,5].iter()
1495     /// .for_each(|&x| {
1496     ///     println!("inspect the number: {}", x);
1497     ///     assert!(x >= 0);
1498     /// });
1499     /// ```
1500     pub INSPECT_FOR_EACH,
1501     complexity,
1502     "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1503 }
1504
1505 declare_clippy_lint! {
1506     /// **What it does:** Checks for usage of `filter_map(|x| x)`.
1507     ///
1508     /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
1509     ///
1510     /// **Known problems:** None.
1511     ///
1512     /// **Example:**
1513     ///
1514     /// ```rust
1515     /// # let iter = vec![Some(1)].into_iter();
1516     /// iter.filter_map(|x| x);
1517     /// ```
1518     /// Use instead:
1519     /// ```rust
1520     /// # let iter = vec![Some(1)].into_iter();
1521     /// iter.flatten();
1522     /// ```
1523     pub FILTER_MAP_IDENTITY,
1524     complexity,
1525     "call to `filter_map` where `flatten` is sufficient"
1526 }
1527
1528 declare_clippy_lint! {
1529     /// **What it does:** Checks for the use of `.bytes().nth()`.
1530     ///
1531     /// **Why is this bad?** `.as_bytes().get()` is more efficient and more
1532     /// readable.
1533     ///
1534     /// **Known problems:** None.
1535     ///
1536     /// **Example:**
1537     ///
1538     /// ```rust
1539     /// // Bad
1540     /// let _ = "Hello".bytes().nth(3);
1541     ///
1542     /// // Good
1543     /// let _ = "Hello".as_bytes().get(3);
1544     /// ```
1545     pub BYTES_NTH,
1546     style,
1547     "replace `.bytes().nth()` with `.as_bytes().get()`"
1548 }
1549
1550 declare_clippy_lint! {
1551     /// **What it does:** Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1552     ///
1553     /// **Why is this bad?** These methods do the same thing as `_.clone()` but may be confusing as
1554     /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1555     ///
1556     /// **Known problems:** None.
1557     ///
1558     /// **Example:**
1559     ///
1560     /// ```rust
1561     /// let a = vec![1, 2, 3];
1562     /// let b = a.to_vec();
1563     /// let c = a.to_owned();
1564     /// ```
1565     /// Use instead:
1566     /// ```rust
1567     /// let a = vec![1, 2, 3];
1568     /// let b = a.clone();
1569     /// let c = a.clone();
1570     /// ```
1571     pub IMPLICIT_CLONE,
1572     pedantic,
1573     "implicitly cloning a value by invoking a function on its dereferenced type"
1574 }
1575
1576 declare_clippy_lint! {
1577     /// **What it does:** Checks for the use of `.iter().count()`.
1578     ///
1579     /// **Why is this bad?** `.len()` is more efficient and more
1580     /// readable.
1581     ///
1582     /// **Known problems:** None.
1583     ///
1584     /// **Example:**
1585     ///
1586     /// ```rust
1587     /// // Bad
1588     /// let some_vec = vec![0, 1, 2, 3];
1589     /// let _ = some_vec.iter().count();
1590     /// let _ = &some_vec[..].iter().count();
1591     ///
1592     /// // Good
1593     /// let some_vec = vec![0, 1, 2, 3];
1594     /// let _ = some_vec.len();
1595     /// let _ = &some_vec[..].len();
1596     /// ```
1597     pub ITER_COUNT,
1598     complexity,
1599     "replace `.iter().count()` with `.len()`"
1600 }
1601
1602 pub struct Methods {
1603     msrv: Option<RustcVersion>,
1604 }
1605
1606 impl Methods {
1607     #[must_use]
1608     pub fn new(msrv: Option<RustcVersion>) -> Self {
1609         Self { msrv }
1610     }
1611 }
1612
1613 impl_lint_pass!(Methods => [
1614     UNWRAP_USED,
1615     EXPECT_USED,
1616     SHOULD_IMPLEMENT_TRAIT,
1617     WRONG_SELF_CONVENTION,
1618     WRONG_PUB_SELF_CONVENTION,
1619     OK_EXPECT,
1620     MAP_UNWRAP_OR,
1621     RESULT_MAP_OR_INTO_OPTION,
1622     OPTION_MAP_OR_NONE,
1623     BIND_INSTEAD_OF_MAP,
1624     OR_FUN_CALL,
1625     EXPECT_FUN_CALL,
1626     CHARS_NEXT_CMP,
1627     CHARS_LAST_CMP,
1628     CLONE_ON_COPY,
1629     CLONE_ON_REF_PTR,
1630     CLONE_DOUBLE_REF,
1631     INEFFICIENT_TO_STRING,
1632     NEW_RET_NO_SELF,
1633     SINGLE_CHAR_PATTERN,
1634     SINGLE_CHAR_ADD_STR,
1635     SEARCH_IS_SOME,
1636     FILTER_NEXT,
1637     SKIP_WHILE_NEXT,
1638     FILTER_MAP,
1639     FILTER_MAP_IDENTITY,
1640     MANUAL_FILTER_MAP,
1641     MANUAL_FIND_MAP,
1642     FILTER_MAP_NEXT,
1643     FLAT_MAP_IDENTITY,
1644     MAP_FLATTEN,
1645     ITERATOR_STEP_BY_ZERO,
1646     ITER_NEXT_SLICE,
1647     ITER_COUNT,
1648     ITER_NTH,
1649     ITER_NTH_ZERO,
1650     BYTES_NTH,
1651     ITER_SKIP_NEXT,
1652     GET_UNWRAP,
1653     STRING_EXTEND_CHARS,
1654     ITER_CLONED_COLLECT,
1655     USELESS_ASREF,
1656     UNNECESSARY_FOLD,
1657     UNNECESSARY_FILTER_MAP,
1658     INTO_ITER_ON_REF,
1659     SUSPICIOUS_MAP,
1660     UNINIT_ASSUMED_INIT,
1661     MANUAL_SATURATING_ARITHMETIC,
1662     ZST_OFFSET,
1663     FILETYPE_IS_FILE,
1664     OPTION_AS_REF_DEREF,
1665     UNNECESSARY_LAZY_EVALUATIONS,
1666     MAP_COLLECT_RESULT_UNIT,
1667     FROM_ITER_INSTEAD_OF_COLLECT,
1668     INSPECT_FOR_EACH,
1669     IMPLICIT_CLONE
1670 ]);
1671
1672 impl<'tcx> LateLintPass<'tcx> for Methods {
1673     #[allow(clippy::too_many_lines)]
1674     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1675         if in_macro(expr.span) {
1676             return;
1677         }
1678
1679         let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1680         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1681         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1682
1683         match method_names.as_slice() {
1684             ["unwrap", "get"] => get_unwrap::check(cx, expr, arg_lists[1], false),
1685             ["unwrap", "get_mut"] => get_unwrap::check(cx, expr, arg_lists[1], true),
1686             ["unwrap", ..] => unwrap_used::check(cx, expr, arg_lists[0]),
1687             ["expect", "ok"] => ok_expect::check(cx, expr, arg_lists[1]),
1688             ["expect", ..] => expect_used::check(cx, expr, arg_lists[0]),
1689             ["unwrap_or", "map"] => option_map_unwrap_or::check(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1690             ["unwrap_or_else", "map"] => {
1691                 if !map_unwrap_or::check(cx, expr, arg_lists[1], arg_lists[0], self.msrv.as_ref()) {
1692                     unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "unwrap_or");
1693                 }
1694             },
1695             ["map_or", ..] => option_map_or_none::check(cx, expr, arg_lists[0]),
1696             ["and_then", ..] => {
1697                 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, arg_lists[0]);
1698                 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, arg_lists[0]);
1699                 if !biom_option_linted && !biom_result_linted {
1700                     unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "and");
1701                 }
1702             },
1703             ["or_else", ..] => {
1704                 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, arg_lists[0]) {
1705                     unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "or");
1706                 }
1707             },
1708             ["next", "filter"] => filter_next::check(cx, expr, arg_lists[1]),
1709             ["next", "skip_while"] => skip_while_next::check(cx, expr, arg_lists[1]),
1710             ["next", "iter"] => iter_next_slice::check(cx, expr, arg_lists[1]),
1711             ["map", "filter"] => filter_map::check(cx, expr, false),
1712             ["map", "filter_map"] => filter_map_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1713             ["next", "filter_map"] => filter_map_next::check(cx, expr, arg_lists[1], self.msrv.as_ref()),
1714             ["map", "find"] => filter_map::check(cx, expr, true),
1715             ["flat_map", "filter"] => filter_flat_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1716             ["flat_map", "filter_map"] => filter_map_flat_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1717             ["flat_map", ..] => flat_map_identity::check(cx, expr, arg_lists[0], method_spans[0]),
1718             ["flatten", "map"] => map_flatten::check(cx, expr, arg_lists[1]),
1719             ["is_some", "find"] => search_is_some::check(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1720             ["is_some", "position"] => {
1721                 search_is_some::check(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1722             },
1723             ["is_some", "rposition"] => {
1724                 search_is_some::check(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1725             },
1726             ["extend", ..] => string_extend_chars::check(cx, expr, arg_lists[0]),
1727             ["count", "into_iter"] => iter_count::check(cx, expr, &arg_lists[1], "into_iter"),
1728             ["count", "iter"] => iter_count::check(cx, expr, &arg_lists[1], "iter"),
1729             ["count", "iter_mut"] => iter_count::check(cx, expr, &arg_lists[1], "iter_mut"),
1730             ["nth", "iter"] => iter_nth::check(cx, expr, &arg_lists, false),
1731             ["nth", "iter_mut"] => iter_nth::check(cx, expr, &arg_lists, true),
1732             ["nth", "bytes"] => bytes_nth::check(cx, expr, &arg_lists[1]),
1733             ["nth", ..] => iter_nth_zero::check(cx, expr, arg_lists[0]),
1734             ["step_by", ..] => iterator_step_by_zero::check(cx, expr, arg_lists[0]),
1735             ["next", "skip"] => iter_skip_next::check(cx, expr, arg_lists[1]),
1736             ["collect", "cloned"] => iter_cloned_collect::check(cx, expr, arg_lists[1]),
1737             ["as_ref"] => useless_asref::check(cx, expr, "as_ref", arg_lists[0]),
1738             ["as_mut"] => useless_asref::check(cx, expr, "as_mut", arg_lists[0]),
1739             ["fold", ..] => unnecessary_fold::check(cx, expr, arg_lists[0], method_spans[0]),
1740             ["filter_map", ..] => {
1741                 unnecessary_filter_map::check(cx, expr, arg_lists[0]);
1742                 filter_map_identity::check(cx, expr, arg_lists[0], method_spans[0]);
1743             },
1744             ["count", "map"] => suspicious_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1745             ["assume_init"] => uninit_assumed_init::check(cx, &arg_lists[0][0], expr),
1746             ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1747                 manual_saturating_arithmetic::check(cx, expr, &arg_lists, &arith["checked_".len()..])
1748             },
1749             ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1750                 zst_offset::check(cx, expr, arg_lists[0])
1751             },
1752             ["is_file", ..] => filetype_is_file::check(cx, expr, arg_lists[0]),
1753             ["map", "as_ref"] => {
1754                 option_as_ref_deref::check(cx, expr, arg_lists[1], arg_lists[0], false, self.msrv.as_ref())
1755             },
1756             ["map", "as_mut"] => {
1757                 option_as_ref_deref::check(cx, expr, arg_lists[1], arg_lists[0], true, self.msrv.as_ref())
1758             },
1759             ["unwrap_or_else", ..] => unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "unwrap_or"),
1760             ["get_or_insert_with", ..] => unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "get_or_insert"),
1761             ["ok_or_else", ..] => unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "ok_or"),
1762             ["collect", "map"] => map_collect_result_unit::check(cx, expr, arg_lists[1], arg_lists[0]),
1763             ["for_each", "inspect"] => inspect_for_each::check(cx, expr, method_spans[1]),
1764             ["to_owned", ..] => implicit_clone::check(cx, expr, sym::ToOwned),
1765             ["to_os_string", ..] => implicit_clone::check(cx, expr, sym::OsStr),
1766             ["to_path_buf", ..] => implicit_clone::check(cx, expr, sym::Path),
1767             ["to_vec", ..] => implicit_clone::check(cx, expr, sym::slice),
1768             _ => {},
1769         }
1770
1771         match expr.kind {
1772             hir::ExprKind::Call(ref func, ref args) => {
1773                 if let hir::ExprKind::Path(path) = &func.kind {
1774                     if match_qpath(path, &["from_iter"]) {
1775                         from_iter_instead_of_collect::check(cx, expr, args);
1776                     }
1777                 }
1778             },
1779             hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1780                 or_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1781                 expect_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1782
1783                 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1784                 if args.len() == 1 && method_call.ident.name == sym::clone {
1785                     clone_on_copy::check(cx, expr, &args[0], self_ty);
1786                     clone_on_ref_ptr::check(cx, expr, &args[0]);
1787                 }
1788                 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1789                     inefficient_to_string::check(cx, expr, &args[0], self_ty);
1790                 }
1791
1792                 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
1793                     if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
1794                         single_char_push_string::check(cx, expr, args);
1795                     } else if match_def_path(cx, fn_def_id, &paths::INSERT_STR) {
1796                         single_char_insert_string::check(cx, expr, args);
1797                     }
1798                 }
1799
1800                 match self_ty.kind() {
1801                     ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
1802                         for &(method, pos) in &PATTERN_METHODS {
1803                             if method_call.ident.name.as_str() == method && args.len() > pos {
1804                                 single_char_pattern::check(cx, expr, &args[pos]);
1805                             }
1806                         }
1807                     },
1808                     ty::Ref(..) if method_call.ident.name == sym::into_iter => {
1809                         into_iter_on_ref::check(cx, expr, self_ty, *method_span);
1810                     },
1811                     _ => (),
1812                 }
1813             },
1814             hir::ExprKind::Binary(op, ref lhs, ref rhs)
1815                 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1816             {
1817                 let mut info = BinaryExprInfo {
1818                     expr,
1819                     chain: lhs,
1820                     other: rhs,
1821                     eq: op.node == hir::BinOpKind::Eq,
1822                 };
1823                 lint_binary_expr_with_method_call(cx, &mut info);
1824             }
1825             _ => (),
1826         }
1827     }
1828
1829     #[allow(clippy::too_many_lines)]
1830     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1831         if in_external_macro(cx.sess(), impl_item.span) {
1832             return;
1833         }
1834         let name = impl_item.ident.name.as_str();
1835         let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
1836         let item = cx.tcx.hir().expect_item(parent);
1837         let self_ty = cx.tcx.type_of(item.def_id);
1838
1839         // if this impl block implements a trait, lint in trait definition instead
1840         if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
1841             return;
1842         }
1843
1844         if_chain! {
1845             if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1846             if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1847
1848             let method_sig = cx.tcx.fn_sig(impl_item.def_id);
1849             let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1850
1851             let first_arg_ty = &method_sig.inputs().iter().next();
1852
1853             // check conventions w.r.t. conversion method names and predicates
1854             if let Some(first_arg_ty) = first_arg_ty;
1855
1856             then {
1857                 if cx.access_levels.is_exported(impl_item.hir_id()) {
1858                     // check missing trait implementations
1859                     for method_config in &TRAIT_METHODS {
1860                         if name == method_config.method_name &&
1861                             sig.decl.inputs.len() == method_config.param_count &&
1862                             method_config.output_type.matches(cx, &sig.decl.output) &&
1863                             method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1864                             fn_header_equals(method_config.fn_header, sig.header) &&
1865                             method_config.lifetime_param_cond(&impl_item)
1866                         {
1867                             span_lint_and_help(
1868                                 cx,
1869                                 SHOULD_IMPLEMENT_TRAIT,
1870                                 impl_item.span,
1871                                 &format!(
1872                                     "method `{}` can be confused for the standard trait method `{}::{}`",
1873                                     method_config.method_name,
1874                                     method_config.trait_name,
1875                                     method_config.method_name
1876                                 ),
1877                                 None,
1878                                 &format!(
1879                                     "consider implementing the trait `{}` or choosing a less ambiguous method name",
1880                                     method_config.trait_name
1881                                 )
1882                             );
1883                         }
1884                     }
1885                 }
1886
1887                 wrong_self_convention::check(
1888                     cx,
1889                     &name,
1890                     item.vis.node.is_pub(),
1891                     self_ty,
1892                     first_arg_ty,
1893                     first_arg.pat.span
1894                 );
1895             }
1896         }
1897
1898         if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1899             let ret_ty = return_ty(cx, impl_item.hir_id());
1900
1901             // walk the return type and check for Self (this does not check associated types)
1902             if contains_ty(ret_ty, self_ty) {
1903                 return;
1904             }
1905
1906             // if return type is impl trait, check the associated types
1907             if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1908                 // one of the associated types must be Self
1909                 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1910                     if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1911                         // walk the associated type and check for Self
1912                         if contains_ty(projection_predicate.ty, self_ty) {
1913                             return;
1914                         }
1915                     }
1916                 }
1917             }
1918
1919             if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1920                 span_lint(
1921                     cx,
1922                     NEW_RET_NO_SELF,
1923                     impl_item.span,
1924                     "methods called `new` usually return `Self`",
1925                 );
1926             }
1927         }
1928     }
1929
1930     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1931         if in_external_macro(cx.tcx.sess, item.span) {
1932             return;
1933         }
1934
1935         if_chain! {
1936             if let TraitItemKind::Fn(ref sig, _) = item.kind;
1937             if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
1938             let first_arg_span = first_arg_ty.span;
1939             let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
1940             let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1941
1942             then {
1943                 wrong_self_convention::check(
1944                     cx,
1945                     &item.ident.name.as_str(),
1946                     false,
1947                     self_ty,
1948                     first_arg_ty,
1949                     first_arg_span
1950                 );
1951             }
1952         }
1953
1954         if_chain! {
1955             if item.ident.name == sym::new;
1956             if let TraitItemKind::Fn(_, _) = item.kind;
1957             let ret_ty = return_ty(cx, item.hir_id());
1958             let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1959             if !contains_ty(ret_ty, self_ty);
1960
1961             then {
1962                 span_lint(
1963                     cx,
1964                     NEW_RET_NO_SELF,
1965                     item.span,
1966                     "methods called `new` usually return `Self`",
1967                 );
1968             }
1969         }
1970     }
1971
1972     extract_msrv_attr!(LateContext);
1973 }
1974
1975 fn derefs_to_slice<'tcx>(
1976     cx: &LateContext<'tcx>,
1977     expr: &'tcx hir::Expr<'tcx>,
1978     ty: Ty<'tcx>,
1979 ) -> Option<&'tcx hir::Expr<'tcx>> {
1980     fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
1981         match ty.kind() {
1982             ty::Slice(_) => true,
1983             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1984             ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
1985             ty::Array(_, size) => size
1986                 .try_eval_usize(cx.tcx, cx.param_env)
1987                 .map_or(false, |size| size < 32),
1988             ty::Ref(_, inner, _) => may_slice(cx, inner),
1989             _ => false,
1990         }
1991     }
1992
1993     if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
1994         if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
1995             Some(&args[0])
1996         } else {
1997             None
1998         }
1999     } else {
2000         match ty.kind() {
2001             ty::Slice(_) => Some(expr),
2002             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2003             ty::Ref(_, inner, _) => {
2004                 if may_slice(cx, inner) {
2005                     Some(expr)
2006                 } else {
2007                     None
2008                 }
2009             },
2010             _ => None,
2011         }
2012     }
2013 }
2014
2015 /// Used for `lint_binary_expr_with_method_call`.
2016 #[derive(Copy, Clone)]
2017 struct BinaryExprInfo<'a> {
2018     expr: &'a hir::Expr<'a>,
2019     chain: &'a hir::Expr<'a>,
2020     other: &'a hir::Expr<'a>,
2021     eq: bool,
2022 }
2023
2024 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2025 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2026     macro_rules! lint_with_both_lhs_and_rhs {
2027         ($func:ident, $cx:expr, $info:ident) => {
2028             if !$func($cx, $info) {
2029                 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2030                 if $func($cx, $info) {
2031                     return;
2032                 }
2033             }
2034         };
2035     }
2036
2037     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2038     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2039     lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2040     lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2041 }
2042
2043 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2044 fn lint_chars_cmp(
2045     cx: &LateContext<'_>,
2046     info: &BinaryExprInfo<'_>,
2047     chain_methods: &[&str],
2048     lint: &'static Lint,
2049     suggest: &str,
2050 ) -> bool {
2051     if_chain! {
2052         if let Some(args) = method_chain_args(info.chain, chain_methods);
2053         if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2054         if arg_char.len() == 1;
2055         if let hir::ExprKind::Path(ref qpath) = fun.kind;
2056         if let Some(segment) = single_segment_path(qpath);
2057         if segment.ident.name == sym::Some;
2058         then {
2059             let mut applicability = Applicability::MachineApplicable;
2060             let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
2061
2062             if *self_ty.kind() != ty::Str {
2063                 return false;
2064             }
2065
2066             span_lint_and_sugg(
2067                 cx,
2068                 lint,
2069                 info.expr.span,
2070                 &format!("you should use the `{}` method", suggest),
2071                 "like this",
2072                 format!("{}{}.{}({})",
2073                         if info.eq { "" } else { "!" },
2074                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
2075                         suggest,
2076                         snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
2077                 applicability,
2078             );
2079
2080             return true;
2081         }
2082     }
2083
2084     false
2085 }
2086
2087 /// Checks for the `CHARS_NEXT_CMP` lint.
2088 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2089     lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2090 }
2091
2092 /// Checks for the `CHARS_LAST_CMP` lint.
2093 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2094     if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2095         true
2096     } else {
2097         lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2098     }
2099 }
2100
2101 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2102 fn lint_chars_cmp_with_unwrap<'tcx>(
2103     cx: &LateContext<'tcx>,
2104     info: &BinaryExprInfo<'_>,
2105     chain_methods: &[&str],
2106     lint: &'static Lint,
2107     suggest: &str,
2108 ) -> bool {
2109     if_chain! {
2110         if let Some(args) = method_chain_args(info.chain, chain_methods);
2111         if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2112         if let ast::LitKind::Char(c) = lit.node;
2113         then {
2114             let mut applicability = Applicability::MachineApplicable;
2115             span_lint_and_sugg(
2116                 cx,
2117                 lint,
2118                 info.expr.span,
2119                 &format!("you should use the `{}` method", suggest),
2120                 "like this",
2121                 format!("{}{}.{}('{}')",
2122                         if info.eq { "" } else { "!" },
2123                         snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
2124                         suggest,
2125                         c),
2126                 applicability,
2127             );
2128
2129             true
2130         } else {
2131             false
2132         }
2133     }
2134 }
2135
2136 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2137 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2138     lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2139 }
2140
2141 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2142 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2143     if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2144         true
2145     } else {
2146         lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
2147     }
2148 }
2149
2150 fn get_hint_if_single_char_arg(
2151     cx: &LateContext<'_>,
2152     arg: &hir::Expr<'_>,
2153     applicability: &mut Applicability,
2154 ) -> Option<String> {
2155     if_chain! {
2156         if let hir::ExprKind::Lit(lit) = &arg.kind;
2157         if let ast::LitKind::Str(r, style) = lit.node;
2158         let string = r.as_str();
2159         if string.chars().count() == 1;
2160         then {
2161             let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
2162             let ch = if let ast::StrStyle::Raw(nhash) = style {
2163                 let nhash = nhash as usize;
2164                 // for raw string: r##"a"##
2165                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
2166             } else {
2167                 // for regular string: "a"
2168                 &snip[1..(snip.len() - 1)]
2169             };
2170             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
2171             Some(hint)
2172         } else {
2173             None
2174         }
2175     }
2176 }
2177
2178 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2179     unsafety: hir::Unsafety::Normal,
2180     constness: hir::Constness::NotConst,
2181     asyncness: hir::IsAsync::NotAsync,
2182     abi: rustc_target::spec::abi::Abi::Rust,
2183 };
2184
2185 struct ShouldImplTraitCase {
2186     trait_name: &'static str,
2187     method_name: &'static str,
2188     param_count: usize,
2189     fn_header: hir::FnHeader,
2190     // implicit self kind expected (none, self, &self, ...)
2191     self_kind: SelfKind,
2192     // checks against the output type
2193     output_type: OutType,
2194     // certain methods with explicit lifetimes can't implement the equivalent trait method
2195     lint_explicit_lifetime: bool,
2196 }
2197 impl ShouldImplTraitCase {
2198     const fn new(
2199         trait_name: &'static str,
2200         method_name: &'static str,
2201         param_count: usize,
2202         fn_header: hir::FnHeader,
2203         self_kind: SelfKind,
2204         output_type: OutType,
2205         lint_explicit_lifetime: bool,
2206     ) -> ShouldImplTraitCase {
2207         ShouldImplTraitCase {
2208             trait_name,
2209             method_name,
2210             param_count,
2211             fn_header,
2212             self_kind,
2213             output_type,
2214             lint_explicit_lifetime,
2215         }
2216     }
2217
2218     fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2219         self.lint_explicit_lifetime
2220             || !impl_item.generics.params.iter().any(|p| {
2221                 matches!(
2222                     p.kind,
2223                     hir::GenericParamKind::Lifetime {
2224                         kind: hir::LifetimeParamKind::Explicit
2225                     }
2226                 )
2227             })
2228     }
2229 }
2230
2231 #[rustfmt::skip]
2232 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2233     ShouldImplTraitCase::new("std::ops::Add", "add",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2234     ShouldImplTraitCase::new("std::convert::AsMut", "as_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2235     ShouldImplTraitCase::new("std::convert::AsRef", "as_ref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2236     ShouldImplTraitCase::new("std::ops::BitAnd", "bitand",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2237     ShouldImplTraitCase::new("std::ops::BitOr", "bitor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2238     ShouldImplTraitCase::new("std::ops::BitXor", "bitxor",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2239     ShouldImplTraitCase::new("std::borrow::Borrow", "borrow",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2240     ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2241     ShouldImplTraitCase::new("std::clone::Clone", "clone",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
2242     ShouldImplTraitCase::new("std::cmp::Ord", "cmp",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Any, true),
2243     // FIXME: default doesn't work
2244     ShouldImplTraitCase::new("std::default::Default", "default",  0,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2245     ShouldImplTraitCase::new("std::ops::Deref", "deref",  1,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2246     ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2247     ShouldImplTraitCase::new("std::ops::Div", "div",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2248     ShouldImplTraitCase::new("std::ops::Drop", "drop",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Unit, true),
2249     ShouldImplTraitCase::new("std::cmp::PartialEq", "eq",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Bool, true),
2250     ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2251     ShouldImplTraitCase::new("std::str::FromStr", "from_str",  1,  FN_HEADER,  SelfKind::No,  OutType::Any, true),
2252     ShouldImplTraitCase::new("std::hash::Hash", "hash",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Unit, true),
2253     ShouldImplTraitCase::new("std::ops::Index", "index",  2,  FN_HEADER,  SelfKind::Ref,  OutType::Ref, true),
2254     ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut",  2,  FN_HEADER,  SelfKind::RefMut,  OutType::Ref, true),
2255     ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2256     ShouldImplTraitCase::new("std::ops::Mul", "mul",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2257     ShouldImplTraitCase::new("std::ops::Neg", "neg",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2258     ShouldImplTraitCase::new("std::iter::Iterator", "next",  1,  FN_HEADER,  SelfKind::RefMut,  OutType::Any, false),
2259     ShouldImplTraitCase::new("std::ops::Not", "not",  1,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2260     ShouldImplTraitCase::new("std::ops::Rem", "rem",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2261     ShouldImplTraitCase::new("std::ops::Shl", "shl",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2262     ShouldImplTraitCase::new("std::ops::Shr", "shr",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2263     ShouldImplTraitCase::new("std::ops::Sub", "sub",  2,  FN_HEADER,  SelfKind::Value,  OutType::Any, true),
2264 ];
2265
2266 #[rustfmt::skip]
2267 const PATTERN_METHODS: [(&str, usize); 17] = [
2268     ("contains", 1),
2269     ("starts_with", 1),
2270     ("ends_with", 1),
2271     ("find", 1),
2272     ("rfind", 1),
2273     ("split", 1),
2274     ("rsplit", 1),
2275     ("split_terminator", 1),
2276     ("rsplit_terminator", 1),
2277     ("splitn", 2),
2278     ("rsplitn", 2),
2279     ("matches", 1),
2280     ("rmatches", 1),
2281     ("match_indices", 1),
2282     ("rmatch_indices", 1),
2283     ("trim_start_matches", 1),
2284     ("trim_end_matches", 1),
2285 ];
2286
2287 #[derive(Clone, Copy, PartialEq, Debug)]
2288 enum SelfKind {
2289     Value,
2290     Ref,
2291     RefMut,
2292     No,
2293 }
2294
2295 impl SelfKind {
2296     fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2297         fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2298             if ty == parent_ty {
2299                 true
2300             } else if ty.is_box() {
2301                 ty.boxed_ty() == parent_ty
2302             } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2303                 if let ty::Adt(_, substs) = ty.kind() {
2304                     substs.types().next().map_or(false, |t| t == parent_ty)
2305                 } else {
2306                     false
2307                 }
2308             } else {
2309                 false
2310             }
2311         }
2312
2313         fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2314             if let ty::Ref(_, t, m) = *ty.kind() {
2315                 return m == mutability && t == parent_ty;
2316             }
2317
2318             let trait_path = match mutability {
2319                 hir::Mutability::Not => &paths::ASREF_TRAIT,
2320                 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2321             };
2322
2323             let trait_def_id = match get_trait_def_id(cx, trait_path) {
2324                 Some(did) => did,
2325                 None => return false,
2326             };
2327             implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2328         }
2329
2330         match self {
2331             Self::Value => matches_value(cx, parent_ty, ty),
2332             Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2333             Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2334             Self::No => ty != parent_ty,
2335         }
2336     }
2337
2338     #[must_use]
2339     fn description(self) -> &'static str {
2340         match self {
2341             Self::Value => "self by value",
2342             Self::Ref => "self by reference",
2343             Self::RefMut => "self by mutable reference",
2344             Self::No => "no self",
2345         }
2346     }
2347 }
2348
2349 #[derive(Clone, Copy)]
2350 enum OutType {
2351     Unit,
2352     Bool,
2353     Any,
2354     Ref,
2355 }
2356
2357 impl OutType {
2358     fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
2359         let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
2360         match (self, ty) {
2361             (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2362             (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
2363             (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
2364             (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
2365             (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2366             _ => false,
2367         }
2368     }
2369 }
2370
2371 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2372     if let hir::TyKind::Path(ref p) = ty.kind {
2373         match_qpath(p, &["bool"])
2374     } else {
2375         false
2376     }
2377 }
2378
2379 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2380     expected.constness == actual.constness
2381         && expected.unsafety == actual.unsafety
2382         && expected.asyncness == actual.asyncness
2383 }