3 use rustc::ty::{self, Ty};
4 use rustc::hir::def::Def;
9 use syntax::codemap::{Span, BytePos};
10 use crate::utils::{get_arg_name, get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_expn_of, is_self,
11 is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
12 match_type, method_chain_args, match_var, return_ty, remove_blocks, same_tys, single_segment_path, snippet,
13 span_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
14 use crate::utils::paths;
15 use crate::utils::sugg;
16 use crate::consts::{constant, Constant};
21 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
23 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
24 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
25 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
26 /// `Allow` by default.
28 /// **Known problems:** None.
34 declare_clippy_lint! {
35 pub OPTION_UNWRAP_USED,
37 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
40 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
42 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
43 /// values. Normally, you want to implement more sophisticated error handling,
44 /// and propagate errors upwards with `try!`.
46 /// Even if you want to panic on errors, not all `Error`s implement good
47 /// messages on display. Therefore it may be beneficial to look at the places
48 /// where they may get displayed. Activate this lint to do just that.
50 /// **Known problems:** None.
56 declare_clippy_lint! {
57 pub RESULT_UNWRAP_USED,
59 "using `Result.unwrap()`, which might be better handled"
62 /// **What it does:** Checks for methods that should live in a trait
63 /// implementation of a `std` trait (see [llogiq's blog
64 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
65 /// information) instead of an inherent implementation.
67 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
68 /// the code, often with very little cost. Also people seeing a `mul(...)`
70 /// may expect `*` to work equally, so you should have good reason to disappoint
73 /// **Known problems:** None.
79 /// fn add(&self, other: &X) -> X { .. }
82 declare_clippy_lint! {
83 pub SHOULD_IMPLEMENT_TRAIT,
85 "defining a method that should be implementing a std trait"
88 /// **What it does:** Checks for methods with certain name prefixes and which
89 /// doesn't match how self is taken. The actual rules are:
91 /// |Prefix |`self` taken |
92 /// |-------|----------------------|
93 /// |`as_` |`&self` or `&mut self`|
96 /// |`is_` |`&self` or none |
99 /// **Why is this bad?** Consistency breeds readability. If you follow the
100 /// conventions, your users won't be surprised that they, e.g., need to supply a
101 /// mutable reference to a `as_..` function.
103 /// **Known problems:** None.
108 /// fn as_str(self) -> &str { .. }
111 declare_clippy_lint! {
112 pub WRONG_SELF_CONVENTION,
114 "defining a method named with an established prefix (like \"into_\") that takes \
115 `self` with the wrong convention"
118 /// **What it does:** This is the same as
119 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
121 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
123 /// **Known problems:** Actually *renaming* the function may break clients if
124 /// the function is part of the public interface. In that case, be mindful of
125 /// the stability guarantees you've given your users.
130 /// pub fn as_str(self) -> &str { .. }
133 declare_clippy_lint! {
134 pub WRONG_PUB_SELF_CONVENTION,
136 "defining a public method named with an established prefix (like \"into_\") that takes \
137 `self` with the wrong convention"
140 /// **What it does:** Checks for usage of `ok().expect(..)`.
142 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
143 /// directly to get a better error message.
145 /// **Known problems:** The error type needs to implement `Debug`
149 /// x.ok().expect("why did I do this again?")
151 declare_clippy_lint! {
154 "using `ok().expect()`, which gives worse error messages than \
155 calling `expect` directly on the Result"
158 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
160 /// **Why is this bad?** Readability, this can be written more concisely as
161 /// `_.map_or(_, _)`.
163 /// **Known problems:** The order of the arguments is not in execution order
167 /// x.map(|a| a + 1).unwrap_or(0)
169 declare_clippy_lint! {
170 pub OPTION_MAP_UNWRAP_OR,
172 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
176 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
178 /// **Why is this bad?** Readability, this can be written more concisely as
179 /// `_.map_or_else(_, _)`.
181 /// **Known problems:** The order of the arguments is not in execution order.
185 /// x.map(|a| a + 1).unwrap_or_else(some_function)
187 declare_clippy_lint! {
188 pub OPTION_MAP_UNWRAP_OR_ELSE,
190 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
194 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
196 /// **Why is this bad?** Readability, this can be written more concisely as
197 /// `result.ok().map_or_else(_, _)`.
199 /// **Known problems:** None.
203 /// x.map(|a| a + 1).unwrap_or_else(some_function)
205 declare_clippy_lint! {
206 pub RESULT_MAP_UNWRAP_OR_ELSE,
208 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
209 `.ok().map_or_else(g, f)`"
212 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
214 /// **Why is this bad?** Readability, this can be written more concisely as
217 /// **Known problems:** The order of the arguments is not in execution order.
221 /// opt.map_or(None, |a| a + 1)
223 declare_clippy_lint! {
224 pub OPTION_MAP_OR_NONE,
226 "using `Option.map_or(None, f)`, which is more succinctly expressed as \
230 /// **What it does:** Checks for usage of `_.filter(_).next()`.
232 /// **Why is this bad?** Readability, this can be written more concisely as
235 /// **Known problems:** None.
239 /// iter.filter(|x| x == 0).next()
241 declare_clippy_lint! {
244 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
247 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
248 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
250 /// **Why is this bad?** Readability, this can be written more concisely as a
251 /// single method call.
253 /// **Known problems:** Often requires a condition + Option/Iterator creation
254 /// inside the closure.
258 /// iter.filter(|x| x == 0).map(|x| x * 2)
260 declare_clippy_lint! {
263 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
264 usually be written as a single method call"
267 /// **What it does:** Checks for an iterator search (such as `find()`,
268 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
270 /// **Why is this bad?** Readability, this can be written more concisely as
273 /// **Known problems:** None.
277 /// iter.find(|x| x == 0).is_some()
279 declare_clippy_lint! {
282 "using an iterator search followed by `is_some()`, which is more succinctly \
283 expressed as a call to `any()`"
286 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
287 /// if it starts with a given char.
289 /// **Why is this bad?** Readability, this can be written more concisely as
290 /// `_.starts_with(_)`.
292 /// **Known problems:** None.
296 /// name.chars().next() == Some('_')
298 declare_clippy_lint! {
301 "using `.chars().next()` to check if a string starts with a char"
304 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
305 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
306 /// `unwrap_or_default` instead.
308 /// **Why is this bad?** The function will always be called and potentially
309 /// allocate an object acting as the default.
311 /// **Known problems:** If the function has side-effects, not calling it will
312 /// change the semantic of the program, but you shouldn't rely on that anyway.
316 /// foo.unwrap_or(String::new())
318 /// this can instead be written:
320 /// foo.unwrap_or_else(String::new)
324 /// foo.unwrap_or_default()
326 declare_clippy_lint! {
329 "using any `*or` method with a function call, which suggests `*or_else`"
332 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
333 /// etc., and suggests to use `unwrap_or_else` instead
335 /// **Why is this bad?** The function will always be called.
337 /// **Known problems:** If the function has side-effects, not calling it will
338 /// change the semantic of the program, but you shouldn't rely on that anyway.
342 /// foo.expect(&format("Err {}: {}", err_code, err_msg))
346 /// foo.expect(format("Err {}: {}", err_code, err_msg).as_str())
348 /// this can instead be written:
350 /// foo.unwrap_or_else(|_| panic!(&format("Err {}: {}", err_code, err_msg)))
352 declare_clippy_lint! {
355 "using any `expect` method with a function call"
358 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
360 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
361 /// generics, not for using the `clone` method on a concrete type.
363 /// **Known problems:** None.
369 declare_clippy_lint! {
372 "using `clone` on a `Copy` type"
375 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
376 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
377 /// function syntax instead (e.g. `Rc::clone(foo)`).
379 /// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
380 /// can obscure the fact that only the pointer is being cloned, not the underlying
387 declare_clippy_lint! {
388 pub CLONE_ON_REF_PTR,
390 "using 'clone' on a ref-counted pointer"
393 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
395 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
396 /// cloning the underlying `T`.
398 /// **Known problems:** None.
405 /// let z = y.clone();
406 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
409 declare_clippy_lint! {
410 pub CLONE_DOUBLE_REF,
412 "using `clone` on `&&T`"
415 /// **What it does:** Checks for `new` not returning `Self`.
417 /// **Why is this bad?** As a convention, `new` methods are used to make a new
418 /// instance of a type.
420 /// **Known problems:** None.
425 /// fn new(..) -> NotAFoo {
429 declare_clippy_lint! {
432 "not returning `Self` in a `new` method"
435 /// **What it does:** Checks for string methods that receive a single-character
436 /// `str` as an argument, e.g. `_.split("x")`.
438 /// **Why is this bad?** Performing these methods using a `char` is faster than
441 /// **Known problems:** Does not catch multi-byte unicode characters.
444 /// `_.split("x")` could be `_.split('x')
445 declare_clippy_lint! {
446 pub SINGLE_CHAR_PATTERN,
448 "using a single-character str where a char could be used, e.g. \
452 /// **What it does:** Checks for getting the inner pointer of a temporary
455 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
456 /// as the `CString` is alive.
458 /// **Known problems:** None.
462 /// let c_str = CString::new("foo").unwrap().as_ptr();
464 /// call_some_ffi_func(c_str);
467 /// Here `c_str` point to a freed address. The correct use would be:
469 /// let c_str = CString::new("foo").unwrap();
471 /// call_some_ffi_func(c_str.as_ptr());
474 declare_clippy_lint! {
475 pub TEMPORARY_CSTRING_AS_PTR,
477 "getting the inner pointer of a temporary `CString`"
480 /// **What it does:** Checks for use of `.iter().nth()` (and the related
481 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
483 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
486 /// **Known problems:** None.
490 /// let some_vec = vec![0, 1, 2, 3];
491 /// let bad_vec = some_vec.iter().nth(3);
492 /// let bad_slice = &some_vec[..].iter().nth(3);
494 /// The correct use would be:
496 /// let some_vec = vec![0, 1, 2, 3];
497 /// let bad_vec = some_vec.get(3);
498 /// let bad_slice = &some_vec[..].get(3);
500 declare_clippy_lint! {
503 "using `.iter().nth()` on a standard library type with O(1) element access"
506 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
508 /// **Why is this bad?** `.nth(x)` is cleaner
510 /// **Known problems:** None.
514 /// let some_vec = vec![0, 1, 2, 3];
515 /// let bad_vec = some_vec.iter().skip(3).next();
516 /// let bad_slice = &some_vec[..].iter().skip(3).next();
518 /// The correct use would be:
520 /// let some_vec = vec![0, 1, 2, 3];
521 /// let bad_vec = some_vec.iter().nth(3);
522 /// let bad_slice = &some_vec[..].iter().nth(3);
524 declare_clippy_lint! {
527 "using `.skip(x).next()` on an iterator"
530 /// **What it does:** Checks for use of `.get().unwrap()` (or
531 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
533 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
536 /// **Known problems:** None.
540 /// let some_vec = vec![0, 1, 2, 3];
541 /// let last = some_vec.get(3).unwrap();
542 /// *some_vec.get_mut(0).unwrap() = 1;
544 /// The correct use would be:
546 /// let some_vec = vec![0, 1, 2, 3];
547 /// let last = some_vec[3];
550 declare_clippy_lint! {
553 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
556 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
557 /// `&str` or `String`.
559 /// **Why is this bad?** `.push_str(s)` is clearer
561 /// **Known problems:** None.
566 /// let def = String::from("def");
567 /// let mut s = String::new();
568 /// s.extend(abc.chars());
569 /// s.extend(def.chars());
571 /// The correct use would be:
574 /// let def = String::from("def");
575 /// let mut s = String::new();
577 /// s.push_str(&def));
579 declare_clippy_lint! {
580 pub STRING_EXTEND_CHARS,
582 "using `x.extend(s.chars())` where s is a `&str` or `String`"
585 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
588 /// **Why is this bad?** `.to_vec()` is clearer
590 /// **Known problems:** None.
594 /// let s = [1,2,3,4,5];
595 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
597 /// The better use would be:
599 /// let s = [1,2,3,4,5];
600 /// let s2 : Vec<isize> = s.to_vec();
602 declare_clippy_lint! {
603 pub ITER_CLONED_COLLECT,
605 "using `.cloned().collect()` on slice to create a `Vec`"
608 /// **What it does:** Checks for usage of `.chars().last()` or
609 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
611 /// **Why is this bad?** Readability, this can be written more concisely as
612 /// `_.ends_with(_)`.
614 /// **Known problems:** None.
618 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
620 declare_clippy_lint! {
623 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
626 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
627 /// types before and after the call are the same.
629 /// **Why is this bad?** The call is unnecessary.
631 /// **Known problems:** None.
635 /// let x: &[i32] = &[1,2,3,4,5];
636 /// do_stuff(x.as_ref());
638 /// The correct use would be:
640 /// let x: &[i32] = &[1,2,3,4,5];
643 declare_clippy_lint! {
646 "using `as_ref` where the types before and after the call are the same"
650 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
651 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
652 /// `sum` or `product`.
654 /// **Why is this bad?** Readability.
656 /// **Known problems:** None.
660 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
662 /// This could be written as:
664 /// let _ = (0..3).any(|x| x > 2);
666 declare_clippy_lint! {
667 pub UNNECESSARY_FOLD,
669 "using `fold` when a more succinct alternative exists"
672 impl LintPass for Pass {
673 fn get_lints(&self) -> LintArray {
677 SHOULD_IMPLEMENT_TRAIT,
678 WRONG_SELF_CONVENTION,
679 WRONG_PUB_SELF_CONVENTION,
681 OPTION_MAP_UNWRAP_OR,
682 OPTION_MAP_UNWRAP_OR_ELSE,
683 RESULT_MAP_UNWRAP_OR_ELSE,
695 TEMPORARY_CSTRING_AS_PTR,
709 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
710 #[allow(cyclomatic_complexity)]
711 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
712 if in_macro(expr.span) {
717 hir::ExprMethodCall(ref method_call, ref method_span, ref args) => {
719 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
720 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
721 lint_get_unwrap(cx, expr, arglists[0], false);
722 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
723 lint_get_unwrap(cx, expr, arglists[0], true);
724 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
725 lint_unwrap(cx, expr, arglists[0]);
726 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
727 lint_ok_expect(cx, expr, arglists[0]);
728 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
729 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
730 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
731 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
732 } else if let Some(arglists) = method_chain_args(expr, &["map_or"]) {
733 lint_map_or_none(cx, expr, arglists[0]);
734 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
735 lint_filter_next(cx, expr, arglists[0]);
736 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
737 lint_filter_map(cx, expr, arglists[0], arglists[1]);
738 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
739 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
740 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
741 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
742 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
743 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
744 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
745 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
746 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
747 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
748 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
749 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
750 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
751 lint_extend(cx, expr, arglists[0]);
752 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
753 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
754 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
755 lint_iter_nth(cx, expr, arglists[0], false);
756 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
757 lint_iter_nth(cx, expr, arglists[0], true);
758 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
759 lint_iter_skip_next(cx, expr);
760 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
761 lint_iter_cloned_collect(cx, expr, arglists[0]);
762 } else if let Some(arglists) = method_chain_args(expr, &["as_ref"]) {
763 lint_asref(cx, expr, "as_ref", arglists[0]);
764 } else if let Some(arglists) = method_chain_args(expr, &["as_mut"]) {
765 lint_asref(cx, expr, "as_mut", arglists[0]);
766 } else if let Some(arglists) = method_chain_args(expr, &["fold"]) {
767 lint_unnecessary_fold(cx, expr, arglists[0]);
770 lint_or_fun_call(cx, expr, *method_span, &method_call.name.as_str(), args);
771 lint_expect_fun_call(cx, expr, *method_span, &method_call.name.as_str(), args);
773 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
774 if args.len() == 1 && method_call.name == "clone" {
775 lint_clone_on_copy(cx, expr, &args[0], self_ty);
776 lint_clone_on_ref_ptr(cx, expr, &args[0]);
780 ty::TyRef(_, ty, _) if ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
781 if method_call.name == method && args.len() > pos {
782 lint_single_char_pattern(cx, expr, &args[pos]);
788 hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
789 let mut info = BinaryExprInfo {
793 eq: op.node == hir::BiEq,
795 lint_binary_expr_with_method_call(cx, &mut info);
801 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
802 if in_external_macro(cx, implitem.span) {
805 let name = implitem.name;
806 let parent = cx.tcx.hir.get_parent(implitem.id);
807 let item = cx.tcx.hir.expect_item(parent);
809 if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
810 if let Some(first_arg_ty) = sig.decl.inputs.get(0);
811 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
812 if let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node;
814 if cx.access_levels.is_exported(implitem.id) {
815 // check missing trait implementations
816 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
817 if name == method_name &&
818 sig.decl.inputs.len() == n_args &&
819 out_type.matches(&sig.decl.output) &&
820 self_kind.matches(first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
821 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
822 "defining a method called `{}` on this type; consider implementing \
823 the `{}` trait or choosing a less ambiguous name", name, trait_name));
828 // check conventions w.r.t. conversion method names and predicates
829 let def_id = cx.tcx.hir.local_def_id(item.id);
830 let ty = cx.tcx.type_of(def_id);
831 let is_copy = is_copy(cx, ty);
832 for &(ref conv, self_kinds) in &CONVENTIONS {
834 if conv.check(&name.as_str());
837 .any(|k| k.matches(first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
839 let lint = if item.vis == hir::Visibility::Public {
840 WRONG_PUB_SELF_CONVENTION
842 WRONG_SELF_CONVENTION
847 &format!("methods called `{}` usually take {}; consider choosing a less \
851 .map(|k| k.description())
858 let ret_ty = return_ty(cx, implitem.id);
860 !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
864 "methods called `new` usually return `Self`");
871 /// Checks for the `OR_FUN_CALL` lint.
872 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
873 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
874 fn check_unwrap_or_default(
878 self_expr: &hir::Expr,
887 if name == "unwrap_or" {
888 if let hir::ExprPath(ref qpath) = fun.node {
889 let path = &*last_path_segment(qpath).name.as_str();
891 if ["default", "new"].contains(&path) {
892 let arg_ty = cx.tables.expr_ty(arg);
893 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
899 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
904 &format!("use of `{}` followed by a call to `{}`", name, path),
906 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
917 /// Check for `*or(foo())`.
918 #[allow(too_many_arguments)]
919 fn check_general_case(
924 self_expr: &hir::Expr,
929 // (path, fn_has_argument, methods, suffix)
930 let know_types: &[(&[_], _, &[_], _)] = &[
931 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
932 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
933 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
934 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
937 // early check if the name is one we care about
938 if know_types.iter().all(|k| !k.2.contains(&name)) {
942 // don't lint for constant values
943 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
944 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
949 let self_ty = cx.tables.expr_ty(self_expr);
951 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
952 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
954 (fn_has_arguments, poss, suffix)
959 if !poss.contains(&name) {
963 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
964 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
965 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
966 (false, true) => snippet(cx, fun_span, ".."),
968 let span_replace_word = method_span.with_hi(span.hi());
973 &format!("use of `{}` followed by a function call", name),
975 format!("{}_{}({})", name, suffix, sugg),
981 hir::ExprCall(ref fun, ref or_args) => {
982 let or_has_args = !or_args.is_empty();
983 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
984 check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
987 hir::ExprMethodCall(_, span, ref or_args) => {
988 check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
995 /// Checks for the `EXPECT_FUN_CALL` lint.
996 fn lint_expect_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
997 fn extract_format_args(arg: &hir::Expr) -> Option<&hir::HirVec<hir::Expr>> {
998 if let hir::ExprAddrOf(_, ref addr_of) = arg.node {
999 if let hir::ExprCall(ref inner_fun, ref inner_args) = addr_of.node {
1000 if let Some(_) = is_expn_of(inner_fun.span, "format") {
1001 if inner_args.len() == 1 {
1002 if let hir::ExprCall(_, ref format_args) = inner_args[0].node {
1003 return Some(format_args);
1013 fn generate_format_arg_snippet(cx: &LateContext, a: &hir::Expr) -> String {
1014 if let hir::ExprAddrOf(_, ref format_arg) = a.node {
1015 if let hir::ExprMatch(ref format_arg_expr, _, _) = format_arg.node {
1016 if let hir::ExprTup(ref format_arg_expr_tup) = format_arg_expr.node {
1017 return snippet(cx, format_arg_expr_tup[0].span, "..").into_owned();
1022 snippet(cx, a.span, "..").into_owned()
1025 fn check_general_case(
1029 self_expr: &hir::Expr,
1033 if name != "expect" {
1037 let self_type = cx.tables.expr_ty(self_expr);
1038 let known_types = &[&paths::OPTION, &paths::RESULT];
1040 // if not a known type, return early
1041 if known_types.iter().all(|&k| !match_type(cx, self_type, k)) {
1045 // don't lint for constant values
1046 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
1047 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
1052 let closure = if match_type(cx, self_type, &paths::OPTION) { "||" } else { "|_|" };
1053 let span_replace_word = method_span.with_hi(span.hi());
1055 if let Some(format_args) = extract_format_args(arg) {
1056 let args_len = format_args.len();
1057 let args: Vec<String> = format_args
1060 .map(|a| generate_format_arg_snippet(cx, a))
1063 let sugg = args.join(", ");
1069 &format!("use of `{}` followed by a function call", name),
1071 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1077 let sugg: Cow<_> = snippet(cx, arg.span, "..");
1083 &format!("use of `{}` followed by a function call", name),
1085 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1089 if args.len() == 2 {
1090 match args[1].node {
1091 hir::ExprLit(_) => {},
1092 _ => check_general_case(cx, name, method_span, &args[0], &args[1], expr.span),
1097 /// Checks for the `CLONE_ON_COPY` lint.
1098 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
1099 let ty = cx.tables.expr_ty(expr);
1100 if let ty::TyRef(_, inner, _) = arg_ty.sty {
1101 if let ty::TyRef(_, innermost, _) = inner.sty {
1106 "using `clone` on a double-reference; \
1107 this will copy the reference instead of cloning the inner type",
1108 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1109 let mut ty = innermost;
1111 while let ty::TyRef(_, inner, _) = ty.sty {
1115 let refs: String = iter::repeat('&').take(n + 1).collect();
1116 let derefs: String = iter::repeat('*').take(n).collect();
1117 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1118 db.span_suggestion(expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()));
1119 db.span_suggestion(expr.span, "or try being explicit about what type to clone", explicit);
1122 return; // don't report clone_on_copy
1126 if is_copy(cx, ty) {
1128 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1129 if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
1130 let parent = cx.tcx.hir.get_parent_node(expr.id);
1131 match cx.tcx.hir.get(parent) {
1132 hir::map::NodeExpr(parent) => match parent.node {
1133 // &*x is a nop, &x.clone() is not
1134 hir::ExprAddrOf(..) |
1135 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1136 hir::ExprMethodCall(..) => return,
1139 hir::map::NodeStmt(stmt) => {
1140 if let hir::StmtDecl(ref decl, _) = stmt.node {
1141 if let hir::DeclLocal(ref loc) = decl.node {
1142 if let hir::PatKind::Ref(..) = loc.pat.node {
1143 // let ref y = *x borrows x, let ref y = x.clone() does not
1151 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
1153 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1158 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1159 if let Some((text, snip)) = snip {
1160 db.span_suggestion(expr.span, text, snip);
1166 fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1167 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1169 if let ty::TyAdt(_, subst) = obj_ty.sty {
1170 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1172 } else if match_type(cx, obj_ty, &paths::ARC) {
1174 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1184 "using '.clone()' on a ref-counted pointer",
1186 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1192 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1194 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1195 let target = &arglists[0][0];
1196 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1197 let ref_str = if self_ty.sty == ty::TyStr {
1199 } else if match_type(cx, self_ty, &paths::STRING) {
1207 STRING_EXTEND_CHARS,
1209 "calling `.extend(_.chars())`",
1212 "{}.push_str({}{})",
1213 snippet(cx, args[0].span, "_"),
1215 snippet(cx, target.span, "_")
1221 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1222 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
1223 if match_type(cx, obj_ty, &paths::STRING) {
1224 lint_string_extend(cx, expr, args);
1228 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1230 if let hir::ExprCall(ref fun, ref args) = new.node;
1232 if let hir::ExprPath(ref path) = fun.node;
1233 if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1234 if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1238 TEMPORARY_CSTRING_AS_PTR,
1240 "you are getting the inner pointer of a temporary `CString`",
1242 db.note("that pointer will be invalid outside this expression");
1243 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1249 fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1250 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1251 && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1255 ITER_CLONED_COLLECT,
1257 "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1263 fn lint_unnecessary_fold(cx: &LateContext, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1264 // Check that this is a call to Iterator::fold rather than just some function called fold
1265 if !match_trait_method(cx, expr, &paths::ITERATOR) {
1269 assert!(fold_args.len() == 3,
1270 "Expected fold_args to have three entries - the receiver, the initial value and the closure");
1272 fn check_fold_with_op(
1274 fold_args: &[hir::Expr],
1276 replacement_method_name: &str,
1277 replacement_has_args: bool) {
1280 // Extract the body of the closure passed to fold
1281 if let hir::ExprClosure(_, _, body_id, _, _) = fold_args[2].node;
1282 let closure_body = cx.tcx.hir.body(body_id);
1283 let closure_expr = remove_blocks(&closure_body.value);
1285 // Check if the closure body is of the form `acc <op> some_expr(x)`
1286 if let hir::ExprBinary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1287 if bin_op.node == op;
1289 // Extract the names of the two arguments to the closure
1290 if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1291 if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1293 if match_var(&*left_expr, first_arg_ident);
1294 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1297 // Span containing `.fold(...)`
1298 let next_point = cx.sess().codemap().next_point(fold_args[0].span);
1299 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1301 let sugg = if replacement_has_args {
1303 ".{replacement}(|{s}| {r})",
1304 replacement = replacement_method_name,
1305 s = second_arg_ident,
1306 r = snippet(cx, right_expr.span, "EXPR"),
1311 replacement = replacement_method_name,
1319 // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
1320 "this `.fold` can be written more succinctly using another method",
1328 // Check if the first argument to .fold is a suitable literal
1329 match fold_args[1].node {
1330 hir::ExprLit(ref lit) => {
1332 ast::LitKind::Bool(false) => check_fold_with_op(
1333 cx, fold_args, hir::BinOp_::BiOr, "any", true
1335 ast::LitKind::Bool(true) => check_fold_with_op(
1336 cx, fold_args, hir::BinOp_::BiAnd, "all", true
1338 ast::LitKind::Int(0, _) => check_fold_with_op(
1339 cx, fold_args, hir::BinOp_::BiAdd, "sum", false
1341 ast::LitKind::Int(1, _) => check_fold_with_op(
1342 cx, fold_args, hir::BinOp_::BiMul, "product", false
1351 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1352 let mut_str = if is_mut { "_mut" } else { "" };
1353 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1355 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1357 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1360 return; // caller is not a type that we want to lint
1368 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1375 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1376 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1377 // because they do not implement `IndexMut`
1378 let expr_ty = cx.tables.expr_ty(&get_args[0]);
1379 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1381 } else if match_type(cx, expr_ty, &paths::VEC) {
1383 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1385 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1387 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1390 return; // caller is not a type that we want to lint
1393 let mut_str = if is_mut { "_mut" } else { "" };
1394 let borrow_str = if is_mut { "&mut " } else { "&" };
1400 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1408 snippet(cx, get_args[0].span, "_"),
1409 snippet(cx, get_args[1].span, "_")
1414 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
1415 // lint if caller of skip is an Iterator
1416 if match_trait_method(cx, expr, &paths::ITERATOR) {
1421 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1426 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
1427 fn may_slice(cx: &LateContext, ty: Ty) -> bool {
1429 ty::TySlice(_) => true,
1430 ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1431 ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1432 ty::TyArray(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
1433 ty::TyRef(_, inner, _) => may_slice(cx, inner),
1438 if let hir::ExprMethodCall(ref path, _, ref args) = expr.node {
1439 if path.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1440 sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1446 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1447 ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1448 ty::TyRef(_, inner, _) => if may_slice(cx, inner) {
1449 sugg::Sugg::hir_opt(cx, expr)
1458 /// lint use of `unwrap()` for `Option`s and `Result`s
1459 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1460 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
1462 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1463 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1464 } else if match_type(cx, obj_ty, &paths::RESULT) {
1465 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1470 if let Some((lint, kind, none_value)) = mess {
1476 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1477 using expect() to provide a better panic \
1486 /// lint use of `ok().expect()` for `Result`s
1487 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1488 // lint if the caller of `ok()` is a `Result`
1489 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1490 let result_type = cx.tables.expr_ty(&ok_args[0]);
1491 if let Some(error_type) = get_error_type(cx, result_type) {
1492 if has_debug_impl(error_type, cx) {
1497 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1504 /// lint use of `map().unwrap_or()` for `Option`s
1505 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1506 // lint if the caller of `map()` is an `Option`
1507 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1508 // get snippets for args to map() and unwrap_or()
1509 let map_snippet = snippet(cx, map_args[1].span, "..");
1510 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1512 // comparing the snippet from source to raw text ("None") below is safe
1513 // because we already have checked the type.
1514 let arg = if unwrap_snippet == "None" {
1519 let suggest = if unwrap_snippet == "None" {
1525 "called `map(f).unwrap_or({})` on an Option value. \
1526 This can be done more directly by calling `{}` instead",
1530 // lint, with note if neither arg is > 1 line and both map() and
1531 // unwrap_or() have the same span
1532 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1533 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1534 if same_span && !multiline {
1535 let suggest = if unwrap_snippet == "None" {
1536 format!("and_then({})", map_snippet)
1538 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1541 "replace `map({}).unwrap_or({})` with `{}`",
1546 span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, ¬e);
1547 } else if same_span && multiline {
1548 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1553 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1554 fn lint_map_unwrap_or_else<'a, 'tcx>(
1555 cx: &LateContext<'a, 'tcx>,
1556 expr: &'tcx hir::Expr,
1557 map_args: &'tcx [hir::Expr],
1558 unwrap_args: &'tcx [hir::Expr],
1560 // lint if the caller of `map()` is an `Option`
1561 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1562 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1563 if is_option || is_result {
1565 let msg = if is_option {
1566 "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1567 `map_or_else(g, f)` instead"
1569 "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1570 `ok().map_or_else(g, f)` instead"
1572 // get snippets for args to map() and unwrap_or_else()
1573 let map_snippet = snippet(cx, map_args[1].span, "..");
1574 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1575 // lint, with note if neither arg is > 1 line and both map() and
1576 // unwrap_or_else() have the same span
1577 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1578 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1579 if same_span && !multiline {
1583 OPTION_MAP_UNWRAP_OR_ELSE
1585 RESULT_MAP_UNWRAP_OR_ELSE
1591 "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1594 if is_result { "ok()." } else { "" }
1597 } else if same_span && multiline {
1601 OPTION_MAP_UNWRAP_OR_ELSE
1603 RESULT_MAP_UNWRAP_OR_ELSE
1612 /// lint use of `_.map_or(None, _)` for `Option`s
1613 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1614 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1615 // check if the first non-self argument to map_or() is None
1616 let map_or_arg_is_none = if let hir::Expr_::ExprPath(ref qpath) = map_or_args[1].node {
1617 match_qpath(qpath, &paths::OPTION_NONE)
1622 if map_or_arg_is_none {
1624 let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1625 `and_then(f)` instead";
1626 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1627 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1628 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1629 span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1630 db.span_suggestion(expr.span, "try using and_then instead", hint);
1636 /// lint use of `filter().next()` for `Iterators`
1637 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1638 // lint if caller of `.filter().next()` is an Iterator
1639 if match_trait_method(cx, expr, &paths::ITERATOR) {
1640 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1641 `.find(p)` instead.";
1642 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1643 if filter_snippet.lines().count() <= 1 {
1644 // add note if not multi-line
1651 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1654 span_lint(cx, FILTER_NEXT, expr.span, msg);
1659 /// lint use of `filter().map()` for `Iterators`
1660 fn lint_filter_map<'a, 'tcx>(
1661 cx: &LateContext<'a, 'tcx>,
1662 expr: &'tcx hir::Expr,
1663 _filter_args: &'tcx [hir::Expr],
1664 _map_args: &'tcx [hir::Expr],
1666 // lint if caller of `.filter().map()` is an Iterator
1667 if match_trait_method(cx, expr, &paths::ITERATOR) {
1668 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1669 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1670 span_lint(cx, FILTER_MAP, expr.span, msg);
1674 /// lint use of `filter().map()` for `Iterators`
1675 fn lint_filter_map_map<'a, 'tcx>(
1676 cx: &LateContext<'a, 'tcx>,
1677 expr: &'tcx hir::Expr,
1678 _filter_args: &'tcx [hir::Expr],
1679 _map_args: &'tcx [hir::Expr],
1681 // lint if caller of `.filter().map()` is an Iterator
1682 if match_trait_method(cx, expr, &paths::ITERATOR) {
1683 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1684 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1685 span_lint(cx, FILTER_MAP, expr.span, msg);
1689 /// lint use of `filter().flat_map()` for `Iterators`
1690 fn lint_filter_flat_map<'a, 'tcx>(
1691 cx: &LateContext<'a, 'tcx>,
1692 expr: &'tcx hir::Expr,
1693 _filter_args: &'tcx [hir::Expr],
1694 _map_args: &'tcx [hir::Expr],
1696 // lint if caller of `.filter().flat_map()` is an Iterator
1697 if match_trait_method(cx, expr, &paths::ITERATOR) {
1698 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1699 This is more succinctly expressed by calling `.flat_map(..)` \
1700 and filtering by returning an empty Iterator.";
1701 span_lint(cx, FILTER_MAP, expr.span, msg);
1705 /// lint use of `filter_map().flat_map()` for `Iterators`
1706 fn lint_filter_map_flat_map<'a, 'tcx>(
1707 cx: &LateContext<'a, 'tcx>,
1708 expr: &'tcx hir::Expr,
1709 _filter_args: &'tcx [hir::Expr],
1710 _map_args: &'tcx [hir::Expr],
1712 // lint if caller of `.filter_map().flat_map()` is an Iterator
1713 if match_trait_method(cx, expr, &paths::ITERATOR) {
1714 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1715 This is more succinctly expressed by calling `.flat_map(..)` \
1716 and filtering by returning an empty Iterator.";
1717 span_lint(cx, FILTER_MAP, expr.span, msg);
1721 /// lint searching an Iterator followed by `is_some()`
1722 fn lint_search_is_some<'a, 'tcx>(
1723 cx: &LateContext<'a, 'tcx>,
1724 expr: &'tcx hir::Expr,
1725 search_method: &str,
1726 search_args: &'tcx [hir::Expr],
1727 is_some_args: &'tcx [hir::Expr],
1729 // lint if caller of search is an Iterator
1730 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1732 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1733 expressed by calling `any()`.",
1736 let search_snippet = snippet(cx, search_args[1].span, "..");
1737 if search_snippet.lines().count() <= 1 {
1738 // add note if not multi-line
1745 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1748 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1753 /// Used for `lint_binary_expr_with_method_call`.
1754 #[derive(Copy, Clone)]
1755 struct BinaryExprInfo<'a> {
1756 expr: &'a hir::Expr,
1757 chain: &'a hir::Expr,
1758 other: &'a hir::Expr,
1762 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1763 fn lint_binary_expr_with_method_call<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, info: &mut BinaryExprInfo) {
1764 macro_rules! lint_with_both_lhs_and_rhs {
1765 ($func:ident, $cx:expr, $info:ident) => {
1766 if !$func($cx, $info) {
1767 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1768 if $func($cx, $info) {
1775 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1776 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1777 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1778 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1781 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1782 fn lint_chars_cmp<'a, 'tcx>(
1783 cx: &LateContext<'a, 'tcx>,
1784 info: &BinaryExprInfo,
1785 chain_methods: &[&str],
1786 lint: &'static Lint,
1790 if let Some(args) = method_chain_args(info.chain, chain_methods);
1791 if let hir::ExprCall(ref fun, ref arg_char) = info.other.node;
1792 if arg_char.len() == 1;
1793 if let hir::ExprPath(ref qpath) = fun.node;
1794 if let Some(segment) = single_segment_path(qpath);
1795 if segment.name == "Some";
1797 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1799 if self_ty.sty != ty::TyStr {
1803 span_lint_and_sugg(cx,
1806 &format!("you should use the `{}` method", suggest),
1808 format!("{}{}.{}({})",
1809 if info.eq { "" } else { "!" },
1810 snippet(cx, args[0][0].span, "_"),
1812 snippet(cx, arg_char[0].span, "_")));
1821 /// Checks for the `CHARS_NEXT_CMP` lint.
1822 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1823 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1826 /// Checks for the `CHARS_LAST_CMP` lint.
1827 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1828 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1831 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1835 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1836 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1837 cx: &LateContext<'a, 'tcx>,
1838 info: &BinaryExprInfo,
1839 chain_methods: &[&str],
1840 lint: &'static Lint,
1844 if let Some(args) = method_chain_args(info.chain, chain_methods);
1845 if let hir::ExprLit(ref lit) = info.other.node;
1846 if let ast::LitKind::Char(c) = lit.node;
1852 &format!("you should use the `{}` method", suggest),
1854 format!("{}{}.{}('{}')",
1855 if info.eq { "" } else { "!" },
1856 snippet(cx, args[0][0].span, "_"),
1868 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
1869 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1870 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
1873 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
1874 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1875 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
1878 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
1882 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1883 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
1884 if let Some((Constant::Str(r), _)) = constant(cx, cx.tables, arg) {
1886 let c = r.chars().next().unwrap();
1887 let snip = snippet(cx, expr.span, "..");
1888 let hint = snip.replace(
1889 &format!("\"{}\"", c.escape_default()),
1890 &format!("'{}'", c.escape_default()));
1893 SINGLE_CHAR_PATTERN,
1895 "single-character string constant used as pattern",
1897 db.span_suggestion(expr.span, "try using a char instead", hint);
1904 /// Checks for the `USELESS_ASREF` lint.
1905 fn lint_asref(cx: &LateContext, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
1906 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
1907 // check if the call is to the actual `AsRef` or `AsMut` trait
1908 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
1909 // check if the type after `as_ref` or `as_mut` is the same as before
1910 let recvr = &as_ref_args[0];
1911 let rcv_ty = cx.tables.expr_ty(recvr);
1912 let res_ty = cx.tables.expr_ty(expr);
1913 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
1914 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
1915 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
1920 &format!("this call to `{}` does nothing", call_name),
1922 snippet(cx, recvr.span, "_").into_owned(),
1928 /// Given a `Result<T, E>` type, return its error type (`E`).
1929 fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
1930 if let ty::TyAdt(_, substs) = ty.sty {
1931 if match_type(cx, ty, &paths::RESULT) {
1932 substs.types().nth(1)
1941 /// This checks whether a given type is known to implement Debug.
1942 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1943 match cx.tcx.lang_items().debug_trait() {
1944 Some(debug) => implements_trait(cx, ty, debug, &[]),
1951 StartsWith(&'static str),
1954 #[cfg_attr(rustfmt, rustfmt_skip)]
1955 const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
1956 (Convention::Eq("new"), &[SelfKind::No]),
1957 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1958 (Convention::StartsWith("from_"), &[SelfKind::No]),
1959 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1960 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1961 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1964 #[cfg_attr(rustfmt, rustfmt_skip)]
1965 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
1966 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1967 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1968 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1969 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1970 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1971 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1972 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1973 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1974 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1975 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1976 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1977 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1978 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1979 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1980 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1981 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1982 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1983 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1984 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1985 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1986 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1987 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1988 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1989 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1990 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1991 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1992 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1993 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1994 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1995 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1998 #[cfg_attr(rustfmt, rustfmt_skip)]
1999 const PATTERN_METHODS: [(&str, usize); 17] = [
2007 ("split_terminator", 1),
2008 ("rsplit_terminator", 1),
2013 ("match_indices", 1),
2014 ("rmatch_indices", 1),
2015 ("trim_left_matches", 1),
2016 ("trim_right_matches", 1),
2020 #[derive(Clone, Copy, PartialEq, Debug)]
2034 allow_value_for_ref: bool,
2035 generics: &hir::Generics,
2037 // Self types in the HIR are desugared to explicit self types. So it will
2040 // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
2041 // the impl is on `Foo`)
2042 // Thus, we only need to test equality against the impl self type or if it is
2044 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
2045 // `Self`, `&mut Self`,
2046 // and `Box<Self>`, including the equivalent types with `Foo`.
2048 let is_actually_self = |ty| is_self_ty(ty) || ty == self_ty;
2051 SelfKind::Value => is_actually_self(ty),
2052 SelfKind::Ref | SelfKind::RefMut => {
2053 if allow_value_for_ref && is_actually_self(ty) {
2057 hir::TyRptr(_, ref mt_ty) => {
2058 let mutability_match = if self == SelfKind::Ref {
2059 mt_ty.mutbl == hir::MutImmutable
2061 mt_ty.mutbl == hir::MutMutable
2063 is_actually_self(&mt_ty.ty) && mutability_match
2072 SelfKind::Value => false,
2073 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
2074 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
2075 SelfKind::No => true,
2080 fn description(&self) -> &'static str {
2082 SelfKind::Value => "self by value",
2083 SelfKind::Ref => "self by reference",
2084 SelfKind::RefMut => "self by mutable reference",
2085 SelfKind::No => "no self",
2090 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
2091 single_segment_ty(ty).map_or(false, |seg| {
2092 generics.ty_params().any(|param| {
2093 param.name == seg.name && param.bounds.iter().any(|bound| {
2094 if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
2095 let path = &ptr.trait_ref.path;
2096 match_path(path, name) && path.segments.last().map_or(false, |s| {
2097 if let Some(ref params) = s.parameters {
2098 if params.parenthesized {
2101 params.types.len() == 1
2102 && (is_self_ty(¶ms.types[0]) || is_ty(&*params.types[0], self_ty))
2116 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
2117 match (&ty.node, &self_ty.node) {
2119 &hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
2120 &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path)),
2124 .map(|seg| seg.name)
2125 .eq(self_ty_path.segments.iter().map(|seg| seg.name)),
2130 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2131 if let hir::TyPath(ref path) = ty.node {
2132 single_segment_path(path)
2139 fn check(&self, other: &str) -> bool {
2141 Convention::Eq(this) => this == other,
2142 Convention::StartsWith(this) => other.starts_with(this) && this != other,
2147 impl fmt::Display for Convention {
2148 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2150 Convention::Eq(this) => this.fmt(f),
2151 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2156 #[derive(Clone, Copy)]
2165 fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
2167 (&OutType::Unit, &hir::DefaultReturn(_)) => true,
2168 (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
2169 (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2170 (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
2171 (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
2177 fn is_bool(ty: &hir::Ty) -> bool {
2178 if let hir::TyPath(ref p) = ty.node {
2179 match_qpath(p, &["bool"])