4 use rustc::{declare_lint, lint_array};
5 use rustc::ty::{self, Ty};
6 use rustc::hir::def::Def;
11 use syntax::codemap::{Span, BytePos};
12 use crate::utils::{get_arg_name, get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_expn_of, is_self,
13 is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
14 match_type, method_chain_args, match_var, return_ty, remove_blocks, same_tys, single_segment_path, snippet,
15 span_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq};
16 use crate::utils::paths;
17 use crate::utils::sugg;
18 use crate::consts::{constant, Constant};
23 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
25 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
26 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
27 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
28 /// `Allow` by default.
30 /// **Known problems:** None.
36 declare_clippy_lint! {
37 pub OPTION_UNWRAP_USED,
39 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
42 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
44 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
45 /// values. Normally, you want to implement more sophisticated error handling,
46 /// and propagate errors upwards with `try!`.
48 /// Even if you want to panic on errors, not all `Error`s implement good
49 /// messages on display. Therefore it may be beneficial to look at the places
50 /// where they may get displayed. Activate this lint to do just that.
52 /// **Known problems:** None.
58 declare_clippy_lint! {
59 pub RESULT_UNWRAP_USED,
61 "using `Result.unwrap()`, which might be better handled"
64 /// **What it does:** Checks for methods that should live in a trait
65 /// implementation of a `std` trait (see [llogiq's blog
66 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
67 /// information) instead of an inherent implementation.
69 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
70 /// the code, often with very little cost. Also people seeing a `mul(...)`
72 /// may expect `*` to work equally, so you should have good reason to disappoint
75 /// **Known problems:** None.
81 /// fn add(&self, other: &X) -> X { .. }
84 declare_clippy_lint! {
85 pub SHOULD_IMPLEMENT_TRAIT,
87 "defining a method that should be implementing a std trait"
90 /// **What it does:** Checks for methods with certain name prefixes and which
91 /// doesn't match how self is taken. The actual rules are:
93 /// |Prefix |`self` taken |
94 /// |-------|----------------------|
95 /// |`as_` |`&self` or `&mut self`|
98 /// |`is_` |`&self` or none |
101 /// **Why is this bad?** Consistency breeds readability. If you follow the
102 /// conventions, your users won't be surprised that they, e.g., need to supply a
103 /// mutable reference to a `as_..` function.
105 /// **Known problems:** None.
110 /// fn as_str(self) -> &str { .. }
113 declare_clippy_lint! {
114 pub WRONG_SELF_CONVENTION,
116 "defining a method named with an established prefix (like \"into_\") that takes \
117 `self` with the wrong convention"
120 /// **What it does:** This is the same as
121 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
123 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
125 /// **Known problems:** Actually *renaming* the function may break clients if
126 /// the function is part of the public interface. In that case, be mindful of
127 /// the stability guarantees you've given your users.
132 /// pub fn as_str(self) -> &str { .. }
135 declare_clippy_lint! {
136 pub WRONG_PUB_SELF_CONVENTION,
138 "defining a public method named with an established prefix (like \"into_\") that takes \
139 `self` with the wrong convention"
142 /// **What it does:** Checks for usage of `ok().expect(..)`.
144 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
145 /// directly to get a better error message.
147 /// **Known problems:** The error type needs to implement `Debug`
151 /// x.ok().expect("why did I do this again?")
153 declare_clippy_lint! {
156 "using `ok().expect()`, which gives worse error messages than \
157 calling `expect` directly on the Result"
160 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
162 /// **Why is this bad?** Readability, this can be written more concisely as
163 /// `_.map_or(_, _)`.
165 /// **Known problems:** The order of the arguments is not in execution order
169 /// x.map(|a| a + 1).unwrap_or(0)
171 declare_clippy_lint! {
172 pub OPTION_MAP_UNWRAP_OR,
174 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
178 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
180 /// **Why is this bad?** Readability, this can be written more concisely as
181 /// `_.map_or_else(_, _)`.
183 /// **Known problems:** The order of the arguments is not in execution order.
187 /// x.map(|a| a + 1).unwrap_or_else(some_function)
189 declare_clippy_lint! {
190 pub OPTION_MAP_UNWRAP_OR_ELSE,
192 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
196 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
198 /// **Why is this bad?** Readability, this can be written more concisely as
199 /// `result.ok().map_or_else(_, _)`.
201 /// **Known problems:** None.
205 /// x.map(|a| a + 1).unwrap_or_else(some_function)
207 declare_clippy_lint! {
208 pub RESULT_MAP_UNWRAP_OR_ELSE,
210 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
211 `.ok().map_or_else(g, f)`"
214 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
216 /// **Why is this bad?** Readability, this can be written more concisely as
219 /// **Known problems:** The order of the arguments is not in execution order.
223 /// opt.map_or(None, |a| a + 1)
225 declare_clippy_lint! {
226 pub OPTION_MAP_OR_NONE,
228 "using `Option.map_or(None, f)`, which is more succinctly expressed as \
232 /// **What it does:** Checks for usage of `_.filter(_).next()`.
234 /// **Why is this bad?** Readability, this can be written more concisely as
237 /// **Known problems:** None.
241 /// iter.filter(|x| x == 0).next()
243 declare_clippy_lint! {
246 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
249 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
250 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
252 /// **Why is this bad?** Readability, this can be written more concisely as a
253 /// single method call.
255 /// **Known problems:** Often requires a condition + Option/Iterator creation
256 /// inside the closure.
260 /// iter.filter(|x| x == 0).map(|x| x * 2)
262 declare_clippy_lint! {
265 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
266 usually be written as a single method call"
269 /// **What it does:** Checks for an iterator search (such as `find()`,
270 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
272 /// **Why is this bad?** Readability, this can be written more concisely as
275 /// **Known problems:** None.
279 /// iter.find(|x| x == 0).is_some()
281 declare_clippy_lint! {
284 "using an iterator search followed by `is_some()`, which is more succinctly \
285 expressed as a call to `any()`"
288 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
289 /// if it starts with a given char.
291 /// **Why is this bad?** Readability, this can be written more concisely as
292 /// `_.starts_with(_)`.
294 /// **Known problems:** None.
298 /// name.chars().next() == Some('_')
300 declare_clippy_lint! {
303 "using `.chars().next()` to check if a string starts with a char"
306 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
307 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
308 /// `unwrap_or_default` instead.
310 /// **Why is this bad?** The function will always be called and potentially
311 /// allocate an object acting as the default.
313 /// **Known problems:** If the function has side-effects, not calling it will
314 /// change the semantic of the program, but you shouldn't rely on that anyway.
318 /// foo.unwrap_or(String::new())
320 /// this can instead be written:
322 /// foo.unwrap_or_else(String::new)
326 /// foo.unwrap_or_default()
328 declare_clippy_lint! {
331 "using any `*or` method with a function call, which suggests `*or_else`"
334 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
335 /// etc., and suggests to use `unwrap_or_else` instead
337 /// **Why is this bad?** The function will always be called.
339 /// **Known problems:** If the function has side-effects, not calling it will
340 /// change the semantic of the program, but you shouldn't rely on that anyway.
344 /// foo.expect(&format("Err {}: {}", err_code, err_msg))
348 /// foo.expect(format("Err {}: {}", err_code, err_msg).as_str())
350 /// this can instead be written:
352 /// foo.unwrap_or_else(|_| panic!("Err {}: {}", err_code, err_msg))
356 /// foo.unwrap_or_else(|_| panic!(format("Err {}: {}", err_code, err_msg).as_str()))
358 declare_clippy_lint! {
361 "using any `expect` method with a function call"
364 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
366 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
367 /// generics, not for using the `clone` method on a concrete type.
369 /// **Known problems:** None.
375 declare_clippy_lint! {
378 "using `clone` on a `Copy` type"
381 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
382 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
383 /// function syntax instead (e.g. `Rc::clone(foo)`).
385 /// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
386 /// can obscure the fact that only the pointer is being cloned, not the underlying
393 declare_clippy_lint! {
394 pub CLONE_ON_REF_PTR,
396 "using 'clone' on a ref-counted pointer"
399 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
401 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
402 /// cloning the underlying `T`.
404 /// **Known problems:** None.
411 /// let z = y.clone();
412 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
415 declare_clippy_lint! {
416 pub CLONE_DOUBLE_REF,
418 "using `clone` on `&&T`"
421 /// **What it does:** Checks for `new` not returning `Self`.
423 /// **Why is this bad?** As a convention, `new` methods are used to make a new
424 /// instance of a type.
426 /// **Known problems:** None.
431 /// fn new(..) -> NotAFoo {
435 declare_clippy_lint! {
438 "not returning `Self` in a `new` method"
441 /// **What it does:** Checks for string methods that receive a single-character
442 /// `str` as an argument, e.g. `_.split("x")`.
444 /// **Why is this bad?** Performing these methods using a `char` is faster than
447 /// **Known problems:** Does not catch multi-byte unicode characters.
450 /// `_.split("x")` could be `_.split('x')
451 declare_clippy_lint! {
452 pub SINGLE_CHAR_PATTERN,
454 "using a single-character str where a char could be used, e.g. \
458 /// **What it does:** Checks for getting the inner pointer of a temporary
461 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
462 /// as the `CString` is alive.
464 /// **Known problems:** None.
468 /// let c_str = CString::new("foo").unwrap().as_ptr();
470 /// call_some_ffi_func(c_str);
473 /// Here `c_str` point to a freed address. The correct use would be:
475 /// let c_str = CString::new("foo").unwrap();
477 /// call_some_ffi_func(c_str.as_ptr());
480 declare_clippy_lint! {
481 pub TEMPORARY_CSTRING_AS_PTR,
483 "getting the inner pointer of a temporary `CString`"
486 /// **What it does:** Checks for use of `.iter().nth()` (and the related
487 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
489 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
492 /// **Known problems:** None.
496 /// let some_vec = vec![0, 1, 2, 3];
497 /// let bad_vec = some_vec.iter().nth(3);
498 /// let bad_slice = &some_vec[..].iter().nth(3);
500 /// The correct use would be:
502 /// let some_vec = vec![0, 1, 2, 3];
503 /// let bad_vec = some_vec.get(3);
504 /// let bad_slice = &some_vec[..].get(3);
506 declare_clippy_lint! {
509 "using `.iter().nth()` on a standard library type with O(1) element access"
512 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
514 /// **Why is this bad?** `.nth(x)` is cleaner
516 /// **Known problems:** None.
520 /// let some_vec = vec![0, 1, 2, 3];
521 /// let bad_vec = some_vec.iter().skip(3).next();
522 /// let bad_slice = &some_vec[..].iter().skip(3).next();
524 /// The correct use would be:
526 /// let some_vec = vec![0, 1, 2, 3];
527 /// let bad_vec = some_vec.iter().nth(3);
528 /// let bad_slice = &some_vec[..].iter().nth(3);
530 declare_clippy_lint! {
533 "using `.skip(x).next()` on an iterator"
536 /// **What it does:** Checks for use of `.get().unwrap()` (or
537 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
539 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
542 /// **Known problems:** None.
546 /// let some_vec = vec![0, 1, 2, 3];
547 /// let last = some_vec.get(3).unwrap();
548 /// *some_vec.get_mut(0).unwrap() = 1;
550 /// The correct use would be:
552 /// let some_vec = vec![0, 1, 2, 3];
553 /// let last = some_vec[3];
556 declare_clippy_lint! {
559 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
562 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
563 /// `&str` or `String`.
565 /// **Why is this bad?** `.push_str(s)` is clearer
567 /// **Known problems:** None.
572 /// let def = String::from("def");
573 /// let mut s = String::new();
574 /// s.extend(abc.chars());
575 /// s.extend(def.chars());
577 /// The correct use would be:
580 /// let def = String::from("def");
581 /// let mut s = String::new();
583 /// s.push_str(&def));
585 declare_clippy_lint! {
586 pub STRING_EXTEND_CHARS,
588 "using `x.extend(s.chars())` where s is a `&str` or `String`"
591 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
594 /// **Why is this bad?** `.to_vec()` is clearer
596 /// **Known problems:** None.
600 /// let s = [1,2,3,4,5];
601 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
603 /// The better use would be:
605 /// let s = [1,2,3,4,5];
606 /// let s2 : Vec<isize> = s.to_vec();
608 declare_clippy_lint! {
609 pub ITER_CLONED_COLLECT,
611 "using `.cloned().collect()` on slice to create a `Vec`"
614 /// **What it does:** Checks for usage of `.chars().last()` or
615 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
617 /// **Why is this bad?** Readability, this can be written more concisely as
618 /// `_.ends_with(_)`.
620 /// **Known problems:** None.
624 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
626 declare_clippy_lint! {
629 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
632 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
633 /// types before and after the call are the same.
635 /// **Why is this bad?** The call is unnecessary.
637 /// **Known problems:** None.
641 /// let x: &[i32] = &[1,2,3,4,5];
642 /// do_stuff(x.as_ref());
644 /// The correct use would be:
646 /// let x: &[i32] = &[1,2,3,4,5];
649 declare_clippy_lint! {
652 "using `as_ref` where the types before and after the call are the same"
656 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
657 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
658 /// `sum` or `product`.
660 /// **Why is this bad?** Readability.
662 /// **Known problems:** None.
666 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
668 /// This could be written as:
670 /// let _ = (0..3).any(|x| x > 2);
672 declare_clippy_lint! {
673 pub UNNECESSARY_FOLD,
675 "using `fold` when a more succinct alternative exists"
678 impl LintPass for Pass {
679 fn get_lints(&self) -> LintArray {
683 SHOULD_IMPLEMENT_TRAIT,
684 WRONG_SELF_CONVENTION,
685 WRONG_PUB_SELF_CONVENTION,
687 OPTION_MAP_UNWRAP_OR,
688 OPTION_MAP_UNWRAP_OR_ELSE,
689 RESULT_MAP_UNWRAP_OR_ELSE,
701 TEMPORARY_CSTRING_AS_PTR,
715 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
716 #[allow(cyclomatic_complexity)]
717 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
718 if in_macro(expr.span) {
723 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
725 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
726 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
727 lint_get_unwrap(cx, expr, arglists[0], false);
728 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
729 lint_get_unwrap(cx, expr, arglists[0], true);
730 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
731 lint_unwrap(cx, expr, arglists[0]);
732 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
733 lint_ok_expect(cx, expr, arglists[0]);
734 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
735 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
736 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
737 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
738 } else if let Some(arglists) = method_chain_args(expr, &["map_or"]) {
739 lint_map_or_none(cx, expr, arglists[0]);
740 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
741 lint_filter_next(cx, expr, arglists[0]);
742 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
743 lint_filter_map(cx, expr, arglists[0], arglists[1]);
744 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
745 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
746 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
747 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
748 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
749 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
750 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
751 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
752 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
753 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
754 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
755 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
756 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
757 lint_extend(cx, expr, arglists[0]);
758 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
759 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
760 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
761 lint_iter_nth(cx, expr, arglists[0], false);
762 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
763 lint_iter_nth(cx, expr, arglists[0], true);
764 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
765 lint_iter_skip_next(cx, expr);
766 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
767 lint_iter_cloned_collect(cx, expr, arglists[0]);
768 } else if let Some(arglists) = method_chain_args(expr, &["as_ref"]) {
769 lint_asref(cx, expr, "as_ref", arglists[0]);
770 } else if let Some(arglists) = method_chain_args(expr, &["as_mut"]) {
771 lint_asref(cx, expr, "as_mut", arglists[0]);
772 } else if let Some(arglists) = method_chain_args(expr, &["fold"]) {
773 lint_unnecessary_fold(cx, expr, arglists[0]);
776 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
777 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
779 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
780 if args.len() == 1 && method_call.ident.name == "clone" {
781 lint_clone_on_copy(cx, expr, &args[0], self_ty);
782 lint_clone_on_ref_ptr(cx, expr, &args[0]);
786 ty::TyRef(_, ty, _) if ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
787 if method_call.ident.name == method && args.len() > pos {
788 lint_single_char_pattern(cx, expr, &args[pos]);
794 hir::ExprKind::Binary(op, ref lhs, ref rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
795 let mut info = BinaryExprInfo {
799 eq: op.node == hir::BinOpKind::Eq,
801 lint_binary_expr_with_method_call(cx, &mut info);
807 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
808 if in_external_macro(cx, implitem.span) {
811 let name = implitem.ident.name;
812 let parent = cx.tcx.hir.get_parent(implitem.id);
813 let item = cx.tcx.hir.expect_item(parent);
815 if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
816 if let Some(first_arg_ty) = sig.decl.inputs.get(0);
817 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
818 if let hir::ItemKind::Impl(_, _, _, _, None, ref self_ty, _) = item.node;
820 if cx.access_levels.is_exported(implitem.id) {
821 // check missing trait implementations
822 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
823 if name == method_name &&
824 sig.decl.inputs.len() == n_args &&
825 out_type.matches(cx, &sig.decl.output) &&
826 self_kind.matches(cx, first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
827 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
828 "defining a method called `{}` on this type; consider implementing \
829 the `{}` trait or choosing a less ambiguous name", name, trait_name));
834 // check conventions w.r.t. conversion method names and predicates
835 let def_id = cx.tcx.hir.local_def_id(item.id);
836 let ty = cx.tcx.type_of(def_id);
837 let is_copy = is_copy(cx, ty);
838 for &(ref conv, self_kinds) in &CONVENTIONS {
840 if conv.check(&name.as_str());
843 .any(|k| k.matches(cx, first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
845 let lint = if item.vis.node.is_pub() {
846 WRONG_PUB_SELF_CONVENTION
848 WRONG_SELF_CONVENTION
853 &format!("methods called `{}` usually take {}; consider choosing a less \
857 .map(|k| k.description())
864 let ret_ty = return_ty(cx, implitem.id);
866 !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
870 "methods called `new` usually return `Self`");
877 /// Checks for the `OR_FUN_CALL` lint.
878 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
879 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
880 fn check_unwrap_or_default(
884 self_expr: &hir::Expr,
893 if name == "unwrap_or" {
894 if let hir::ExprKind::Path(ref qpath) = fun.node {
895 let path = &*last_path_segment(qpath).ident.as_str();
897 if ["default", "new"].contains(&path) {
898 let arg_ty = cx.tables.expr_ty(arg);
899 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
905 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
910 &format!("use of `{}` followed by a call to `{}`", name, path),
912 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
923 /// Check for `*or(foo())`.
924 #[allow(too_many_arguments)]
925 fn check_general_case(
930 self_expr: &hir::Expr,
935 // (path, fn_has_argument, methods, suffix)
936 let know_types: &[(&[_], _, &[_], _)] = &[
937 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
938 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
939 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
940 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
943 // early check if the name is one we care about
944 if know_types.iter().all(|k| !k.2.contains(&name)) {
948 // don't lint for constant values
949 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
950 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
955 let self_ty = cx.tables.expr_ty(self_expr);
957 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
958 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
960 (fn_has_arguments, poss, suffix)
965 if !poss.contains(&name) {
969 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
970 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
971 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
972 (false, true) => snippet(cx, fun_span, ".."),
974 let span_replace_word = method_span.with_hi(span.hi());
979 &format!("use of `{}` followed by a function call", name),
981 format!("{}_{}({})", name, suffix, sugg),
987 hir::ExprKind::Call(ref fun, ref or_args) => {
988 let or_has_args = !or_args.is_empty();
989 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
990 check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
993 hir::ExprKind::MethodCall(_, span, ref or_args) => {
994 check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
1001 /// Checks for the `EXPECT_FUN_CALL` lint.
1002 fn lint_expect_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
1003 fn extract_format_args(arg: &hir::Expr) -> Option<&hir::HirVec<hir::Expr>> {
1004 if let hir::ExprKind::AddrOf(_, ref addr_of) = arg.node {
1005 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = addr_of.node {
1006 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1 {
1007 if let hir::ExprKind::Call(_, ref format_args) = inner_args[0].node {
1008 return Some(format_args);
1017 fn generate_format_arg_snippet(cx: &LateContext, a: &hir::Expr) -> String {
1018 if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
1019 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
1020 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
1021 return snippet(cx, format_arg_expr_tup[0].span, "..").into_owned();
1026 snippet(cx, a.span, "..").into_owned()
1029 fn check_general_case(
1033 self_expr: &hir::Expr,
1037 if name != "expect" {
1041 let self_type = cx.tables.expr_ty(self_expr);
1042 let known_types = &[&paths::OPTION, &paths::RESULT];
1044 // if not a known type, return early
1045 if known_types.iter().all(|&k| !match_type(cx, self_type, k)) {
1049 // don't lint for constant values
1050 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
1051 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
1056 let closure = if match_type(cx, self_type, &paths::OPTION) { "||" } else { "|_|" };
1057 let span_replace_word = method_span.with_hi(span.hi());
1059 if let Some(format_args) = extract_format_args(arg) {
1060 let args_len = format_args.len();
1061 let args: Vec<String> = format_args
1064 .map(|a| generate_format_arg_snippet(cx, a))
1067 let sugg = args.join(", ");
1073 &format!("use of `{}` followed by a function call", name),
1075 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1081 let sugg: Cow<_> = snippet(cx, arg.span, "..");
1087 &format!("use of `{}` followed by a function call", name),
1089 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1093 if args.len() == 2 {
1094 match args[1].node {
1095 hir::ExprKind::Lit(_) => {},
1096 _ => check_general_case(cx, name, method_span, &args[0], &args[1], expr.span),
1101 /// Checks for the `CLONE_ON_COPY` lint.
1102 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
1103 let ty = cx.tables.expr_ty(expr);
1104 if let ty::TyRef(_, inner, _) = arg_ty.sty {
1105 if let ty::TyRef(_, innermost, _) = inner.sty {
1110 "using `clone` on a double-reference; \
1111 this will copy the reference instead of cloning the inner type",
1112 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1113 let mut ty = innermost;
1115 while let ty::TyRef(_, inner, _) = ty.sty {
1119 let refs: String = iter::repeat('&').take(n + 1).collect();
1120 let derefs: String = iter::repeat('*').take(n).collect();
1121 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1122 db.span_suggestion(expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()));
1123 db.span_suggestion(expr.span, "or try being explicit about what type to clone", explicit);
1126 return; // don't report clone_on_copy
1130 if is_copy(cx, ty) {
1132 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1133 if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
1134 let parent = cx.tcx.hir.get_parent_node(expr.id);
1135 match cx.tcx.hir.get(parent) {
1136 hir::map::NodeExpr(parent) => match parent.node {
1137 // &*x is a nop, &x.clone() is not
1138 hir::ExprKind::AddrOf(..) |
1139 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1140 hir::ExprKind::MethodCall(..) => return,
1143 hir::map::NodeStmt(stmt) => {
1144 if let hir::StmtKind::Decl(ref decl, _) = stmt.node {
1145 if let hir::DeclKind::Local(ref loc) = decl.node {
1146 if let hir::PatKind::Ref(..) = loc.pat.node {
1147 // let ref y = *x borrows x, let ref y = x.clone() does not
1155 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
1157 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1162 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1163 if let Some((text, snip)) = snip {
1164 db.span_suggestion(expr.span, text, snip);
1170 fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1171 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1173 if let ty::TyAdt(_, subst) = obj_ty.sty {
1174 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1176 } else if match_type(cx, obj_ty, &paths::ARC) {
1178 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1188 "using '.clone()' on a ref-counted pointer",
1190 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1196 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1198 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1199 let target = &arglists[0][0];
1200 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1201 let ref_str = if self_ty.sty == ty::TyStr {
1203 } else if match_type(cx, self_ty, &paths::STRING) {
1211 STRING_EXTEND_CHARS,
1213 "calling `.extend(_.chars())`",
1216 "{}.push_str({}{})",
1217 snippet(cx, args[0].span, "_"),
1219 snippet(cx, target.span, "_")
1225 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1226 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
1227 if match_type(cx, obj_ty, &paths::STRING) {
1228 lint_string_extend(cx, expr, args);
1232 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1234 if let hir::ExprKind::Call(ref fun, ref args) = new.node;
1236 if let hir::ExprKind::Path(ref path) = fun.node;
1237 if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1238 if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1242 TEMPORARY_CSTRING_AS_PTR,
1244 "you are getting the inner pointer of a temporary `CString`",
1246 db.note("that pointer will be invalid outside this expression");
1247 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1253 fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1254 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1255 && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1259 ITER_CLONED_COLLECT,
1261 "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1267 fn lint_unnecessary_fold(cx: &LateContext, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1268 // Check that this is a call to Iterator::fold rather than just some function called fold
1269 if !match_trait_method(cx, expr, &paths::ITERATOR) {
1273 assert!(fold_args.len() == 3,
1274 "Expected fold_args to have three entries - the receiver, the initial value and the closure");
1276 fn check_fold_with_op(
1278 fold_args: &[hir::Expr],
1280 replacement_method_name: &str,
1281 replacement_has_args: bool) {
1284 // Extract the body of the closure passed to fold
1285 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].node;
1286 let closure_body = cx.tcx.hir.body(body_id);
1287 let closure_expr = remove_blocks(&closure_body.value);
1289 // Check if the closure body is of the form `acc <op> some_expr(x)`
1290 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1291 if bin_op.node == op;
1293 // Extract the names of the two arguments to the closure
1294 if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1295 if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1297 if match_var(&*left_expr, first_arg_ident);
1298 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1301 // Span containing `.fold(...)`
1302 let next_point = cx.sess().codemap().next_point(fold_args[0].span);
1303 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1305 let sugg = if replacement_has_args {
1307 ".{replacement}(|{s}| {r})",
1308 replacement = replacement_method_name,
1309 s = second_arg_ident,
1310 r = snippet(cx, right_expr.span, "EXPR"),
1315 replacement = replacement_method_name,
1323 // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
1324 "this `.fold` can be written more succinctly using another method",
1332 // Check if the first argument to .fold is a suitable literal
1333 match fold_args[1].node {
1334 hir::ExprKind::Lit(ref lit) => {
1336 ast::LitKind::Bool(false) => check_fold_with_op(
1337 cx, fold_args, hir::BinOpKind::Or, "any", true
1339 ast::LitKind::Bool(true) => check_fold_with_op(
1340 cx, fold_args, hir::BinOpKind::And, "all", true
1342 ast::LitKind::Int(0, _) => check_fold_with_op(
1343 cx, fold_args, hir::BinOpKind::Add, "sum", false
1345 ast::LitKind::Int(1, _) => check_fold_with_op(
1346 cx, fold_args, hir::BinOpKind::Mul, "product", false
1355 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1356 let mut_str = if is_mut { "_mut" } else { "" };
1357 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1359 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1361 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1364 return; // caller is not a type that we want to lint
1372 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1379 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1380 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1381 // because they do not implement `IndexMut`
1382 let expr_ty = cx.tables.expr_ty(&get_args[0]);
1383 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1385 } else if match_type(cx, expr_ty, &paths::VEC) {
1387 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1389 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1391 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1394 return; // caller is not a type that we want to lint
1397 let mut_str = if is_mut { "_mut" } else { "" };
1398 let borrow_str = if is_mut { "&mut " } else { "&" };
1404 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1412 snippet(cx, get_args[0].span, "_"),
1413 snippet(cx, get_args[1].span, "_")
1418 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
1419 // lint if caller of skip is an Iterator
1420 if match_trait_method(cx, expr, &paths::ITERATOR) {
1425 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1430 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
1431 fn may_slice(cx: &LateContext, ty: Ty) -> bool {
1433 ty::TySlice(_) => true,
1434 ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1435 ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1436 ty::TyArray(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
1437 ty::TyRef(_, inner, _) => may_slice(cx, inner),
1442 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.node {
1443 if path.ident.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1444 sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1450 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1451 ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1452 ty::TyRef(_, inner, _) => if may_slice(cx, inner) {
1453 sugg::Sugg::hir_opt(cx, expr)
1462 /// lint use of `unwrap()` for `Option`s and `Result`s
1463 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1464 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
1466 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1467 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1468 } else if match_type(cx, obj_ty, &paths::RESULT) {
1469 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1474 if let Some((lint, kind, none_value)) = mess {
1480 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1481 using expect() to provide a better panic \
1490 /// lint use of `ok().expect()` for `Result`s
1491 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1492 // lint if the caller of `ok()` is a `Result`
1493 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1494 let result_type = cx.tables.expr_ty(&ok_args[0]);
1495 if let Some(error_type) = get_error_type(cx, result_type) {
1496 if has_debug_impl(error_type, cx) {
1501 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1508 /// lint use of `map().unwrap_or()` for `Option`s
1509 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1510 // lint if the caller of `map()` is an `Option`
1511 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1512 // get snippets for args to map() and unwrap_or()
1513 let map_snippet = snippet(cx, map_args[1].span, "..");
1514 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1516 // comparing the snippet from source to raw text ("None") below is safe
1517 // because we already have checked the type.
1518 let arg = if unwrap_snippet == "None" {
1523 let suggest = if unwrap_snippet == "None" {
1529 "called `map(f).unwrap_or({})` on an Option value. \
1530 This can be done more directly by calling `{}` instead",
1534 // lint, with note if neither arg is > 1 line and both map() and
1535 // unwrap_or() have the same span
1536 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1537 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1538 if same_span && !multiline {
1539 let suggest = if unwrap_snippet == "None" {
1540 format!("and_then({})", map_snippet)
1542 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1545 "replace `map({}).unwrap_or({})` with `{}`",
1550 span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, ¬e);
1551 } else if same_span && multiline {
1552 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1557 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1558 fn lint_map_unwrap_or_else<'a, 'tcx>(
1559 cx: &LateContext<'a, 'tcx>,
1560 expr: &'tcx hir::Expr,
1561 map_args: &'tcx [hir::Expr],
1562 unwrap_args: &'tcx [hir::Expr],
1564 // lint if the caller of `map()` is an `Option`
1565 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1566 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1567 if is_option || is_result {
1569 let msg = if is_option {
1570 "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1571 `map_or_else(g, f)` instead"
1573 "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1574 `ok().map_or_else(g, f)` instead"
1576 // get snippets for args to map() and unwrap_or_else()
1577 let map_snippet = snippet(cx, map_args[1].span, "..");
1578 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1579 // lint, with note if neither arg is > 1 line and both map() and
1580 // unwrap_or_else() have the same span
1581 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1582 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1583 if same_span && !multiline {
1587 OPTION_MAP_UNWRAP_OR_ELSE
1589 RESULT_MAP_UNWRAP_OR_ELSE
1595 "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1598 if is_result { "ok()." } else { "" }
1601 } else if same_span && multiline {
1605 OPTION_MAP_UNWRAP_OR_ELSE
1607 RESULT_MAP_UNWRAP_OR_ELSE
1616 /// lint use of `_.map_or(None, _)` for `Option`s
1617 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1618 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1619 // check if the first non-self argument to map_or() is None
1620 let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].node {
1621 match_qpath(qpath, &paths::OPTION_NONE)
1626 if map_or_arg_is_none {
1628 let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1629 `and_then(f)` instead";
1630 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1631 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1632 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1633 span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1634 db.span_suggestion(expr.span, "try using and_then instead", hint);
1640 /// lint use of `filter().next()` for `Iterators`
1641 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1642 // lint if caller of `.filter().next()` is an Iterator
1643 if match_trait_method(cx, expr, &paths::ITERATOR) {
1644 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1645 `.find(p)` instead.";
1646 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1647 if filter_snippet.lines().count() <= 1 {
1648 // add note if not multi-line
1655 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1658 span_lint(cx, FILTER_NEXT, expr.span, msg);
1663 /// lint use of `filter().map()` for `Iterators`
1664 fn lint_filter_map<'a, 'tcx>(
1665 cx: &LateContext<'a, 'tcx>,
1666 expr: &'tcx hir::Expr,
1667 _filter_args: &'tcx [hir::Expr],
1668 _map_args: &'tcx [hir::Expr],
1670 // lint if caller of `.filter().map()` is an Iterator
1671 if match_trait_method(cx, expr, &paths::ITERATOR) {
1672 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1673 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1674 span_lint(cx, FILTER_MAP, expr.span, msg);
1678 /// lint use of `filter().map()` for `Iterators`
1679 fn lint_filter_map_map<'a, 'tcx>(
1680 cx: &LateContext<'a, 'tcx>,
1681 expr: &'tcx hir::Expr,
1682 _filter_args: &'tcx [hir::Expr],
1683 _map_args: &'tcx [hir::Expr],
1685 // lint if caller of `.filter().map()` is an Iterator
1686 if match_trait_method(cx, expr, &paths::ITERATOR) {
1687 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1688 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1689 span_lint(cx, FILTER_MAP, expr.span, msg);
1693 /// lint use of `filter().flat_map()` for `Iterators`
1694 fn lint_filter_flat_map<'a, 'tcx>(
1695 cx: &LateContext<'a, 'tcx>,
1696 expr: &'tcx hir::Expr,
1697 _filter_args: &'tcx [hir::Expr],
1698 _map_args: &'tcx [hir::Expr],
1700 // lint if caller of `.filter().flat_map()` is an Iterator
1701 if match_trait_method(cx, expr, &paths::ITERATOR) {
1702 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1703 This is more succinctly expressed by calling `.flat_map(..)` \
1704 and filtering by returning an empty Iterator.";
1705 span_lint(cx, FILTER_MAP, expr.span, msg);
1709 /// lint use of `filter_map().flat_map()` for `Iterators`
1710 fn lint_filter_map_flat_map<'a, 'tcx>(
1711 cx: &LateContext<'a, 'tcx>,
1712 expr: &'tcx hir::Expr,
1713 _filter_args: &'tcx [hir::Expr],
1714 _map_args: &'tcx [hir::Expr],
1716 // lint if caller of `.filter_map().flat_map()` is an Iterator
1717 if match_trait_method(cx, expr, &paths::ITERATOR) {
1718 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1719 This is more succinctly expressed by calling `.flat_map(..)` \
1720 and filtering by returning an empty Iterator.";
1721 span_lint(cx, FILTER_MAP, expr.span, msg);
1725 /// lint searching an Iterator followed by `is_some()`
1726 fn lint_search_is_some<'a, 'tcx>(
1727 cx: &LateContext<'a, 'tcx>,
1728 expr: &'tcx hir::Expr,
1729 search_method: &str,
1730 search_args: &'tcx [hir::Expr],
1731 is_some_args: &'tcx [hir::Expr],
1733 // lint if caller of search is an Iterator
1734 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1736 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1737 expressed by calling `any()`.",
1740 let search_snippet = snippet(cx, search_args[1].span, "..");
1741 if search_snippet.lines().count() <= 1 {
1742 // add note if not multi-line
1749 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1752 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1757 /// Used for `lint_binary_expr_with_method_call`.
1758 #[derive(Copy, Clone)]
1759 struct BinaryExprInfo<'a> {
1760 expr: &'a hir::Expr,
1761 chain: &'a hir::Expr,
1762 other: &'a hir::Expr,
1766 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1767 fn lint_binary_expr_with_method_call<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, info: &mut BinaryExprInfo) {
1768 macro_rules! lint_with_both_lhs_and_rhs {
1769 ($func:ident, $cx:expr, $info:ident) => {
1770 if !$func($cx, $info) {
1771 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1772 if $func($cx, $info) {
1779 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1780 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1781 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1782 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1785 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1786 fn lint_chars_cmp<'a, 'tcx>(
1787 cx: &LateContext<'a, 'tcx>,
1788 info: &BinaryExprInfo,
1789 chain_methods: &[&str],
1790 lint: &'static Lint,
1794 if let Some(args) = method_chain_args(info.chain, chain_methods);
1795 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.node;
1796 if arg_char.len() == 1;
1797 if let hir::ExprKind::Path(ref qpath) = fun.node;
1798 if let Some(segment) = single_segment_path(qpath);
1799 if segment.ident.name == "Some";
1801 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1803 if self_ty.sty != ty::TyStr {
1807 span_lint_and_sugg(cx,
1810 &format!("you should use the `{}` method", suggest),
1812 format!("{}{}.{}({})",
1813 if info.eq { "" } else { "!" },
1814 snippet(cx, args[0][0].span, "_"),
1816 snippet(cx, arg_char[0].span, "_")));
1825 /// Checks for the `CHARS_NEXT_CMP` lint.
1826 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1827 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1830 /// Checks for the `CHARS_LAST_CMP` lint.
1831 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1832 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1835 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1839 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1840 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1841 cx: &LateContext<'a, 'tcx>,
1842 info: &BinaryExprInfo,
1843 chain_methods: &[&str],
1844 lint: &'static Lint,
1848 if let Some(args) = method_chain_args(info.chain, chain_methods);
1849 if let hir::ExprKind::Lit(ref lit) = info.other.node;
1850 if let ast::LitKind::Char(c) = lit.node;
1856 &format!("you should use the `{}` method", suggest),
1858 format!("{}{}.{}('{}')",
1859 if info.eq { "" } else { "!" },
1860 snippet(cx, args[0][0].span, "_"),
1872 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
1873 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1874 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
1877 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
1878 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1879 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
1882 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
1886 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1887 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
1888 if let Some((Constant::Str(r), _)) = constant(cx, cx.tables, arg) {
1890 let c = r.chars().next().unwrap();
1891 let snip = snippet(cx, expr.span, "..");
1892 let hint = snip.replace(
1893 &format!("\"{}\"", c.escape_default()),
1894 &format!("'{}'", c.escape_default()));
1897 SINGLE_CHAR_PATTERN,
1899 "single-character string constant used as pattern",
1901 db.span_suggestion(expr.span, "try using a char instead", hint);
1908 /// Checks for the `USELESS_ASREF` lint.
1909 fn lint_asref(cx: &LateContext, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
1910 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
1911 // check if the call is to the actual `AsRef` or `AsMut` trait
1912 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
1913 // check if the type after `as_ref` or `as_mut` is the same as before
1914 let recvr = &as_ref_args[0];
1915 let rcv_ty = cx.tables.expr_ty(recvr);
1916 let res_ty = cx.tables.expr_ty(expr);
1917 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
1918 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
1919 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
1924 &format!("this call to `{}` does nothing", call_name),
1926 snippet(cx, recvr.span, "_").into_owned(),
1932 /// Given a `Result<T, E>` type, return its error type (`E`).
1933 fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
1934 if let ty::TyAdt(_, substs) = ty.sty {
1935 if match_type(cx, ty, &paths::RESULT) {
1936 substs.types().nth(1)
1945 /// This checks whether a given type is known to implement Debug.
1946 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1947 match cx.tcx.lang_items().debug_trait() {
1948 Some(debug) => implements_trait(cx, ty, debug, &[]),
1955 StartsWith(&'static str),
1958 #[cfg_attr(rustfmt, rustfmt_skip)]
1959 const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
1960 (Convention::Eq("new"), &[SelfKind::No]),
1961 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1962 (Convention::StartsWith("from_"), &[SelfKind::No]),
1963 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1964 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1965 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1968 #[cfg_attr(rustfmt, rustfmt_skip)]
1969 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
1970 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1971 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1972 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1973 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1974 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1975 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1976 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1977 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1978 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1979 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1980 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1981 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1982 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1983 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1984 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1985 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1986 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1987 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1988 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1989 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1990 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1991 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1992 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1993 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1994 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1995 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1996 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1997 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1998 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1999 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
2002 #[cfg_attr(rustfmt, rustfmt_skip)]
2003 const PATTERN_METHODS: [(&str, usize); 17] = [
2011 ("split_terminator", 1),
2012 ("rsplit_terminator", 1),
2017 ("match_indices", 1),
2018 ("rmatch_indices", 1),
2019 ("trim_left_matches", 1),
2020 ("trim_right_matches", 1),
2024 #[derive(Clone, Copy, PartialEq, Debug)]
2039 allow_value_for_ref: bool,
2040 generics: &hir::Generics,
2042 // Self types in the HIR are desugared to explicit self types. So it will
2045 // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
2046 // the impl is on `Foo`)
2047 // Thus, we only need to test equality against the impl self type or if it is
2049 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
2050 // `Self`, `&mut Self`,
2051 // and `Box<Self>`, including the equivalent types with `Foo`.
2053 let is_actually_self = |ty| is_self_ty(ty) || SpanlessEq::new(cx).eq_ty(ty, self_ty);
2056 SelfKind::Value => is_actually_self(ty),
2057 SelfKind::Ref | SelfKind::RefMut => {
2058 if allow_value_for_ref && is_actually_self(ty) {
2062 hir::TyKind::Rptr(_, ref mt_ty) => {
2063 let mutability_match = if self == SelfKind::Ref {
2064 mt_ty.mutbl == hir::MutImmutable
2066 mt_ty.mutbl == hir::MutMutable
2068 is_actually_self(&mt_ty.ty) && mutability_match
2077 SelfKind::Value => false,
2078 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
2079 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
2080 SelfKind::No => true,
2085 fn description(self) -> &'static str {
2087 SelfKind::Value => "self by value",
2088 SelfKind::Ref => "self by reference",
2089 SelfKind::RefMut => "self by mutable reference",
2090 SelfKind::No => "no self",
2095 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
2096 single_segment_ty(ty).map_or(false, |seg| {
2097 generics.params.iter().any(|param| match param.kind {
2098 hir::GenericParamKind::Type { .. } => {
2099 param.name.ident().name == seg.ident.name && param.bounds.iter().any(|bound| {
2100 if let hir::GenericBound::Trait(ref ptr, ..) = *bound {
2101 let path = &ptr.trait_ref.path;
2102 match_path(path, name) && path.segments.last().map_or(false, |s| {
2103 if let Some(ref params) = s.args {
2104 if params.parenthesized {
2107 // FIXME(flip1995): messy, improve if there is a better option
2109 let types: Vec<_> = params.args.iter().filter_map(|arg| match arg {
2110 hir::GenericArg::Type(ty) => Some(ty),
2114 && (is_self_ty(&types[0]) || is_ty(&*types[0], self_ty))
2130 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
2131 match (&ty.node, &self_ty.node) {
2133 &hir::TyKind::Path(hir::QPath::Resolved(_, ref ty_path)),
2134 &hir::TyKind::Path(hir::QPath::Resolved(_, ref self_ty_path)),
2138 .map(|seg| seg.ident.name)
2139 .eq(self_ty_path.segments.iter().map(|seg| seg.ident.name)),
2144 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2145 if let hir::TyKind::Path(ref path) = ty.node {
2146 single_segment_path(path)
2153 fn check(&self, other: &str) -> bool {
2155 Convention::Eq(this) => this == other,
2156 Convention::StartsWith(this) => other.starts_with(this) && this != other,
2161 impl fmt::Display for Convention {
2162 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2164 Convention::Eq(this) => this.fmt(f),
2165 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2170 #[derive(Clone, Copy)]
2179 fn matches(self, cx: &LateContext, ty: &hir::FunctionRetTy) -> bool {
2180 let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
2182 (OutType::Unit, &hir::DefaultReturn(_)) => true,
2183 (OutType::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,
2184 (OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2185 (OutType::Any, &hir::Return(ref ty)) if !is_unit(ty) => true,
2186 (OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyKind::Rptr(_, _)),
2192 fn is_bool(ty: &hir::Ty) -> bool {
2193 if let hir::TyKind::Path(ref p) = ty.node {
2194 match_qpath(p, &["bool"])