1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
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;
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,
27 use if_chain::if_chain;
33 mod unnecessary_filter_map;
38 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
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.
45 /// **Known problems:** None.
51 declare_clippy_lint! {
52 pub OPTION_UNWRAP_USED,
54 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
57 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
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!`.
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.
67 /// **Known problems:** None.
73 declare_clippy_lint! {
74 pub RESULT_UNWRAP_USED,
76 "using `Result.unwrap()`, which might be better handled"
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.
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(...)`
87 /// may expect `*` to work equally, so you should have good reason to disappoint
90 /// **Known problems:** None.
96 /// fn add(&self, other: &X) -> X { .. }
99 declare_clippy_lint! {
100 pub SHOULD_IMPLEMENT_TRAIT,
102 "defining a method that should be implementing a std trait"
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:
108 /// |Prefix |`self` taken |
109 /// |-------|----------------------|
110 /// |`as_` |`&self` or `&mut self`|
112 /// |`into_`|`self` |
113 /// |`is_` |`&self` or none |
114 /// |`to_` |`&self` |
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.
120 /// **Known problems:** None.
125 /// fn as_str(self) -> &str { .. }
128 declare_clippy_lint! {
129 pub WRONG_SELF_CONVENTION,
131 "defining a method named with an established prefix (like \"into_\") that takes \
132 `self` with the wrong convention"
135 /// **What it does:** This is the same as
136 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
138 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
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.
147 /// pub fn as_str(self) -> &str { .. }
150 declare_clippy_lint! {
151 pub WRONG_PUB_SELF_CONVENTION,
153 "defining a public method named with an established prefix (like \"into_\") that takes \
154 `self` with the wrong convention"
157 /// **What it does:** Checks for usage of `ok().expect(..)`.
159 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
160 /// directly to get a better error message.
162 /// **Known problems:** The error type needs to implement `Debug`
166 /// x.ok().expect("why did I do this again?")
168 declare_clippy_lint! {
171 "using `ok().expect()`, which gives worse error messages than \
172 calling `expect` directly on the Result"
175 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
177 /// **Why is this bad?** Readability, this can be written more concisely as
178 /// `_.map_or(_, _)`.
180 /// **Known problems:** The order of the arguments is not in execution order
184 /// x.map(|a| a + 1).unwrap_or(0)
186 declare_clippy_lint! {
187 pub OPTION_MAP_UNWRAP_OR,
189 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
193 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
195 /// **Why is this bad?** Readability, this can be written more concisely as
196 /// `_.map_or_else(_, _)`.
198 /// **Known problems:** The order of the arguments is not in execution order.
202 /// x.map(|a| a + 1).unwrap_or_else(some_function)
204 declare_clippy_lint! {
205 pub OPTION_MAP_UNWRAP_OR_ELSE,
207 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
211 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
213 /// **Why is this bad?** Readability, this can be written more concisely as
214 /// `result.ok().map_or_else(_, _)`.
216 /// **Known problems:** None.
220 /// x.map(|a| a + 1).unwrap_or_else(some_function)
222 declare_clippy_lint! {
223 pub RESULT_MAP_UNWRAP_OR_ELSE,
225 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
226 `.ok().map_or_else(g, f)`"
229 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
231 /// **Why is this bad?** Readability, this can be written more concisely as
234 /// **Known problems:** The order of the arguments is not in execution order.
238 /// opt.map_or(None, |a| a + 1)
240 declare_clippy_lint! {
241 pub OPTION_MAP_OR_NONE,
243 "using `Option.map_or(None, f)`, which is more succinctly expressed as \
247 /// **What it does:** Checks for usage of `_.filter(_).next()`.
249 /// **Why is this bad?** Readability, this can be written more concisely as
252 /// **Known problems:** None.
256 /// iter.filter(|x| x == 0).next()
258 declare_clippy_lint! {
261 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
264 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
266 /// **Why is this bad?** Readability, this can be written more concisely as a
267 /// single method call.
269 /// **Known problems:**
273 /// iter.map(|x| x.iter()).flatten()
275 declare_clippy_lint! {
278 "using combinations of `flatten` and `map` which can usually be written as a \
282 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
283 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
285 /// **Why is this bad?** Readability, this can be written more concisely as a
286 /// single method call.
288 /// **Known problems:** Often requires a condition + Option/Iterator creation
289 /// inside the closure.
293 /// iter.filter(|x| x == 0).map(|x| x * 2)
295 declare_clippy_lint! {
298 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
299 usually be written as a single method call"
302 /// **What it does:** Checks for an iterator search (such as `find()`,
303 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
305 /// **Why is this bad?** Readability, this can be written more concisely as
308 /// **Known problems:** None.
312 /// iter.find(|x| x == 0).is_some()
314 declare_clippy_lint! {
317 "using an iterator search followed by `is_some()`, which is more succinctly \
318 expressed as a call to `any()`"
321 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
322 /// if it starts with a given char.
324 /// **Why is this bad?** Readability, this can be written more concisely as
325 /// `_.starts_with(_)`.
327 /// **Known problems:** None.
331 /// name.chars().next() == Some('_')
333 declare_clippy_lint! {
336 "using `.chars().next()` to check if a string starts with a char"
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.
343 /// **Why is this bad?** The function will always be called and potentially
344 /// allocate an object acting as the default.
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.
351 /// foo.unwrap_or(String::new())
353 /// this can instead be written:
355 /// foo.unwrap_or_else(String::new)
359 /// foo.unwrap_or_default()
361 declare_clippy_lint! {
364 "using any `*or` method with a function call, which suggests `*or_else`"
367 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
368 /// etc., and suggests to use `unwrap_or_else` instead
370 /// **Why is this bad?** The function will always be called.
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.
377 /// foo.expect(&format!("Err {}: {}", err_code, err_msg))
381 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str())
383 /// this can instead be written:
385 /// foo.unwrap_or_else(|_| panic!("Err {}: {}", err_code, err_msg))
387 declare_clippy_lint! {
390 "using any `expect` method with a function call"
393 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
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.
398 /// **Known problems:** None.
404 declare_clippy_lint! {
407 "using `clone` on a `Copy` type"
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)`).
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
422 declare_clippy_lint! {
423 pub CLONE_ON_REF_PTR,
425 "using 'clone' on a ref-counted pointer"
428 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
430 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
431 /// cloning the underlying `T`.
433 /// **Known problems:** None.
440 /// let z = y.clone();
441 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
444 declare_clippy_lint! {
445 pub CLONE_DOUBLE_REF,
447 "using `clone` on `&&T`"
450 /// **What it does:** Checks for `new` not returning `Self`.
452 /// **Why is this bad?** As a convention, `new` methods are used to make a new
453 /// instance of a type.
455 /// **Known problems:** None.
460 /// fn new(..) -> NotAFoo {
464 declare_clippy_lint! {
467 "not returning `Self` in a `new` method"
470 /// **What it does:** Checks for string methods that receive a single-character
471 /// `str` as an argument, e.g. `_.split("x")`.
473 /// **Why is this bad?** Performing these methods using a `char` is faster than
476 /// **Known problems:** Does not catch multi-byte unicode characters.
479 /// `_.split("x")` could be `_.split('x')`
480 declare_clippy_lint! {
481 pub SINGLE_CHAR_PATTERN,
483 "using a single-character str where a char could be used, e.g. \
487 /// **What it does:** Checks for getting the inner pointer of a temporary
490 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
491 /// as the `CString` is alive.
493 /// **Known problems:** None.
497 /// let c_str = CString::new("foo").unwrap().as_ptr();
499 /// call_some_ffi_func(c_str);
502 /// Here `c_str` point to a freed address. The correct use would be:
504 /// let c_str = CString::new("foo").unwrap();
506 /// call_some_ffi_func(c_str.as_ptr());
509 declare_clippy_lint! {
510 pub TEMPORARY_CSTRING_AS_PTR,
512 "getting the inner pointer of a temporary `CString`"
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.
518 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
521 /// **Known problems:** None.
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);
529 /// The correct use would be:
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);
535 declare_clippy_lint! {
538 "using `.iter().nth()` on a standard library type with O(1) element access"
541 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
543 /// **Why is this bad?** `.nth(x)` is cleaner
545 /// **Known problems:** None.
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();
553 /// The correct use would be:
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);
559 declare_clippy_lint! {
562 "using `.skip(x).next()` on an iterator"
565 /// **What it does:** Checks for use of `.get().unwrap()` (or
566 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
568 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
571 /// **Known problems:** None.
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;
579 /// The correct use would be:
581 /// let some_vec = vec![0, 1, 2, 3];
582 /// let last = some_vec[3];
585 declare_clippy_lint! {
588 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
591 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
592 /// `&str` or `String`.
594 /// **Why is this bad?** `.push_str(s)` is clearer
596 /// **Known problems:** None.
601 /// let def = String::from("def");
602 /// let mut s = String::new();
603 /// s.extend(abc.chars());
604 /// s.extend(def.chars());
606 /// The correct use would be:
609 /// let def = String::from("def");
610 /// let mut s = String::new();
612 /// s.push_str(&def));
614 declare_clippy_lint! {
615 pub STRING_EXTEND_CHARS,
617 "using `x.extend(s.chars())` where s is a `&str` or `String`"
620 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
623 /// **Why is this bad?** `.to_vec()` is clearer
625 /// **Known problems:** None.
629 /// let s = [1,2,3,4,5];
630 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
632 /// The better use would be:
634 /// let s = [1,2,3,4,5];
635 /// let s2 : Vec<isize> = s.to_vec();
637 declare_clippy_lint! {
638 pub ITER_CLONED_COLLECT,
640 "using `.cloned().collect()` on slice to create a `Vec`"
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.
646 /// **Why is this bad?** Readability, this can be written more concisely as
647 /// `_.ends_with(_)`.
649 /// **Known problems:** None.
653 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
655 declare_clippy_lint! {
658 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
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.
664 /// **Why is this bad?** The call is unnecessary.
666 /// **Known problems:** None.
670 /// let x: &[i32] = &[1,2,3,4,5];
671 /// do_stuff(x.as_ref());
673 /// The correct use would be:
675 /// let x: &[i32] = &[1,2,3,4,5];
678 declare_clippy_lint! {
681 "using `as_ref` where the types before and after the call are the same"
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`.
689 /// **Why is this bad?** Readability.
691 /// **Known problems:** None.
695 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
697 /// This could be written as:
699 /// let _ = (0..3).any(|x| x > 2);
701 declare_clippy_lint! {
702 pub UNNECESSARY_FOLD,
704 "using `fold` when a more succinct alternative exists"
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.
712 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
713 /// operation is being performed.
715 /// **Known problems:** None
719 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
721 /// As there is no transformation of the argument this could be written as:
723 /// let _ = (0..3).filter(|&x| x > 2);
727 /// let _ = (0..4).filter_map(i32::checked_abs);
729 /// As there is no conditional check on the argument this could be written as:
731 /// let _ = (0..4).map(i32::checked_abs);
733 declare_clippy_lint! {
734 pub UNNECESSARY_FILTER_MAP,
736 "using `filter_map` when a more succinct alternative exists"
739 impl LintPass for Pass {
740 fn get_lints(&self) -> LintArray {
744 SHOULD_IMPLEMENT_TRAIT,
745 WRONG_SELF_CONVENTION,
746 WRONG_PUB_SELF_CONVENTION,
748 OPTION_MAP_UNWRAP_OR,
749 OPTION_MAP_UNWRAP_OR_ELSE,
750 RESULT_MAP_UNWRAP_OR_ELSE,
762 TEMPORARY_CSTRING_AS_PTR,
773 UNNECESSARY_FILTER_MAP
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) {
786 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
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]);
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);
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]);
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]);
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 {
866 eq: op.node == hir::BinOpKind::Eq,
868 lint_binary_expr_with_method_call(cx, &mut info);
874 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
875 if in_external_macro(cx.sess(), implitem.span) {
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);
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;
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));
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()) {
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
913 WRONG_SELF_CONVENTION
918 &format!("methods called `{}` usually take {}; consider choosing a less \
922 .map(|k| k.description())
927 // Only check the first convention to match (CONVENTIONS should be listed from most to least specific)
934 if let hir::ImplItemKind::Method(ref sig, id) = implitem.node {
935 let ret_ty = return_ty(cx, implitem.id);
937 !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
941 "methods called `new` usually return `Self`");
947 /// Checks for the `OR_FUN_CALL` lint.
948 fn lint_or_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
949 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
950 fn check_unwrap_or_default(
951 cx: &LateContext<'_, '_>,
954 self_expr: &hir::Expr,
963 if name == "unwrap_or" {
964 if let hir::ExprKind::Path(ref qpath) = fun.node {
965 let path = &*last_path_segment(qpath).ident.as_str();
967 if ["default", "new"].contains(&path) {
968 let arg_ty = cx.tables.expr_ty(arg);
969 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
975 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
980 &format!("use of `{}` followed by a call to `{}`", name, path),
982 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
993 /// Check for `*or(foo())`.
994 #[allow(clippy::too_many_arguments)]
995 fn check_general_case(
996 cx: &LateContext<'_, '_>,
1000 self_expr: &hir::Expr,
1005 // (path, fn_has_argument, methods, suffix)
1006 let know_types: &[(&[_], _, &[_], _)] = &[
1007 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1008 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1009 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1010 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1013 // early check if the name is one we care about
1014 if know_types.iter().all(|k| !k.2.contains(&name)) {
1018 // don't lint for constant values
1019 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
1020 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
1025 let self_ty = cx.tables.expr_ty(self_expr);
1027 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
1028 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
1030 (fn_has_arguments, poss, suffix)
1035 if !poss.contains(&name) {
1039 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1040 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
1041 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
1042 (false, true) => snippet(cx, fun_span, ".."),
1044 let span_replace_word = method_span.with_hi(span.hi());
1049 &format!("use of `{}` followed by a function call", name),
1051 format!("{}_{}({})", name, suffix, sugg),
1055 if args.len() == 2 {
1056 match args[1].node {
1057 hir::ExprKind::Call(ref fun, ref or_args) => {
1058 let or_has_args = !or_args.is_empty();
1059 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1060 check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
1063 hir::ExprKind::MethodCall(_, span, ref or_args) => {
1064 check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
1071 /// Checks for the `EXPECT_FUN_CALL` lint.
1072 fn lint_expect_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
1073 fn extract_format_args(arg: &hir::Expr) -> Option<&hir::HirVec<hir::Expr>> {
1074 let arg = match &arg.node {
1075 hir::ExprKind::AddrOf(_, expr)=> expr,
1076 hir::ExprKind::MethodCall(method_name, _, args)
1077 if method_name.ident.name == "as_str" ||
1078 method_name.ident.name == "as_ref"
1083 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg.node {
1084 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1 {
1085 if let hir::ExprKind::Call(_, ref format_args) = inner_args[0].node {
1086 return Some(format_args);
1094 fn generate_format_arg_snippet(cx: &LateContext<'_, '_>, a: &hir::Expr) -> String {
1095 if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
1096 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
1097 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
1098 return snippet(cx, format_arg_expr_tup[0].span, "..").into_owned();
1103 snippet(cx, a.span, "..").into_owned()
1106 fn check_general_case(
1107 cx: &LateContext<'_, '_>,
1110 self_expr: &hir::Expr,
1114 fn is_call(node: &hir::ExprKind) -> bool {
1116 hir::ExprKind::AddrOf(_, expr) => {
1119 hir::ExprKind::Call(..)
1120 | hir::ExprKind::MethodCall(..)
1121 // These variants are debatable or require further examination
1122 | hir::ExprKind::If(..)
1123 | hir::ExprKind::Match(..)
1124 | hir::ExprKind::Block{ .. } => true,
1129 if name != "expect" {
1133 let self_type = cx.tables.expr_ty(self_expr);
1134 let known_types = &[&paths::OPTION, &paths::RESULT];
1136 // if not a known type, return early
1137 if known_types.iter().all(|&k| !match_type(cx, self_type, k)) {
1141 if !is_call(&arg.node) {
1145 let closure = if match_type(cx, self_type, &paths::OPTION) { "||" } else { "|_|" };
1146 let span_replace_word = method_span.with_hi(span.hi());
1148 if let Some(format_args) = extract_format_args(arg) {
1149 let args_len = format_args.len();
1150 let args: Vec<String> = format_args
1153 .map(|a| generate_format_arg_snippet(cx, a))
1156 let sugg = args.join(", ");
1162 &format!("use of `{}` followed by a function call", name),
1164 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1170 let sugg: Cow<'_, _> = snippet(cx, arg.span, "..");
1176 &format!("use of `{}` followed by a function call", name),
1178 format!("unwrap_or_else({} {{ let msg = {}; panic!(msg) }}))", closure, sugg),
1182 if args.len() == 2 {
1183 match args[1].node {
1184 hir::ExprKind::Lit(_) => {},
1185 _ => check_general_case(cx, name, method_span, &args[0], &args[1], expr.span),
1190 /// Checks for the `CLONE_ON_COPY` lint.
1191 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty<'_>) {
1192 let ty = cx.tables.expr_ty(expr);
1193 if let ty::Ref(_, inner, _) = arg_ty.sty {
1194 if let ty::Ref(_, innermost, _) = inner.sty {
1199 "using `clone` on a double-reference; \
1200 this will copy the reference instead of cloning the inner type",
1201 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1202 let mut ty = innermost;
1204 while let ty::Ref(_, inner, _) = ty.sty {
1208 let refs: String = iter::repeat('&').take(n + 1).collect();
1209 let derefs: String = iter::repeat('*').take(n).collect();
1210 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1211 db.span_suggestion_with_applicability(
1213 "try dereferencing it",
1214 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1215 Applicability::MaybeIncorrect,
1217 db.span_suggestion_with_applicability(
1219 "or try being explicit about what type to clone",
1221 Applicability::MaybeIncorrect,
1225 return; // don't report clone_on_copy
1229 if is_copy(cx, ty) {
1231 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1232 if let ty::Ref(..) = cx.tables.expr_ty(arg).sty {
1233 let parent = cx.tcx.hir.get_parent_node(expr.id);
1234 match cx.tcx.hir.get(parent) {
1235 hir::Node::Expr(parent) => match parent.node {
1236 // &*x is a nop, &x.clone() is not
1237 hir::ExprKind::AddrOf(..) |
1238 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1239 hir::ExprKind::MethodCall(..) => return,
1242 hir::Node::Stmt(stmt) => {
1243 if let hir::StmtKind::Decl(ref decl, _) = stmt.node {
1244 if let hir::DeclKind::Local(ref loc) = decl.node {
1245 if let hir::PatKind::Ref(..) = loc.pat.node {
1246 // let ref y = *x borrows x, let ref y = x.clone() does not
1254 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
1256 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1261 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1262 if let Some((text, snip)) = snip {
1263 db.span_suggestion_with_applicability(
1267 Applicability::Unspecified,
1274 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr) {
1275 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1277 if let ty::Adt(_, subst) = obj_ty.sty {
1278 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1280 } else if match_type(cx, obj_ty, &paths::ARC) {
1282 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1292 "using '.clone()' on a ref-counted pointer",
1294 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1300 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1302 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1303 let target = &arglists[0][0];
1304 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1305 let ref_str = if self_ty.sty == ty::Str {
1307 } else if match_type(cx, self_ty, &paths::STRING) {
1315 STRING_EXTEND_CHARS,
1317 "calling `.extend(_.chars())`",
1320 "{}.push_str({}{})",
1321 snippet(cx, args[0].span, "_"),
1323 snippet(cx, target.span, "_")
1329 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1330 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
1331 if match_type(cx, obj_ty, &paths::STRING) {
1332 lint_string_extend(cx, expr, args);
1336 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1338 if let hir::ExprKind::Call(ref fun, ref args) = new.node;
1340 if let hir::ExprKind::Path(ref path) = fun.node;
1341 if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1342 if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1346 TEMPORARY_CSTRING_AS_PTR,
1348 "you are getting the inner pointer of a temporary `CString`",
1350 db.note("that pointer will be invalid outside this expression");
1351 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1357 fn lint_iter_cloned_collect(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1358 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1359 && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1363 ITER_CLONED_COLLECT,
1365 "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1371 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1372 fn check_fold_with_op(
1373 cx: &LateContext<'_, '_>,
1374 fold_args: &[hir::Expr],
1376 replacement_method_name: &str,
1377 replacement_has_args: bool) {
1380 // Extract the body of the closure passed to fold
1381 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].node;
1382 let closure_body = cx.tcx.hir.body(body_id);
1383 let closure_expr = remove_blocks(&closure_body.value);
1385 // Check if the closure body is of the form `acc <op> some_expr(x)`
1386 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1387 if bin_op.node == op;
1389 // Extract the names of the two arguments to the closure
1390 if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1391 if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1393 if match_var(&*left_expr, first_arg_ident);
1394 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1397 // Span containing `.fold(...)`
1398 let next_point = cx.sess().source_map().next_point(fold_args[0].span);
1399 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1401 let sugg = if replacement_has_args {
1403 ".{replacement}(|{s}| {r})",
1404 replacement = replacement_method_name,
1405 s = second_arg_ident,
1406 r = snippet(cx, right_expr.span, "EXPR"),
1411 replacement = replacement_method_name,
1419 // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
1420 "this `.fold` can be written more succinctly using another method",
1428 // Check that this is a call to Iterator::fold rather than just some function called fold
1429 if !match_trait_method(cx, expr, &paths::ITERATOR) {
1433 assert!(fold_args.len() == 3,
1434 "Expected fold_args to have three entries - the receiver, the initial value and the closure");
1436 // Check if the first argument to .fold is a suitable literal
1437 match fold_args[1].node {
1438 hir::ExprKind::Lit(ref lit) => {
1440 ast::LitKind::Bool(false) => check_fold_with_op(
1441 cx, fold_args, hir::BinOpKind::Or, "any", true
1443 ast::LitKind::Bool(true) => check_fold_with_op(
1444 cx, fold_args, hir::BinOpKind::And, "all", true
1446 ast::LitKind::Int(0, _) => check_fold_with_op(
1447 cx, fold_args, hir::BinOpKind::Add, "sum", false
1449 ast::LitKind::Int(1, _) => check_fold_with_op(
1450 cx, fold_args, hir::BinOpKind::Mul, "product", false
1459 fn lint_iter_nth(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1460 let mut_str = if is_mut { "_mut" } else { "" };
1461 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1463 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1465 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1468 return; // caller is not a type that we want to lint
1476 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1483 fn lint_get_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1484 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1485 // because they do not implement `IndexMut`
1486 let expr_ty = cx.tables.expr_ty(&get_args[0]);
1487 let get_args_str = if get_args.len() > 1 {
1488 snippet(cx, get_args[1].span, "_")
1490 return; // not linting on a .get().unwrap() chain or variant
1493 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1494 needs_ref = get_args_str.parse::<usize>().is_ok();
1496 } else if match_type(cx, expr_ty, &paths::VEC) {
1497 needs_ref = get_args_str.parse::<usize>().is_ok();
1499 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1500 needs_ref = get_args_str.parse::<usize>().is_ok();
1502 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1505 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1509 return; // caller is not a type that we want to lint
1512 let mut_str = if is_mut { "_mut" } else { "" };
1513 let borrow_str = if !needs_ref { "" } else if is_mut { "&mut " } else { "&" };
1519 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1527 snippet(cx, get_args[0].span, "_"),
1533 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr) {
1534 // lint if caller of skip is an Iterator
1535 if match_trait_method(cx, expr, &paths::ITERATOR) {
1540 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1545 fn derefs_to_slice(cx: &LateContext<'_, '_>, expr: &hir::Expr, ty: Ty<'_>) -> Option<sugg::Sugg<'static>> {
1546 fn may_slice(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1548 ty::Slice(_) => true,
1549 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1550 ty::Adt(..) => match_type(cx, ty, &paths::VEC),
1551 ty::Array(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
1552 ty::Ref(_, inner, _) => may_slice(cx, inner),
1557 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.node {
1558 if path.ident.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1559 sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1565 ty::Slice(_) => sugg::Sugg::hir_opt(cx, expr),
1566 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1567 ty::Ref(_, inner, _) => if may_slice(cx, inner) {
1568 sugg::Sugg::hir_opt(cx, expr)
1577 /// lint use of `unwrap()` for `Option`s and `Result`s
1578 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1579 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
1581 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1582 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1583 } else if match_type(cx, obj_ty, &paths::RESULT) {
1584 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1589 if let Some((lint, kind, none_value)) = mess {
1595 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1596 using expect() to provide a better panic \
1605 /// lint use of `ok().expect()` for `Result`s
1606 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1607 // lint if the caller of `ok()` is a `Result`
1608 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1609 let result_type = cx.tables.expr_ty(&ok_args[0]);
1610 if let Some(error_type) = get_error_type(cx, result_type) {
1611 if has_debug_impl(error_type, cx) {
1616 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1623 /// lint use of `map().unwrap_or()` for `Option`s
1624 fn lint_map_unwrap_or(cx: &LateContext<'_, '_>, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1625 // lint if the caller of `map()` is an `Option`
1626 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1627 // get snippets for args to map() and unwrap_or()
1628 let map_snippet = snippet(cx, map_args[1].span, "..");
1629 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1631 // comparing the snippet from source to raw text ("None") below is safe
1632 // because we already have checked the type.
1633 let arg = if unwrap_snippet == "None" {
1638 let suggest = if unwrap_snippet == "None" {
1644 "called `map(f).unwrap_or({})` on an Option value. \
1645 This can be done more directly by calling `{}` instead",
1649 // lint, with note if neither arg is > 1 line and both map() and
1650 // unwrap_or() have the same span
1651 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1652 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1653 if same_span && !multiline {
1654 let suggest = if unwrap_snippet == "None" {
1655 format!("and_then({})", map_snippet)
1657 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1660 "replace `map({}).unwrap_or({})` with `{}`",
1665 span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, ¬e);
1666 } else if same_span && multiline {
1667 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1672 /// lint use of `map().flatten()` for `Iterators`
1673 fn lint_map_flatten<'a, 'tcx>(
1674 cx: &LateContext<'a, 'tcx>,
1675 expr: &'tcx hir::Expr,
1676 map_args: &'tcx [hir::Expr],
1678 // lint if caller of `.map().flatten()` is an Iterator
1679 if match_trait_method(cx, expr, &paths::ITERATOR) {
1680 let msg = "called `map(..).flatten()` on an `Iterator`. \
1681 This is more succinctly expressed by calling `.flat_map(..)`";
1682 let self_snippet = snippet(cx, map_args[0].span, "..");
1683 let func_snippet = snippet(cx, map_args[1].span, "..");
1684 let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
1685 span_lint_and_then(cx, MAP_FLATTEN, expr.span, msg, |db| {
1686 db.span_suggestion_with_applicability(
1688 "try using flat_map instead",
1690 Applicability::MachineApplicable,
1696 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1697 fn lint_map_unwrap_or_else<'a, 'tcx>(
1698 cx: &LateContext<'a, 'tcx>,
1699 expr: &'tcx hir::Expr,
1700 map_args: &'tcx [hir::Expr],
1701 unwrap_args: &'tcx [hir::Expr],
1703 // lint if the caller of `map()` is an `Option`
1704 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1705 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1706 if is_option || is_result {
1708 let msg = if is_option {
1709 "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1710 `map_or_else(g, f)` instead"
1712 "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1713 `ok().map_or_else(g, f)` instead"
1715 // get snippets for args to map() and unwrap_or_else()
1716 let map_snippet = snippet(cx, map_args[1].span, "..");
1717 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1718 // lint, with note if neither arg is > 1 line and both map() and
1719 // unwrap_or_else() have the same span
1720 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1721 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1722 if same_span && !multiline {
1726 OPTION_MAP_UNWRAP_OR_ELSE
1728 RESULT_MAP_UNWRAP_OR_ELSE
1734 "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1737 if is_result { "ok()." } else { "" }
1740 } else if same_span && multiline {
1744 OPTION_MAP_UNWRAP_OR_ELSE
1746 RESULT_MAP_UNWRAP_OR_ELSE
1755 /// lint use of `_.map_or(None, _)` for `Option`s
1756 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1757 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1758 // check if the first non-self argument to map_or() is None
1759 let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].node {
1760 match_qpath(qpath, &paths::OPTION_NONE)
1765 if map_or_arg_is_none {
1767 let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1768 `and_then(f)` instead";
1769 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1770 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1771 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1772 span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1773 db.span_suggestion_with_applicability(
1775 "try using and_then instead",
1777 Applicability::MachineApplicable, // snippet
1784 /// lint use of `filter().next()` for `Iterators`
1785 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1786 // lint if caller of `.filter().next()` is an Iterator
1787 if match_trait_method(cx, expr, &paths::ITERATOR) {
1788 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1789 `.find(p)` instead.";
1790 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1791 if filter_snippet.lines().count() <= 1 {
1792 // add note if not multi-line
1799 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1802 span_lint(cx, FILTER_NEXT, expr.span, msg);
1807 /// lint use of `filter().map()` for `Iterators`
1808 fn lint_filter_map<'a, 'tcx>(
1809 cx: &LateContext<'a, 'tcx>,
1810 expr: &'tcx hir::Expr,
1811 _filter_args: &'tcx [hir::Expr],
1812 _map_args: &'tcx [hir::Expr],
1814 // lint if caller of `.filter().map()` is an Iterator
1815 if match_trait_method(cx, expr, &paths::ITERATOR) {
1816 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1817 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1818 span_lint(cx, FILTER_MAP, expr.span, msg);
1822 /// lint use of `filter().map()` for `Iterators`
1823 fn lint_filter_map_map<'a, 'tcx>(
1824 cx: &LateContext<'a, 'tcx>,
1825 expr: &'tcx hir::Expr,
1826 _filter_args: &'tcx [hir::Expr],
1827 _map_args: &'tcx [hir::Expr],
1829 // lint if caller of `.filter().map()` is an Iterator
1830 if match_trait_method(cx, expr, &paths::ITERATOR) {
1831 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1832 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1833 span_lint(cx, FILTER_MAP, expr.span, msg);
1837 /// lint use of `filter().flat_map()` for `Iterators`
1838 fn lint_filter_flat_map<'a, 'tcx>(
1839 cx: &LateContext<'a, 'tcx>,
1840 expr: &'tcx hir::Expr,
1841 _filter_args: &'tcx [hir::Expr],
1842 _map_args: &'tcx [hir::Expr],
1844 // lint if caller of `.filter().flat_map()` is an Iterator
1845 if match_trait_method(cx, expr, &paths::ITERATOR) {
1846 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1847 This is more succinctly expressed by calling `.flat_map(..)` \
1848 and filtering by returning an empty Iterator.";
1849 span_lint(cx, FILTER_MAP, expr.span, msg);
1853 /// lint use of `filter_map().flat_map()` for `Iterators`
1854 fn lint_filter_map_flat_map<'a, 'tcx>(
1855 cx: &LateContext<'a, 'tcx>,
1856 expr: &'tcx hir::Expr,
1857 _filter_args: &'tcx [hir::Expr],
1858 _map_args: &'tcx [hir::Expr],
1860 // lint if caller of `.filter_map().flat_map()` is an Iterator
1861 if match_trait_method(cx, expr, &paths::ITERATOR) {
1862 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1863 This is more succinctly expressed by calling `.flat_map(..)` \
1864 and filtering by returning an empty Iterator.";
1865 span_lint(cx, FILTER_MAP, expr.span, msg);
1869 /// lint searching an Iterator followed by `is_some()`
1870 fn lint_search_is_some<'a, 'tcx>(
1871 cx: &LateContext<'a, 'tcx>,
1872 expr: &'tcx hir::Expr,
1873 search_method: &str,
1874 search_args: &'tcx [hir::Expr],
1875 is_some_args: &'tcx [hir::Expr],
1877 // lint if caller of search is an Iterator
1878 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1880 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1881 expressed by calling `any()`.",
1884 let search_snippet = snippet(cx, search_args[1].span, "..");
1885 if search_snippet.lines().count() <= 1 {
1886 // add note if not multi-line
1893 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1896 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1901 /// Used for `lint_binary_expr_with_method_call`.
1902 #[derive(Copy, Clone)]
1903 struct BinaryExprInfo<'a> {
1904 expr: &'a hir::Expr,
1905 chain: &'a hir::Expr,
1906 other: &'a hir::Expr,
1910 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1911 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
1912 macro_rules! lint_with_both_lhs_and_rhs {
1913 ($func:ident, $cx:expr, $info:ident) => {
1914 if !$func($cx, $info) {
1915 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1916 if $func($cx, $info) {
1923 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1924 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1925 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1926 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1929 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1931 cx: &LateContext<'_, '_>,
1932 info: &BinaryExprInfo<'_>,
1933 chain_methods: &[&str],
1934 lint: &'static Lint,
1938 if let Some(args) = method_chain_args(info.chain, chain_methods);
1939 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.node;
1940 if arg_char.len() == 1;
1941 if let hir::ExprKind::Path(ref qpath) = fun.node;
1942 if let Some(segment) = single_segment_path(qpath);
1943 if segment.ident.name == "Some";
1945 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1947 if self_ty.sty != ty::Str {
1951 span_lint_and_sugg(cx,
1954 &format!("you should use the `{}` method", suggest),
1956 format!("{}{}.{}({})",
1957 if info.eq { "" } else { "!" },
1958 snippet(cx, args[0][0].span, "_"),
1960 snippet(cx, arg_char[0].span, "_")));
1969 /// Checks for the `CHARS_NEXT_CMP` lint.
1970 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1971 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1974 /// Checks for the `CHARS_LAST_CMP` lint.
1975 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1976 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1979 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1983 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1984 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1985 cx: &LateContext<'a, 'tcx>,
1986 info: &BinaryExprInfo<'_>,
1987 chain_methods: &[&str],
1988 lint: &'static Lint,
1992 if let Some(args) = method_chain_args(info.chain, chain_methods);
1993 if let hir::ExprKind::Lit(ref lit) = info.other.node;
1994 if let ast::LitKind::Char(c) = lit.node;
2000 &format!("you should use the `{}` method", suggest),
2002 format!("{}{}.{}('{}')",
2003 if info.eq { "" } else { "!" },
2004 snippet(cx, args[0][0].span, "_"),
2016 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2017 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2018 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2021 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2022 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2023 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2026 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
2030 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
2031 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, _expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
2033 if let hir::ExprKind::Lit(lit) = &arg.node;
2034 if let ast::LitKind::Str(r, _) = lit.node;
2035 if r.as_str().len() == 1;
2037 let snip = snippet(cx, arg.span, "..");
2038 let hint = format!("'{}'", &snip[1..snip.len() - 1]);
2041 SINGLE_CHAR_PATTERN,
2043 "single-character string constant used as pattern",
2044 "try using a char instead",
2051 /// Checks for the `USELESS_ASREF` lint.
2052 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
2053 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
2054 // check if the call is to the actual `AsRef` or `AsMut` trait
2055 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
2056 // check if the type after `as_ref` or `as_mut` is the same as before
2057 let recvr = &as_ref_args[0];
2058 let rcv_ty = cx.tables.expr_ty(recvr);
2059 let res_ty = cx.tables.expr_ty(expr);
2060 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
2061 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
2062 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
2067 &format!("this call to `{}` does nothing", call_name),
2069 snippet(cx, recvr.span, "_").into_owned(),
2075 /// Given a `Result<T, E>` type, return its error type (`E`).
2076 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
2077 if let ty::Adt(_, substs) = ty.sty {
2078 if match_type(cx, ty, &paths::RESULT) {
2079 substs.types().nth(1)
2088 /// This checks whether a given type is known to implement Debug.
2089 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
2090 match cx.tcx.lang_items().debug_trait() {
2091 Some(debug) => implements_trait(cx, ty, debug, &[]),
2098 StartsWith(&'static str),
2102 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
2103 (Convention::Eq("new"), &[SelfKind::No]),
2104 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
2105 (Convention::StartsWith("from_"), &[SelfKind::No]),
2106 (Convention::StartsWith("into_"), &[SelfKind::Value]),
2107 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
2108 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
2109 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
2113 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
2114 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
2115 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
2116 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
2117 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
2118 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
2119 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
2120 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
2121 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
2122 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
2123 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
2124 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
2125 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
2126 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
2127 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
2128 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
2129 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
2130 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
2131 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
2132 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
2133 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
2134 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
2135 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
2136 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
2137 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
2138 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
2139 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
2140 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
2141 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
2142 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
2143 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
2147 const PATTERN_METHODS: [(&str, usize); 17] = [
2155 ("split_terminator", 1),
2156 ("rsplit_terminator", 1),
2161 ("match_indices", 1),
2162 ("rmatch_indices", 1),
2163 ("trim_left_matches", 1),
2164 ("trim_right_matches", 1),
2168 #[derive(Clone, Copy, PartialEq, Debug)]
2179 cx: &LateContext<'_, '_>,
2183 allow_value_for_ref: bool,
2184 generics: &hir::Generics,
2186 // Self types in the HIR are desugared to explicit self types. So it will
2189 // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
2190 // the impl is on `Foo`)
2191 // Thus, we only need to test equality against the impl self type or if it is
2193 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
2194 // `Self`, `&mut Self`,
2195 // and `Box<Self>`, including the equivalent types with `Foo`.
2197 let is_actually_self = |ty| is_self_ty(ty) || SpanlessEq::new(cx).eq_ty(ty, self_ty);
2200 SelfKind::Value => is_actually_self(ty),
2201 SelfKind::Ref | SelfKind::RefMut => {
2202 if allow_value_for_ref && is_actually_self(ty) {
2206 hir::TyKind::Rptr(_, ref mt_ty) => {
2207 let mutability_match = if self == SelfKind::Ref {
2208 mt_ty.mutbl == hir::MutImmutable
2210 mt_ty.mutbl == hir::MutMutable
2212 is_actually_self(&mt_ty.ty) && mutability_match
2221 SelfKind::Value => false,
2222 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
2223 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
2224 SelfKind::No => true,
2229 fn description(self) -> &'static str {
2231 SelfKind::Value => "self by value",
2232 SelfKind::Ref => "self by reference",
2233 SelfKind::RefMut => "self by mutable reference",
2234 SelfKind::No => "no self",
2239 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
2240 single_segment_ty(ty).map_or(false, |seg| {
2241 generics.params.iter().any(|param| match param.kind {
2242 hir::GenericParamKind::Type { .. } => {
2243 param.name.ident().name == seg.ident.name && param.bounds.iter().any(|bound| {
2244 if let hir::GenericBound::Trait(ref ptr, ..) = *bound {
2245 let path = &ptr.trait_ref.path;
2246 match_path(path, name) && path.segments.last().map_or(false, |s| {
2247 if let Some(ref params) = s.args {
2248 if params.parenthesized {
2251 // FIXME(flip1995): messy, improve if there is a better option
2253 let types: Vec<_> = params.args.iter().filter_map(|arg| match arg {
2254 hir::GenericArg::Type(ty) => Some(ty),
2258 && (is_self_ty(&types[0]) || is_ty(&*types[0], self_ty))
2274 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
2275 match (&ty.node, &self_ty.node) {
2277 &hir::TyKind::Path(hir::QPath::Resolved(_, ref ty_path)),
2278 &hir::TyKind::Path(hir::QPath::Resolved(_, ref self_ty_path)),
2282 .map(|seg| seg.ident.name)
2283 .eq(self_ty_path.segments.iter().map(|seg| seg.ident.name)),
2288 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2289 if let hir::TyKind::Path(ref path) = ty.node {
2290 single_segment_path(path)
2297 fn check(&self, other: &str) -> bool {
2299 Convention::Eq(this) => this == other,
2300 Convention::StartsWith(this) => other.starts_with(this) && this != other,
2305 impl fmt::Display for Convention {
2306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
2308 Convention::Eq(this) => this.fmt(f),
2309 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2314 #[derive(Clone, Copy)]
2323 fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FunctionRetTy) -> bool {
2324 let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
2326 (OutType::Unit, &hir::DefaultReturn(_)) => true,
2327 (OutType::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,
2328 (OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2329 (OutType::Any, &hir::Return(ref ty)) if !is_unit(ty) => true,
2330 (OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyKind::Rptr(_, _)),
2336 fn is_bool(ty: &hir::Ty) -> bool {
2337 if let hir::TyKind::Path(ref p) = ty.node {
2338 match_qpath(p, &["bool"])