3 use rustc::ty::{self, Ty};
4 use rustc::hir::def::Def;
9 use syntax::codemap::{Span, BytePos};
10 use utils::{get_arg_name, get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_self, is_self_ty,
11 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};
16 use 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.
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.
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 { .. }
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 { .. }
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 { .. }
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:** None.
149 /// x.ok().expect("why did I do this again?")
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:** None.
167 /// x.map(|a| a + 1).unwrap_or(0)
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:** None.
185 /// x.map(|a| a + 1).unwrap_or_else(some_function)
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)
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:** None.
221 /// opt.map_or(None, |a| a + 1)
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()
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)
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()
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('_')
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()
329 "using any `*or` method with a function call, which suggests `*or_else`"
332 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
334 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
335 /// generics, not for using the `clone` method on a concrete type.
337 /// **Known problems:** None.
346 "using `clone` on a `Copy` type"
349 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
350 /// (Rc, Arc, rc::Weak, or sync::Weak), and suggests calling Clone on
351 /// the corresponding trait instead.
353 /// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
354 /// can obscure the fact that only the pointer is being cloned, not the underlying
361 declare_restriction_lint! {
362 pub CLONE_ON_REF_PTR,
363 "using 'clone' on a ref-counted pointer"
366 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
368 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
369 /// cloning the underlying `T`.
371 /// **Known problems:** None.
378 /// let z = y.clone();
379 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
383 pub CLONE_DOUBLE_REF,
385 "using `clone` on `&&T`"
388 /// **What it does:** Checks for `new` not returning `Self`.
390 /// **Why is this bad?** As a convention, `new` methods are used to make a new
391 /// instance of a type.
393 /// **Known problems:** None.
398 /// fn new(..) -> NotAFoo {
405 "not returning `Self` in a `new` method"
408 /// **What it does:** Checks for string methods that receive a single-character
409 /// `str` as an argument, e.g. `_.split("x")`.
411 /// **Why is this bad?** Performing these methods using a `char` is faster than
414 /// **Known problems:** Does not catch multi-byte unicode characters.
417 /// `_.split("x")` could be `_.split('x')
419 pub SINGLE_CHAR_PATTERN,
421 "using a single-character str where a char could be used, e.g. \
425 /// **What it does:** Checks for getting the inner pointer of a temporary
428 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
429 /// as the `CString` is alive.
431 /// **Known problems:** None.
435 /// let c_str = CString::new("foo").unwrap().as_ptr();
437 /// call_some_ffi_func(c_str);
440 /// Here `c_str` point to a freed address. The correct use would be:
442 /// let c_str = CString::new("foo").unwrap();
444 /// call_some_ffi_func(c_str.as_ptr());
448 pub TEMPORARY_CSTRING_AS_PTR,
450 "getting the inner pointer of a temporary `CString`"
453 /// **What it does:** Checks for use of `.iter().nth()` (and the related
454 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
456 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
459 /// **Known problems:** None.
463 /// let some_vec = vec![0, 1, 2, 3];
464 /// let bad_vec = some_vec.iter().nth(3);
465 /// let bad_slice = &some_vec[..].iter().nth(3);
467 /// The correct use would be:
469 /// let some_vec = vec![0, 1, 2, 3];
470 /// let bad_vec = some_vec.get(3);
471 /// let bad_slice = &some_vec[..].get(3);
476 "using `.iter().nth()` on a standard library type with O(1) element access"
479 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
481 /// **Why is this bad?** `.nth(x)` is cleaner
483 /// **Known problems:** None.
487 /// let some_vec = vec![0, 1, 2, 3];
488 /// let bad_vec = some_vec.iter().skip(3).next();
489 /// let bad_slice = &some_vec[..].iter().skip(3).next();
491 /// The correct use would be:
493 /// let some_vec = vec![0, 1, 2, 3];
494 /// let bad_vec = some_vec.iter().nth(3);
495 /// let bad_slice = &some_vec[..].iter().nth(3);
500 "using `.skip(x).next()` on an iterator"
503 /// **What it does:** Checks for use of `.get().unwrap()` (or
504 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
506 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
509 /// **Known problems:** None.
513 /// let some_vec = vec![0, 1, 2, 3];
514 /// let last = some_vec.get(3).unwrap();
515 /// *some_vec.get_mut(0).unwrap() = 1;
517 /// The correct use would be:
519 /// let some_vec = vec![0, 1, 2, 3];
520 /// let last = some_vec[3];
526 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
529 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
530 /// `&str` or `String`.
532 /// **Why is this bad?** `.push_str(s)` is clearer
534 /// **Known problems:** None.
539 /// let def = String::from("def");
540 /// let mut s = String::new();
541 /// s.extend(abc.chars());
542 /// s.extend(def.chars());
544 /// The correct use would be:
547 /// let def = String::from("def");
548 /// let mut s = String::new();
550 /// s.push_str(&def));
553 pub STRING_EXTEND_CHARS,
555 "using `x.extend(s.chars())` where s is a `&str` or `String`"
558 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
561 /// **Why is this bad?** `.to_vec()` is clearer
563 /// **Known problems:** None.
567 /// let s = [1,2,3,4,5];
568 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
570 /// The better use would be:
572 /// let s = [1,2,3,4,5];
573 /// let s2 : Vec<isize> = s.to_vec();
576 pub ITER_CLONED_COLLECT,
578 "using `.cloned().collect()` on slice to create a `Vec`"
581 /// **What it does:** Checks for usage of `.chars().last()` or
582 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
584 /// **Why is this bad?** Readability, this can be written more concisely as
585 /// `_.ends_with(_)`.
587 /// **Known problems:** None.
591 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
596 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
599 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
600 /// types before and after the call are the same.
602 /// **Why is this bad?** The call is unnecessary.
604 /// **Known problems:** None.
608 /// let x: &[i32] = &[1,2,3,4,5];
609 /// do_stuff(x.as_ref());
611 /// The correct use would be:
613 /// let x: &[i32] = &[1,2,3,4,5];
619 "using `as_ref` where the types before and after the call are the same"
623 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
624 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
625 /// `sum` or `product`.
627 /// **Why is this bad?** Readability.
629 /// **Known problems:** None.
633 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
635 /// This could be written as:
637 /// let _ = (0..3).any(|x| x > 2);
640 pub UNNECESSARY_FOLD,
642 "using `fold` when a more succinct alternative exists"
645 impl LintPass for Pass {
646 fn get_lints(&self) -> LintArray {
650 SHOULD_IMPLEMENT_TRAIT,
651 WRONG_SELF_CONVENTION,
652 WRONG_PUB_SELF_CONVENTION,
654 OPTION_MAP_UNWRAP_OR,
655 OPTION_MAP_UNWRAP_OR_ELSE,
656 RESULT_MAP_UNWRAP_OR_ELSE,
667 TEMPORARY_CSTRING_AS_PTR,
681 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
682 #[allow(unused_attributes)]
683 // ^ required because `cyclomatic_complexity` attribute shows up as unused
684 #[cyclomatic_complexity = "30"]
685 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
686 if in_macro(expr.span) {
691 hir::ExprMethodCall(ref method_call, ref method_span, ref args) => {
693 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
694 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
695 lint_get_unwrap(cx, expr, arglists[0], false);
696 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
697 lint_get_unwrap(cx, expr, arglists[0], true);
698 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
699 lint_unwrap(cx, expr, arglists[0]);
700 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
701 lint_ok_expect(cx, expr, arglists[0]);
702 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
703 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
704 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
705 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
706 } else if let Some(arglists) = method_chain_args(expr, &["map_or"]) {
707 lint_map_or_none(cx, expr, arglists[0]);
708 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
709 lint_filter_next(cx, expr, arglists[0]);
710 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
711 lint_filter_map(cx, expr, arglists[0], arglists[1]);
712 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
713 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
714 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
715 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
716 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
717 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
718 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
719 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
720 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
721 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
722 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
723 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
724 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
725 lint_extend(cx, expr, arglists[0]);
726 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
727 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
728 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
729 lint_iter_nth(cx, expr, arglists[0], false);
730 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
731 lint_iter_nth(cx, expr, arglists[0], true);
732 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
733 lint_iter_skip_next(cx, expr);
734 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
735 lint_iter_cloned_collect(cx, expr, arglists[0]);
736 } else if let Some(arglists) = method_chain_args(expr, &["as_ref"]) {
737 lint_asref(cx, expr, "as_ref", arglists[0]);
738 } else if let Some(arglists) = method_chain_args(expr, &["as_mut"]) {
739 lint_asref(cx, expr, "as_mut", arglists[0]);
740 } else if let Some(arglists) = method_chain_args(expr, &["fold"]) {
741 lint_unnecessary_fold(cx, expr, arglists[0]);
744 lint_or_fun_call(cx, expr, *method_span, &method_call.name.as_str(), args);
746 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
747 if args.len() == 1 && method_call.name == "clone" {
748 lint_clone_on_copy(cx, expr, &args[0], self_ty);
749 lint_clone_on_ref_ptr(cx, expr, &args[0]);
753 ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
754 if method_call.name == method && args.len() > pos {
755 lint_single_char_pattern(cx, expr, &args[pos]);
761 hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
762 let mut info = BinaryExprInfo {
766 eq: op.node == hir::BiEq,
768 lint_binary_expr_with_method_call(cx, &mut info);
774 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
775 if in_external_macro(cx, implitem.span) {
778 let name = implitem.name;
779 let parent = cx.tcx.hir.get_parent(implitem.id);
780 let item = cx.tcx.hir.expect_item(parent);
782 if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
783 if let Some(first_arg_ty) = sig.decl.inputs.get(0);
784 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
785 if let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node;
787 if cx.access_levels.is_exported(implitem.id) {
788 // check missing trait implementations
789 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
790 if name == method_name &&
791 sig.decl.inputs.len() == n_args &&
792 out_type.matches(&sig.decl.output) &&
793 self_kind.matches(first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
794 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
795 "defining a method called `{}` on this type; consider implementing \
796 the `{}` trait or choosing a less ambiguous name", name, trait_name));
801 // check conventions w.r.t. conversion method names and predicates
802 let def_id = cx.tcx.hir.local_def_id(item.id);
803 let ty = cx.tcx.type_of(def_id);
804 let is_copy = is_copy(cx, ty);
805 for &(ref conv, self_kinds) in &CONVENTIONS {
807 if conv.check(&name.as_str());
810 .any(|k| k.matches(first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
812 let lint = if item.vis == hir::Visibility::Public {
813 WRONG_PUB_SELF_CONVENTION
815 WRONG_SELF_CONVENTION
820 &format!("methods called `{}` usually take {}; consider choosing a less \
824 .map(|k| k.description())
831 let ret_ty = return_ty(cx, implitem.id);
833 !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
837 "methods called `new` usually return `Self`");
844 /// Checks for the `OR_FUN_CALL` lint.
845 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
846 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
847 fn check_unwrap_or_default(
851 self_expr: &hir::Expr,
860 if name == "unwrap_or" {
861 if let hir::ExprPath(ref qpath) = fun.node {
862 let path = &*last_path_segment(qpath).name.as_str();
864 if ["default", "new"].contains(&path) {
865 let arg_ty = cx.tables.expr_ty(arg);
866 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
872 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
877 &format!("use of `{}` followed by a call to `{}`", name, path),
879 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
890 /// Check for `*or(foo())`.
891 fn check_general_case(
896 self_expr: &hir::Expr,
901 // (path, fn_has_argument, methods, suffix)
902 let know_types: &[(&[_], _, &[_], _)] = &[
903 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
904 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
905 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
906 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
909 // early check if the name is one we care about
910 if know_types.iter().all(|k| !k.2.contains(&name)) {
914 // don't lint for constant values
915 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
916 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
921 let self_ty = cx.tables.expr_ty(self_expr);
923 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
924 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
926 (fn_has_arguments, poss, suffix)
931 if !poss.contains(&name) {
935 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
936 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
937 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
938 (false, true) => snippet(cx, fun_span, ".."),
940 let span_replace_word = method_span.with_hi(span.hi());
945 &format!("use of `{}` followed by a function call", name),
947 format!("{}_{}({})", name, suffix, sugg),
953 hir::ExprCall(ref fun, ref or_args) => {
954 let or_has_args = !or_args.is_empty();
955 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
956 check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
959 hir::ExprMethodCall(_, span, ref or_args) => {
960 check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
967 /// Checks for the `CLONE_ON_COPY` lint.
968 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
969 let ty = cx.tables.expr_ty(expr);
970 if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
971 if let ty::TyRef(_, ty::TypeAndMut { ty: innermost, .. }) = inner.sty {
976 "using `clone` on a double-reference; \
977 this will copy the reference instead of cloning the inner type",
978 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
979 let mut ty = innermost;
981 while let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = ty.sty {
985 let refs: String = iter::repeat('&').take(n + 1).collect();
986 let derefs: String = iter::repeat('*').take(n).collect();
987 let explicit = format!("{}{}::clone({})", refs, ty, snip);
988 db.span_suggestion(expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()));
989 db.span_suggestion(expr.span, "or try being explicit about what type to clone", explicit);
992 return; // don't report clone_on_copy
998 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
999 if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
1000 let parent = cx.tcx.hir.get_parent_node(expr.id);
1001 match cx.tcx.hir.get(parent) {
1002 hir::map::NodeExpr(parent) => match parent.node {
1003 // &*x is a nop, &x.clone() is not
1004 hir::ExprAddrOf(..) |
1005 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1006 hir::ExprMethodCall(..) => return,
1009 hir::map::NodeStmt(stmt) => {
1010 if let hir::StmtDecl(ref decl, _) = stmt.node {
1011 if let hir::DeclLocal(ref loc) = decl.node {
1012 if let hir::PatKind::Ref(..) = loc.pat.node {
1013 // let ref y = *x borrows x, let ref y = x.clone() does not
1021 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
1023 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1028 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1029 if let Some((text, snip)) = snip {
1030 db.span_suggestion(expr.span, text, snip);
1036 fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1037 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(arg));
1039 if let ty::TyAdt(_, subst) = obj_ty.sty {
1040 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1042 } else if match_type(cx, obj_ty, &paths::ARC) {
1044 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1054 "using '.clone()' on a ref-counted pointer",
1056 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1062 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1064 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1065 let target = &arglists[0][0];
1066 let (self_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(target));
1067 let ref_str = if self_ty.sty == ty::TyStr {
1069 } else if match_type(cx, self_ty, &paths::STRING) {
1077 STRING_EXTEND_CHARS,
1079 "calling `.extend(_.chars())`",
1082 "{}.push_str({}{})",
1083 snippet(cx, args[0].span, "_"),
1085 snippet(cx, target.span, "_")
1091 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1092 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&args[0]));
1093 if match_type(cx, obj_ty, &paths::STRING) {
1094 lint_string_extend(cx, expr, args);
1098 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1100 if let hir::ExprCall(ref fun, ref args) = new.node;
1102 if let hir::ExprPath(ref path) = fun.node;
1103 if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1104 if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1108 TEMPORARY_CSTRING_AS_PTR,
1110 "you are getting the inner pointer of a temporary `CString`",
1112 db.note("that pointer will be invalid outside this expression");
1113 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1119 fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1120 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1121 && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1125 ITER_CLONED_COLLECT,
1127 "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1133 fn lint_unnecessary_fold(cx: &LateContext, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1134 // Check that this is a call to Iterator::fold rather than just some function called fold
1135 if !match_trait_method(cx, expr, &paths::ITERATOR) {
1139 assert!(fold_args.len() == 3,
1140 "Expected fold_args to have three entries - the receiver, the initial value and the closure");
1142 fn check_fold_with_op(
1144 fold_args: &[hir::Expr],
1146 replacement_method_name: &str,
1147 replacement_has_args: bool) {
1150 // Extract the body of the closure passed to fold
1151 if let hir::ExprClosure(_, _, body_id, _, _) = fold_args[2].node;
1152 let closure_body = cx.tcx.hir.body(body_id);
1153 let closure_expr = remove_blocks(&closure_body.value);
1155 // Check if the closure body is of the form `acc <op> some_expr(x)`
1156 if let hir::ExprBinary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1157 if bin_op.node == op;
1159 // Extract the names of the two arguments to the closure
1160 if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1161 if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1163 if match_var(&*left_expr, first_arg_ident);
1164 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1167 // Span containing `.fold(...)`
1168 let next_point = cx.sess().codemap().next_point(fold_args[0].span);
1169 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1171 let sugg = if replacement_has_args {
1173 ".{replacement}(|{s}| {r})",
1174 replacement = replacement_method_name,
1175 s = second_arg_ident,
1176 r = snippet(cx, right_expr.span, "EXPR"),
1181 replacement = replacement_method_name,
1189 // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
1190 "this `.fold` can be written more succinctly using another method",
1198 // Check if the first argument to .fold is a suitable literal
1199 match fold_args[1].node {
1200 hir::ExprLit(ref lit) => {
1202 ast::LitKind::Bool(false) => check_fold_with_op(
1203 cx, fold_args, hir::BinOp_::BiOr, "any", true
1205 ast::LitKind::Bool(true) => check_fold_with_op(
1206 cx, fold_args, hir::BinOp_::BiAnd, "all", true
1208 ast::LitKind::Int(0, _) => check_fold_with_op(
1209 cx, fold_args, hir::BinOp_::BiAdd, "sum", false
1211 ast::LitKind::Int(1, _) => check_fold_with_op(
1212 cx, fold_args, hir::BinOp_::BiMul, "product", false
1221 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1222 let mut_str = if is_mut { "_mut" } else { "" };
1223 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1225 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1227 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1230 return; // caller is not a type that we want to lint
1238 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1245 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1246 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1247 // because they do not implement `IndexMut`
1248 let expr_ty = cx.tables.expr_ty(&get_args[0]);
1249 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1251 } else if match_type(cx, expr_ty, &paths::VEC) {
1253 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1255 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1257 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1260 return; // caller is not a type that we want to lint
1263 let mut_str = if is_mut { "_mut" } else { "" };
1264 let borrow_str = if is_mut { "&mut " } else { "&" };
1270 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1278 snippet(cx, get_args[0].span, "_"),
1279 snippet(cx, get_args[1].span, "_")
1284 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
1285 // lint if caller of skip is an Iterator
1286 if match_trait_method(cx, expr, &paths::ITERATOR) {
1291 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1296 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
1297 fn may_slice(cx: &LateContext, ty: Ty) -> bool {
1299 ty::TySlice(_) => true,
1300 ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1301 ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1302 ty::TyArray(_, size) => size.val.to_raw_bits().expect("array length") < 32,
1303 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => may_slice(cx, inner),
1308 if let hir::ExprMethodCall(ref path, _, ref args) = expr.node {
1309 if path.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1310 sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1316 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1317 ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1318 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => if may_slice(cx, inner) {
1319 sugg::Sugg::hir_opt(cx, expr)
1328 /// lint use of `unwrap()` for `Option`s and `Result`s
1329 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1330 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&unwrap_args[0]));
1332 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1333 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1334 } else if match_type(cx, obj_ty, &paths::RESULT) {
1335 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1340 if let Some((lint, kind, none_value)) = mess {
1346 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1347 using expect() to provide a better panic \
1356 /// lint use of `ok().expect()` for `Result`s
1357 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1358 // lint if the caller of `ok()` is a `Result`
1359 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1360 let result_type = cx.tables.expr_ty(&ok_args[0]);
1361 if let Some(error_type) = get_error_type(cx, result_type) {
1362 if has_debug_impl(error_type, cx) {
1367 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1374 /// lint use of `map().unwrap_or()` for `Option`s
1375 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1376 // lint if the caller of `map()` is an `Option`
1377 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1378 // get snippets for args to map() and unwrap_or()
1379 let map_snippet = snippet(cx, map_args[1].span, "..");
1380 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1382 // comparing the snippet from source to raw text ("None") below is safe
1383 // because we already have checked the type.
1384 let arg = if unwrap_snippet == "None" {
1389 let suggest = if unwrap_snippet == "None" {
1395 "called `map(f).unwrap_or({})` on an Option value. \
1396 This can be done more directly by calling `{}` instead",
1400 // lint, with note if neither arg is > 1 line and both map() and
1401 // unwrap_or() have the same span
1402 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1403 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1404 if same_span && !multiline {
1405 let suggest = if unwrap_snippet == "None" {
1406 format!("and_then({})", map_snippet)
1408 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1411 "replace `map({}).unwrap_or({})` with `{}`",
1416 span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, ¬e);
1417 } else if same_span && multiline {
1418 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1423 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1424 fn lint_map_unwrap_or_else<'a, 'tcx>(
1425 cx: &LateContext<'a, 'tcx>,
1426 expr: &'tcx hir::Expr,
1427 map_args: &'tcx [hir::Expr],
1428 unwrap_args: &'tcx [hir::Expr],
1430 // lint if the caller of `map()` is an `Option`
1431 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1432 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1433 if is_option || is_result {
1435 let msg = if is_option {
1436 "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1437 `map_or_else(g, f)` instead"
1439 "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1440 `ok().map_or_else(g, f)` instead"
1442 // get snippets for args to map() and unwrap_or_else()
1443 let map_snippet = snippet(cx, map_args[1].span, "..");
1444 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1445 // lint, with note if neither arg is > 1 line and both map() and
1446 // unwrap_or_else() have the same span
1447 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1448 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1449 if same_span && !multiline {
1453 OPTION_MAP_UNWRAP_OR_ELSE
1455 RESULT_MAP_UNWRAP_OR_ELSE
1461 "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1464 if is_result { "ok()." } else { "" }
1467 } else if same_span && multiline {
1471 OPTION_MAP_UNWRAP_OR_ELSE
1473 RESULT_MAP_UNWRAP_OR_ELSE
1482 /// lint use of `_.map_or(None, _)` for `Option`s
1483 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1484 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1485 // check if the first non-self argument to map_or() is None
1486 let map_or_arg_is_none = if let hir::Expr_::ExprPath(ref qpath) = map_or_args[1].node {
1487 match_qpath(qpath, &paths::OPTION_NONE)
1492 if map_or_arg_is_none {
1494 let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1495 `and_then(f)` instead";
1496 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1497 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1498 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1499 span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1500 db.span_suggestion(expr.span, "try using and_then instead", hint);
1506 /// lint use of `filter().next()` for `Iterators`
1507 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1508 // lint if caller of `.filter().next()` is an Iterator
1509 if match_trait_method(cx, expr, &paths::ITERATOR) {
1510 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1511 `.find(p)` instead.";
1512 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1513 if filter_snippet.lines().count() <= 1 {
1514 // add note if not multi-line
1521 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1524 span_lint(cx, FILTER_NEXT, expr.span, msg);
1529 /// lint use of `filter().map()` for `Iterators`
1530 fn lint_filter_map<'a, 'tcx>(
1531 cx: &LateContext<'a, 'tcx>,
1532 expr: &'tcx hir::Expr,
1533 _filter_args: &'tcx [hir::Expr],
1534 _map_args: &'tcx [hir::Expr],
1536 // lint if caller of `.filter().map()` is an Iterator
1537 if match_trait_method(cx, expr, &paths::ITERATOR) {
1538 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1539 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1540 span_lint(cx, FILTER_MAP, expr.span, msg);
1544 /// lint use of `filter().map()` for `Iterators`
1545 fn lint_filter_map_map<'a, 'tcx>(
1546 cx: &LateContext<'a, 'tcx>,
1547 expr: &'tcx hir::Expr,
1548 _filter_args: &'tcx [hir::Expr],
1549 _map_args: &'tcx [hir::Expr],
1551 // lint if caller of `.filter().map()` is an Iterator
1552 if match_trait_method(cx, expr, &paths::ITERATOR) {
1553 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1554 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1555 span_lint(cx, FILTER_MAP, expr.span, msg);
1559 /// lint use of `filter().flat_map()` for `Iterators`
1560 fn lint_filter_flat_map<'a, 'tcx>(
1561 cx: &LateContext<'a, 'tcx>,
1562 expr: &'tcx hir::Expr,
1563 _filter_args: &'tcx [hir::Expr],
1564 _map_args: &'tcx [hir::Expr],
1566 // lint if caller of `.filter().flat_map()` is an Iterator
1567 if match_trait_method(cx, expr, &paths::ITERATOR) {
1568 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1569 This is more succinctly expressed by calling `.flat_map(..)` \
1570 and filtering by returning an empty Iterator.";
1571 span_lint(cx, FILTER_MAP, expr.span, msg);
1575 /// lint use of `filter_map().flat_map()` for `Iterators`
1576 fn lint_filter_map_flat_map<'a, 'tcx>(
1577 cx: &LateContext<'a, 'tcx>,
1578 expr: &'tcx hir::Expr,
1579 _filter_args: &'tcx [hir::Expr],
1580 _map_args: &'tcx [hir::Expr],
1582 // lint if caller of `.filter_map().flat_map()` is an Iterator
1583 if match_trait_method(cx, expr, &paths::ITERATOR) {
1584 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1585 This is more succinctly expressed by calling `.flat_map(..)` \
1586 and filtering by returning an empty Iterator.";
1587 span_lint(cx, FILTER_MAP, expr.span, msg);
1591 /// lint searching an Iterator followed by `is_some()`
1592 fn lint_search_is_some<'a, 'tcx>(
1593 cx: &LateContext<'a, 'tcx>,
1594 expr: &'tcx hir::Expr,
1595 search_method: &str,
1596 search_args: &'tcx [hir::Expr],
1597 is_some_args: &'tcx [hir::Expr],
1599 // lint if caller of search is an Iterator
1600 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1602 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1603 expressed by calling `any()`.",
1606 let search_snippet = snippet(cx, search_args[1].span, "..");
1607 if search_snippet.lines().count() <= 1 {
1608 // add note if not multi-line
1615 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1618 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1623 /// Used for `lint_binary_expr_with_method_call`.
1624 #[derive(Copy, Clone)]
1625 struct BinaryExprInfo<'a> {
1626 expr: &'a hir::Expr,
1627 chain: &'a hir::Expr,
1628 other: &'a hir::Expr,
1632 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1633 fn lint_binary_expr_with_method_call<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, info: &mut BinaryExprInfo) {
1634 macro_rules! lint_with_both_lhs_and_rhs {
1635 ($func:ident, $cx:expr, $info:ident) => {
1636 if !$func($cx, $info) {
1637 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1638 if $func($cx, $info) {
1645 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1646 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1647 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1648 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1651 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1652 fn lint_chars_cmp<'a, 'tcx>(
1653 cx: &LateContext<'a, 'tcx>,
1654 info: &BinaryExprInfo,
1655 chain_methods: &[&str],
1656 lint: &'static Lint,
1660 if let Some(args) = method_chain_args(info.chain, chain_methods);
1661 if let hir::ExprCall(ref fun, ref arg_char) = info.other.node;
1662 if arg_char.len() == 1;
1663 if let hir::ExprPath(ref qpath) = fun.node;
1664 if let Some(segment) = single_segment_path(qpath);
1665 if segment.name == "Some";
1667 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1669 if self_ty.sty != ty::TyStr {
1673 span_lint_and_sugg(cx,
1676 &format!("you should use the `{}` method", suggest),
1678 format!("{}{}.{}({})",
1679 if info.eq { "" } else { "!" },
1680 snippet(cx, args[0][0].span, "_"),
1682 snippet(cx, arg_char[0].span, "_")));
1691 /// Checks for the `CHARS_NEXT_CMP` lint.
1692 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1693 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1696 /// Checks for the `CHARS_LAST_CMP` lint.
1697 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1698 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1701 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1705 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1706 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1707 cx: &LateContext<'a, 'tcx>,
1708 info: &BinaryExprInfo,
1709 chain_methods: &[&str],
1710 lint: &'static Lint,
1714 if let Some(args) = method_chain_args(info.chain, chain_methods);
1715 if let hir::ExprLit(ref lit) = info.other.node;
1716 if let ast::LitKind::Char(c) = lit.node;
1722 &format!("you should use the `{}` method", suggest),
1724 format!("{}{}.{}('{}')",
1725 if info.eq { "" } else { "!" },
1726 snippet(cx, args[0][0].span, "_"),
1738 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
1739 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1740 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
1743 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
1744 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1745 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
1748 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
1752 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1753 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
1754 if let Some((Constant::Str(r), _)) = constant(cx, arg) {
1756 let c = r.chars().next().unwrap();
1757 let snip = snippet(cx, expr.span, "..");
1758 let hint = snip.replace(
1759 &format!("\"{}\"", c.escape_default()),
1760 &format!("'{}'", c.escape_default()));
1763 SINGLE_CHAR_PATTERN,
1765 "single-character string constant used as pattern",
1767 db.span_suggestion(expr.span, "try using a char instead", hint);
1774 /// Checks for the `USELESS_ASREF` lint.
1775 fn lint_asref(cx: &LateContext, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
1776 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
1777 // check if the call is to the actual `AsRef` or `AsMut` trait
1778 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
1779 // check if the type after `as_ref` or `as_mut` is the same as before
1780 let recvr = &as_ref_args[0];
1781 let rcv_ty = cx.tables.expr_ty(recvr);
1782 let res_ty = cx.tables.expr_ty(expr);
1783 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
1784 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
1785 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
1790 &format!("this call to `{}` does nothing", call_name),
1792 snippet(cx, recvr.span, "_").into_owned(),
1798 /// Given a `Result<T, E>` type, return its error type (`E`).
1799 fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
1800 if let ty::TyAdt(_, substs) = ty.sty {
1801 if match_type(cx, ty, &paths::RESULT) {
1802 substs.types().nth(1)
1811 /// This checks whether a given type is known to implement Debug.
1812 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1813 match cx.tcx.lang_items().debug_trait() {
1814 Some(debug) => implements_trait(cx, ty, debug, &[]),
1821 StartsWith(&'static str),
1824 #[cfg_attr(rustfmt, rustfmt_skip)]
1825 const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
1826 (Convention::Eq("new"), &[SelfKind::No]),
1827 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1828 (Convention::StartsWith("from_"), &[SelfKind::No]),
1829 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1830 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1831 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1834 #[cfg_attr(rustfmt, rustfmt_skip)]
1835 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
1836 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1837 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1838 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1839 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1840 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1841 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1842 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1843 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1844 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1845 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1846 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1847 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1848 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1849 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1850 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1851 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1852 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1853 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1854 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1855 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1856 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1857 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1858 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1859 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1860 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1861 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1862 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1863 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1864 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1865 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1868 #[cfg_attr(rustfmt, rustfmt_skip)]
1869 const PATTERN_METHODS: [(&str, usize); 17] = [
1877 ("split_terminator", 1),
1878 ("rsplit_terminator", 1),
1883 ("match_indices", 1),
1884 ("rmatch_indices", 1),
1885 ("trim_left_matches", 1),
1886 ("trim_right_matches", 1),
1890 #[derive(Clone, Copy, PartialEq, Debug)]
1904 allow_value_for_ref: bool,
1905 generics: &hir::Generics,
1907 // Self types in the HIR are desugared to explicit self types. So it will
1910 // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
1911 // the impl is on `Foo`)
1912 // Thus, we only need to test equality against the impl self type or if it is
1914 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
1915 // `Self`, `&mut Self`,
1916 // and `Box<Self>`, including the equivalent types with `Foo`.
1918 let is_actually_self = |ty| is_self_ty(ty) || ty == self_ty;
1921 SelfKind::Value => is_actually_self(ty),
1922 SelfKind::Ref | SelfKind::RefMut => {
1923 if allow_value_for_ref && is_actually_self(ty) {
1927 hir::TyRptr(_, ref mt_ty) => {
1928 let mutability_match = if self == SelfKind::Ref {
1929 mt_ty.mutbl == hir::MutImmutable
1931 mt_ty.mutbl == hir::MutMutable
1933 is_actually_self(&mt_ty.ty) && mutability_match
1942 SelfKind::Value => false,
1943 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
1944 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
1945 SelfKind::No => true,
1950 fn description(&self) -> &'static str {
1952 SelfKind::Value => "self by value",
1953 SelfKind::Ref => "self by reference",
1954 SelfKind::RefMut => "self by mutable reference",
1955 SelfKind::No => "no self",
1960 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
1961 single_segment_ty(ty).map_or(false, |seg| {
1962 generics.ty_params().any(|param| {
1963 param.name == seg.name && param.bounds.iter().any(|bound| {
1964 if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
1965 let path = &ptr.trait_ref.path;
1966 match_path(path, name) && path.segments.last().map_or(false, |s| {
1967 if let Some(ref params) = s.parameters {
1968 if params.parenthesized {
1971 params.types.len() == 1
1972 && (is_self_ty(¶ms.types[0]) || is_ty(&*params.types[0], self_ty))
1986 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
1987 match (&ty.node, &self_ty.node) {
1989 &hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
1990 &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path)),
1994 .map(|seg| seg.name)
1995 .eq(self_ty_path.segments.iter().map(|seg| seg.name)),
2000 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2001 if let hir::TyPath(ref path) = ty.node {
2002 single_segment_path(path)
2009 fn check(&self, other: &str) -> bool {
2011 Convention::Eq(this) => this == other,
2012 Convention::StartsWith(this) => other.starts_with(this) && this != other,
2017 impl fmt::Display for Convention {
2018 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2020 Convention::Eq(this) => this.fmt(f),
2021 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2026 #[derive(Clone, Copy)]
2035 fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
2037 (&OutType::Unit, &hir::DefaultReturn(_)) => true,
2038 (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
2039 (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2040 (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
2041 (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
2047 fn is_bool(ty: &hir::Ty) -> bool {
2048 if let hir::TyPath(ref p) = ty.node {
2049 match_qpath(p, &["bool"])