3 use rustc::middle::const_val::ConstVal;
4 use rustc::ty::{self, Ty};
5 use rustc::hir::def::Def;
6 use rustc::ty::subst::Substs;
7 use rustc_const_eval::ConstContext;
12 use syntax::codemap::Span;
13 use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_self, is_self_ty,
14 iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
15 match_type, method_chain_args, return_ty, same_tys, single_segment_path, snippet, span_lint,
16 span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
19 use utils::const_to_u64;
24 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
26 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
27 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
28 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
29 /// `Allow` by default.
31 /// **Known problems:** None.
38 pub OPTION_UNWRAP_USED,
40 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
43 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
45 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
46 /// values. Normally, you want to implement more sophisticated error handling,
47 /// and propagate errors upwards with `try!`.
49 /// Even if you want to panic on errors, not all `Error`s implement good
50 /// messages on display. Therefore it may be beneficial to look at the places
51 /// where they may get displayed. Activate this lint to do just that.
53 /// **Known problems:** None.
60 pub RESULT_UNWRAP_USED,
62 "using `Result.unwrap()`, which might be better handled"
65 /// **What it does:** Checks for methods that should live in a trait
66 /// implementation of a `std` trait (see [llogiq's blog
67 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
68 /// information) instead of an inherent implementation.
70 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
71 /// the code, often with very little cost. Also people seeing a `mul(...)`
73 /// may expect `*` to work equally, so you should have good reason to disappoint
76 /// **Known problems:** None.
82 /// fn add(&self, other: &X) -> X { .. }
86 pub SHOULD_IMPLEMENT_TRAIT,
88 "defining a method that should be implementing a std trait"
91 /// **What it does:** Checks for methods with certain name prefixes and which
92 /// doesn't match how self is taken. The actual rules are:
94 /// |Prefix |`self` taken |
95 /// |-------|----------------------|
96 /// |`as_` |`&self` or `&mut self`|
99 /// |`is_` |`&self` or none |
100 /// |`to_` |`&self` |
102 /// **Why is this bad?** Consistency breeds readability. If you follow the
103 /// conventions, your users won't be surprised that they, e.g., need to supply a
104 /// mutable reference to a `as_..` function.
106 /// **Known problems:** None.
111 /// fn as_str(self) -> &str { .. }
115 pub WRONG_SELF_CONVENTION,
117 "defining a method named with an established prefix (like \"into_\") that takes \
118 `self` with the wrong convention"
121 /// **What it does:** This is the same as
122 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
124 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
126 /// **Known problems:** Actually *renaming* the function may break clients if
127 /// the function is part of the public interface. In that case, be mindful of
128 /// the stability guarantees you've given your users.
133 /// pub fn as_str(self) -> &str { .. }
137 pub WRONG_PUB_SELF_CONVENTION,
139 "defining a public method named with an established prefix (like \"into_\") that takes \
140 `self` with the wrong convention"
143 /// **What it does:** Checks for usage of `ok().expect(..)`.
145 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
146 /// directly to get a better error message.
148 /// **Known problems:** None.
152 /// x.ok().expect("why did I do this again?")
157 "using `ok().expect()`, which gives worse error messages than \
158 calling `expect` directly on the Result"
161 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
163 /// **Why is this bad?** Readability, this can be written more concisely as
164 /// `_.map_or(_, _)`.
166 /// **Known problems:** None.
170 /// x.map(|a| a + 1).unwrap_or(0)
173 pub OPTION_MAP_UNWRAP_OR,
175 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
179 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
181 /// **Why is this bad?** Readability, this can be written more concisely as
182 /// `_.map_or_else(_, _)`.
184 /// **Known problems:** None.
188 /// x.map(|a| a + 1).unwrap_or_else(some_function)
191 pub OPTION_MAP_UNWRAP_OR_ELSE,
193 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
197 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
199 /// **Why is this bad?** Readability, this can be written more concisely as
200 /// `result.ok().map_or_else(_, _)`.
202 /// **Known problems:** None.
206 /// x.map(|a| a + 1).unwrap_or_else(some_function)
209 pub RESULT_MAP_UNWRAP_OR_ELSE,
211 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
212 `.ok().map_or_else(g, f)`"
215 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
217 /// **Why is this bad?** Readability, this can be written more concisely as
220 /// **Known problems:** None.
224 /// opt.map_or(None, |a| a + 1)
227 pub OPTION_MAP_OR_NONE,
229 "using `Option.map_or(None, f)`, which is more succinctly expressed as \
233 /// **What it does:** Checks for usage of `_.filter(_).next()`.
235 /// **Why is this bad?** Readability, this can be written more concisely as
238 /// **Known problems:** None.
242 /// iter.filter(|x| x == 0).next()
247 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
250 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
251 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
253 /// **Why is this bad?** Readability, this can be written more concisely as a
254 /// single method call.
256 /// **Known problems:** Often requires a condition + Option/Iterator creation
257 /// inside the closure.
261 /// iter.filter(|x| x == 0).map(|x| x * 2)
266 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
267 usually be written as a single method call"
270 /// **What it does:** Checks for an iterator search (such as `find()`,
271 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
273 /// **Why is this bad?** Readability, this can be written more concisely as
276 /// **Known problems:** None.
280 /// iter.find(|x| x == 0).is_some()
285 "using an iterator search followed by `is_some()`, which is more succinctly \
286 expressed as a call to `any()`"
289 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
290 /// if it starts with a given char.
292 /// **Why is this bad?** Readability, this can be written more concisely as
293 /// `_.starts_with(_)`.
295 /// **Known problems:** None.
299 /// name.chars().next() == Some('_')
304 "using `.chars().next()` to check if a string starts with a char"
307 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
308 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
309 /// `unwrap_or_default` instead.
311 /// **Why is this bad?** The function will always be called and potentially
312 /// allocate an object acting as the default.
314 /// **Known problems:** If the function has side-effects, not calling it will
315 /// change the semantic of the program, but you shouldn't rely on that anyway.
319 /// foo.unwrap_or(String::new())
321 /// this can instead be written:
323 /// foo.unwrap_or_else(String::new)
327 /// foo.unwrap_or_default()
332 "using any `*or` method with a function call, which suggests `*or_else`"
335 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
337 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
338 /// generics, not for using the `clone` method on a concrete type.
340 /// **Known problems:** None.
349 "using `clone` on a `Copy` type"
352 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
353 /// (Rc, Arc, rc::Weak, or sync::Weak), and suggests calling Clone on
354 /// the corresponding trait instead.
356 /// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
357 /// can obscure the fact that only the pointer is being cloned, not the underlying
364 declare_restriction_lint! {
365 pub CLONE_ON_REF_PTR,
366 "using 'clone' on a ref-counted pointer"
369 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
371 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
372 /// cloning the underlying `T`.
374 /// **Known problems:** None.
381 /// let z = y.clone();
382 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
386 pub CLONE_DOUBLE_REF,
388 "using `clone` on `&&T`"
391 /// **What it does:** Checks for `new` not returning `Self`.
393 /// **Why is this bad?** As a convention, `new` methods are used to make a new
394 /// instance of a type.
396 /// **Known problems:** None.
401 /// fn new(..) -> NotAFoo {
408 "not returning `Self` in a `new` method"
411 /// **What it does:** Checks for string methods that receive a single-character
412 /// `str` as an argument, e.g. `_.split("x")`.
414 /// **Why is this bad?** Performing these methods using a `char` is faster than
417 /// **Known problems:** Does not catch multi-byte unicode characters.
420 /// `_.split("x")` could be `_.split('x')
422 pub SINGLE_CHAR_PATTERN,
424 "using a single-character str where a char could be used, e.g. \
428 /// **What it does:** Checks for getting the inner pointer of a temporary
431 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
432 /// as the `CString` is alive.
434 /// **Known problems:** None.
438 /// let c_str = CString::new("foo").unwrap().as_ptr();
440 /// call_some_ffi_func(c_str);
443 /// Here `c_str` point to a freed address. The correct use would be:
445 /// let c_str = CString::new("foo").unwrap();
447 /// call_some_ffi_func(c_str.as_ptr());
451 pub TEMPORARY_CSTRING_AS_PTR,
453 "getting the inner pointer of a temporary `CString`"
456 /// **What it does:** Checks for use of `.iter().nth()` (and the related
457 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
459 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
462 /// **Known problems:** None.
466 /// let some_vec = vec![0, 1, 2, 3];
467 /// let bad_vec = some_vec.iter().nth(3);
468 /// let bad_slice = &some_vec[..].iter().nth(3);
470 /// The correct use would be:
472 /// let some_vec = vec![0, 1, 2, 3];
473 /// let bad_vec = some_vec.get(3);
474 /// let bad_slice = &some_vec[..].get(3);
479 "using `.iter().nth()` on a standard library type with O(1) element access"
482 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
484 /// **Why is this bad?** `.nth(x)` is cleaner
486 /// **Known problems:** None.
490 /// let some_vec = vec![0, 1, 2, 3];
491 /// let bad_vec = some_vec.iter().skip(3).next();
492 /// let bad_slice = &some_vec[..].iter().skip(3).next();
494 /// The correct use would be:
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);
503 "using `.skip(x).next()` on an iterator"
506 /// **What it does:** Checks for use of `.get().unwrap()` (or
507 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
509 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
512 /// **Known problems:** None.
516 /// let some_vec = vec![0, 1, 2, 3];
517 /// let last = some_vec.get(3).unwrap();
518 /// *some_vec.get_mut(0).unwrap() = 1;
520 /// The correct use would be:
522 /// let some_vec = vec![0, 1, 2, 3];
523 /// let last = some_vec[3];
529 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
532 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
533 /// `&str` or `String`.
535 /// **Why is this bad?** `.push_str(s)` is clearer
537 /// **Known problems:** None.
542 /// let def = String::from("def");
543 /// let mut s = String::new();
544 /// s.extend(abc.chars());
545 /// s.extend(def.chars());
547 /// The correct use would be:
550 /// let def = String::from("def");
551 /// let mut s = String::new();
553 /// s.push_str(&def));
556 pub STRING_EXTEND_CHARS,
558 "using `x.extend(s.chars())` where s is a `&str` or `String`"
561 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
564 /// **Why is this bad?** `.to_vec()` is clearer
566 /// **Known problems:** None.
570 /// let s = [1,2,3,4,5];
571 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
573 /// The better use would be:
575 /// let s = [1,2,3,4,5];
576 /// let s2 : Vec<isize> = s.to_vec();
579 pub ITER_CLONED_COLLECT,
581 "using `.cloned().collect()` on slice to create a `Vec`"
584 /// **What it does:** Checks for usage of `.chars().last()` or
585 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
587 /// **Why is this bad?** Readability, this can be written more concisely as
588 /// `_.ends_with(_)`.
590 /// **Known problems:** None.
594 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
599 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
602 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
603 /// types before and after the call are the same.
605 /// **Why is this bad?** The call is unnecessary.
607 /// **Known problems:** None.
611 /// let x: &[i32] = &[1,2,3,4,5];
612 /// do_stuff(x.as_ref());
614 /// The correct use would be:
616 /// let x: &[i32] = &[1,2,3,4,5];
622 "using `as_ref` where the types before and after the call are the same"
625 impl LintPass for Pass {
626 fn get_lints(&self) -> LintArray {
630 SHOULD_IMPLEMENT_TRAIT,
631 WRONG_SELF_CONVENTION,
632 WRONG_PUB_SELF_CONVENTION,
634 OPTION_MAP_UNWRAP_OR,
635 OPTION_MAP_UNWRAP_OR_ELSE,
636 RESULT_MAP_UNWRAP_OR_ELSE,
647 TEMPORARY_CSTRING_AS_PTR,
660 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
661 #[allow(unused_attributes)]
662 // ^ required because `cyclomatic_complexity` attribute shows up as unused
663 #[cyclomatic_complexity = "30"]
664 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
665 if in_macro(expr.span) {
670 hir::ExprMethodCall(ref method_call, _, ref args) => {
672 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
673 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
674 lint_get_unwrap(cx, expr, arglists[0], false);
675 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
676 lint_get_unwrap(cx, expr, arglists[0], true);
677 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
678 lint_unwrap(cx, expr, arglists[0]);
679 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
680 lint_ok_expect(cx, expr, arglists[0]);
681 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
682 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
683 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
684 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
685 } else if let Some(arglists) = method_chain_args(expr, &["map_or"]) {
686 lint_map_or_none(cx, expr, arglists[0]);
687 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
688 lint_filter_next(cx, expr, arglists[0]);
689 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
690 lint_filter_map(cx, expr, arglists[0], arglists[1]);
691 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
692 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
693 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
694 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
695 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
696 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
697 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
698 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
699 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
700 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
701 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
702 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
703 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
704 lint_extend(cx, expr, arglists[0]);
705 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
706 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
707 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
708 lint_iter_nth(cx, expr, arglists[0], false);
709 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
710 lint_iter_nth(cx, expr, arglists[0], true);
711 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
712 lint_iter_skip_next(cx, expr);
713 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
714 lint_iter_cloned_collect(cx, expr, arglists[0]);
715 } else if let Some(arglists) = method_chain_args(expr, &["as_ref"]) {
716 lint_asref(cx, expr, "as_ref", arglists[0]);
717 } else if let Some(arglists) = method_chain_args(expr, &["as_mut"]) {
718 lint_asref(cx, expr, "as_mut", arglists[0]);
721 lint_or_fun_call(cx, expr, &method_call.name.as_str(), args);
723 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
724 if args.len() == 1 && method_call.name == "clone" {
725 lint_clone_on_copy(cx, expr, &args[0], self_ty);
726 lint_clone_on_ref_ptr(cx, expr, &args[0]);
730 ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
731 if method_call.name == method && args.len() > pos {
732 lint_single_char_pattern(cx, expr, &args[pos]);
738 hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
739 let mut info = BinaryExprInfo {
743 eq: op.node == hir::BiEq,
745 lint_binary_expr_with_method_call(cx, &mut info);
751 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
752 if in_external_macro(cx, implitem.span) {
755 let name = implitem.name;
756 let parent = cx.tcx.hir.get_parent(implitem.id);
757 let item = cx.tcx.hir.expect_item(parent);
759 if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
760 if let Some(first_arg_ty) = sig.decl.inputs.get(0);
761 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
762 if let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node;
764 if cx.access_levels.is_exported(implitem.id) {
765 // check missing trait implementations
766 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
767 if name == method_name &&
768 sig.decl.inputs.len() == n_args &&
769 out_type.matches(&sig.decl.output) &&
770 self_kind.matches(first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
771 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
772 "defining a method called `{}` on this type; consider implementing \
773 the `{}` trait or choosing a less ambiguous name", name, trait_name));
778 // check conventions w.r.t. conversion method names and predicates
779 let def_id = cx.tcx.hir.local_def_id(item.id);
780 let ty = cx.tcx.type_of(def_id);
781 let is_copy = is_copy(cx, ty);
782 for &(ref conv, self_kinds) in &CONVENTIONS {
784 if conv.check(&name.as_str());
787 .any(|k| k.matches(first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
789 let lint = if item.vis == hir::Visibility::Public {
790 WRONG_PUB_SELF_CONVENTION
792 WRONG_SELF_CONVENTION
797 &format!("methods called `{}` usually take {}; consider choosing a less \
801 .map(|k| k.description())
808 let ret_ty = return_ty(cx, implitem.id);
810 !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
814 "methods called `new` usually return `Self`");
821 /// Checks for the `OR_FUN_CALL` lint.
822 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[hir::Expr]) {
823 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
824 fn check_unwrap_or_default(
828 self_expr: &hir::Expr,
837 if name == "unwrap_or" {
838 if let hir::ExprPath(ref qpath) = fun.node {
839 let path = &*last_path_segment(qpath).name.as_str();
841 if ["default", "new"].contains(&path) {
842 let arg_ty = cx.tables.expr_ty(arg);
843 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
849 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
854 &format!("use of `{}` followed by a call to `{}`", name, path),
856 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
867 /// Check for `*or(foo())`.
868 fn check_general_case(
872 self_expr: &hir::Expr,
877 // (path, fn_has_argument, methods, suffix)
878 let know_types: &[(&[_], _, &[_], _)] = &[
879 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
880 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
881 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
882 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
885 // early check if the name is one we care about
886 if know_types.iter().all(|k| !k.2.contains(&name)) {
890 // don't lint for constant values
891 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
892 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
897 let self_ty = cx.tables.expr_ty(self_expr);
899 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
900 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
902 (fn_has_arguments, poss, suffix)
907 if !poss.contains(&name) {
911 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
912 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
913 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
914 (false, true) => snippet(cx, fun_span, ".."),
921 &format!("use of `{}` followed by a function call", name),
923 format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg),
929 hir::ExprCall(ref fun, ref or_args) => {
930 let or_has_args = !or_args.is_empty();
931 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
932 check_general_case(cx, name, fun.span, &args[0], &args[1], or_has_args, expr.span);
935 hir::ExprMethodCall(_, span, ref or_args) => {
936 check_general_case(cx, name, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
943 /// Checks for the `CLONE_ON_COPY` lint.
944 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
945 let ty = cx.tables.expr_ty(expr);
946 if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
947 if let ty::TyRef(_, ty::TypeAndMut { ty: innermost, .. }) = inner.sty {
952 "using `clone` on a double-reference; \
953 this will copy the reference instead of cloning the inner type",
954 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
955 let mut ty = innermost;
957 while let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = ty.sty {
961 let refs: String = iter::repeat('&').take(n + 1).collect();
962 let derefs: String = iter::repeat('*').take(n).collect();
963 let explicit = format!("{}{}::clone({})", refs, ty, snip);
964 db.span_suggestion(expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()));
965 db.span_suggestion(expr.span, "or try being explicit about what type to clone", explicit);
968 return; // don't report clone_on_copy
974 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
975 if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
976 let parent = cx.tcx.hir.get_parent_node(expr.id);
977 match cx.tcx.hir.get(parent) {
978 hir::map::NodeExpr(parent) => match parent.node {
979 // &*x is a nop, &x.clone() is not
980 hir::ExprAddrOf(..) |
981 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
982 hir::ExprMethodCall(..) => return,
985 hir::map::NodeStmt(stmt) => {
986 if let hir::StmtDecl(ref decl, _) = stmt.node {
987 if let hir::DeclLocal(ref loc) = decl.node {
988 if let hir::PatKind::Ref(..) = loc.pat.node {
989 // let ref y = *x borrows x, let ref y = x.clone() does not
997 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
999 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1004 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1005 if let Some((text, snip)) = snip {
1006 db.span_suggestion(expr.span, text, snip);
1012 fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1013 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(arg));
1015 if let ty::TyAdt(_, subst) = obj_ty.sty {
1016 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1018 } else if match_type(cx, obj_ty, &paths::ARC) {
1020 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1030 "using '.clone()' on a ref-counted pointer",
1032 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1038 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1040 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1041 let target = &arglists[0][0];
1042 let (self_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(target));
1043 let ref_str = if self_ty.sty == ty::TyStr {
1045 } else if match_type(cx, self_ty, &paths::STRING) {
1053 STRING_EXTEND_CHARS,
1055 "calling `.extend(_.chars())`",
1058 "{}.push_str({}{})",
1059 snippet(cx, args[0].span, "_"),
1061 snippet(cx, target.span, "_")
1067 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
1068 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&args[0]));
1069 if match_type(cx, obj_ty, &paths::STRING) {
1070 lint_string_extend(cx, expr, args);
1074 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1076 if let hir::ExprCall(ref fun, ref args) = new.node;
1078 if let hir::ExprPath(ref path) = fun.node;
1079 if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1080 if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1084 TEMPORARY_CSTRING_AS_PTR,
1086 "you are getting the inner pointer of a temporary `CString`",
1088 db.note("that pointer will be invalid outside this expression");
1089 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1095 fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1096 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1097 && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1101 ITER_CLONED_COLLECT,
1103 "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1109 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1110 let mut_str = if is_mut { "_mut" } else { "" };
1111 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1113 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1115 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1118 return; // caller is not a type that we want to lint
1126 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1133 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1134 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1135 // because they do not implement `IndexMut`
1136 let expr_ty = cx.tables.expr_ty(&get_args[0]);
1137 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1139 } else if match_type(cx, expr_ty, &paths::VEC) {
1141 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1143 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1145 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1148 return; // caller is not a type that we want to lint
1151 let mut_str = if is_mut { "_mut" } else { "" };
1152 let borrow_str = if is_mut { "&mut " } else { "&" };
1158 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1166 snippet(cx, get_args[0].span, "_"),
1167 snippet(cx, get_args[1].span, "_")
1172 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
1173 // lint if caller of skip is an Iterator
1174 if match_trait_method(cx, expr, &paths::ITERATOR) {
1179 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1184 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
1185 fn may_slice(cx: &LateContext, ty: Ty) -> bool {
1187 ty::TySlice(_) => true,
1188 ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1189 ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1190 ty::TyArray(_, size) => const_to_u64(size) < 32,
1191 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => may_slice(cx, inner),
1196 if let hir::ExprMethodCall(ref path, _, ref args) = expr.node {
1197 if path.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1198 sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1204 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1205 ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1206 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => if may_slice(cx, inner) {
1207 sugg::Sugg::hir_opt(cx, expr)
1216 /// lint use of `unwrap()` for `Option`s and `Result`s
1217 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1218 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&unwrap_args[0]));
1220 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1221 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1222 } else if match_type(cx, obj_ty, &paths::RESULT) {
1223 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1228 if let Some((lint, kind, none_value)) = mess {
1234 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1235 using expect() to provide a better panic \
1244 /// lint use of `ok().expect()` for `Result`s
1245 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1246 // lint if the caller of `ok()` is a `Result`
1247 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1248 let result_type = cx.tables.expr_ty(&ok_args[0]);
1249 if let Some(error_type) = get_error_type(cx, result_type) {
1250 if has_debug_impl(error_type, cx) {
1255 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1262 /// lint use of `map().unwrap_or()` for `Option`s
1263 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1264 // lint if the caller of `map()` is an `Option`
1265 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1266 // get snippets for args to map() and unwrap_or()
1267 let map_snippet = snippet(cx, map_args[1].span, "..");
1268 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1270 // comparing the snippet from source to raw text ("None") below is safe
1271 // because we already have checked the type.
1272 let arg = if unwrap_snippet == "None" {
1277 let suggest = if unwrap_snippet == "None" {
1283 "called `map(f).unwrap_or({})` on an Option value. \
1284 This can be done more directly by calling `{}` instead",
1288 // lint, with note if neither arg is > 1 line and both map() and
1289 // unwrap_or() have the same span
1290 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1291 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1292 if same_span && !multiline {
1293 let suggest = if unwrap_snippet == "None" {
1294 format!("and_then({})", map_snippet)
1296 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1299 "replace `map({}).unwrap_or({})` with `{}`",
1304 span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, ¬e);
1305 } else if same_span && multiline {
1306 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1311 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1312 fn lint_map_unwrap_or_else<'a, 'tcx>(
1313 cx: &LateContext<'a, 'tcx>,
1314 expr: &'tcx hir::Expr,
1315 map_args: &'tcx [hir::Expr],
1316 unwrap_args: &'tcx [hir::Expr],
1318 // lint if the caller of `map()` is an `Option`
1319 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1320 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1321 if is_option || is_result {
1323 let msg = if is_option {
1324 "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1325 `map_or_else(g, f)` instead"
1327 "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1328 `ok().map_or_else(g, f)` instead"
1330 // get snippets for args to map() and unwrap_or_else()
1331 let map_snippet = snippet(cx, map_args[1].span, "..");
1332 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1333 // lint, with note if neither arg is > 1 line and both map() and
1334 // unwrap_or_else() have the same span
1335 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1336 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1337 if same_span && !multiline {
1341 OPTION_MAP_UNWRAP_OR_ELSE
1343 RESULT_MAP_UNWRAP_OR_ELSE
1349 "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1352 if is_result { "ok()." } else { "" }
1355 } else if same_span && multiline {
1359 OPTION_MAP_UNWRAP_OR_ELSE
1361 RESULT_MAP_UNWRAP_OR_ELSE
1370 /// lint use of `_.map_or(None, _)` for `Option`s
1371 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1372 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1373 // check if the first non-self argument to map_or() is None
1374 let map_or_arg_is_none = if let hir::Expr_::ExprPath(ref qpath) = map_or_args[1].node {
1375 match_qpath(qpath, &paths::OPTION_NONE)
1380 if map_or_arg_is_none {
1382 let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1383 `and_then(f)` instead";
1384 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1385 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1386 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1387 span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1388 db.span_suggestion(expr.span, "try using and_then instead", hint);
1394 /// lint use of `filter().next()` for `Iterators`
1395 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1396 // lint if caller of `.filter().next()` is an Iterator
1397 if match_trait_method(cx, expr, &paths::ITERATOR) {
1398 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1399 `.find(p)` instead.";
1400 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1401 if filter_snippet.lines().count() <= 1 {
1402 // add note if not multi-line
1409 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1412 span_lint(cx, FILTER_NEXT, expr.span, msg);
1417 /// lint use of `filter().map()` for `Iterators`
1418 fn lint_filter_map<'a, 'tcx>(
1419 cx: &LateContext<'a, 'tcx>,
1420 expr: &'tcx hir::Expr,
1421 _filter_args: &'tcx [hir::Expr],
1422 _map_args: &'tcx [hir::Expr],
1424 // lint if caller of `.filter().map()` is an Iterator
1425 if match_trait_method(cx, expr, &paths::ITERATOR) {
1426 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1427 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1428 span_lint(cx, FILTER_MAP, expr.span, msg);
1432 /// lint use of `filter().map()` for `Iterators`
1433 fn lint_filter_map_map<'a, 'tcx>(
1434 cx: &LateContext<'a, 'tcx>,
1435 expr: &'tcx hir::Expr,
1436 _filter_args: &'tcx [hir::Expr],
1437 _map_args: &'tcx [hir::Expr],
1439 // lint if caller of `.filter().map()` is an Iterator
1440 if match_trait_method(cx, expr, &paths::ITERATOR) {
1441 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1442 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1443 span_lint(cx, FILTER_MAP, expr.span, msg);
1447 /// lint use of `filter().flat_map()` for `Iterators`
1448 fn lint_filter_flat_map<'a, 'tcx>(
1449 cx: &LateContext<'a, 'tcx>,
1450 expr: &'tcx hir::Expr,
1451 _filter_args: &'tcx [hir::Expr],
1452 _map_args: &'tcx [hir::Expr],
1454 // lint if caller of `.filter().flat_map()` is an Iterator
1455 if match_trait_method(cx, expr, &paths::ITERATOR) {
1456 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1457 This is more succinctly expressed by calling `.flat_map(..)` \
1458 and filtering by returning an empty Iterator.";
1459 span_lint(cx, FILTER_MAP, expr.span, msg);
1463 /// lint use of `filter_map().flat_map()` for `Iterators`
1464 fn lint_filter_map_flat_map<'a, 'tcx>(
1465 cx: &LateContext<'a, 'tcx>,
1466 expr: &'tcx hir::Expr,
1467 _filter_args: &'tcx [hir::Expr],
1468 _map_args: &'tcx [hir::Expr],
1470 // lint if caller of `.filter_map().flat_map()` is an Iterator
1471 if match_trait_method(cx, expr, &paths::ITERATOR) {
1472 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1473 This is more succinctly expressed by calling `.flat_map(..)` \
1474 and filtering by returning an empty Iterator.";
1475 span_lint(cx, FILTER_MAP, expr.span, msg);
1479 /// lint searching an Iterator followed by `is_some()`
1480 fn lint_search_is_some<'a, 'tcx>(
1481 cx: &LateContext<'a, 'tcx>,
1482 expr: &'tcx hir::Expr,
1483 search_method: &str,
1484 search_args: &'tcx [hir::Expr],
1485 is_some_args: &'tcx [hir::Expr],
1487 // lint if caller of search is an Iterator
1488 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1490 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1491 expressed by calling `any()`.",
1494 let search_snippet = snippet(cx, search_args[1].span, "..");
1495 if search_snippet.lines().count() <= 1 {
1496 // add note if not multi-line
1503 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1506 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1511 /// Used for `lint_binary_expr_with_method_call`.
1512 #[derive(Copy, Clone)]
1513 struct BinaryExprInfo<'a> {
1514 expr: &'a hir::Expr,
1515 chain: &'a hir::Expr,
1516 other: &'a hir::Expr,
1520 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1521 fn lint_binary_expr_with_method_call<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, info: &mut BinaryExprInfo) {
1522 macro_rules! lint_with_both_lhs_and_rhs {
1523 ($func:ident, $cx:expr, $info:ident) => {
1524 if !$func($cx, $info) {
1525 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1526 if $func($cx, $info) {
1533 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1534 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1535 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1536 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1539 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1540 fn lint_chars_cmp<'a, 'tcx>(
1541 cx: &LateContext<'a, 'tcx>,
1542 info: &BinaryExprInfo,
1543 chain_methods: &[&str],
1544 lint: &'static Lint,
1548 if let Some(args) = method_chain_args(info.chain, chain_methods);
1549 if let hir::ExprCall(ref fun, ref arg_char) = info.other.node;
1550 if arg_char.len() == 1;
1551 if let hir::ExprPath(ref qpath) = fun.node;
1552 if let Some(segment) = single_segment_path(qpath);
1553 if segment.name == "Some";
1555 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1557 if self_ty.sty != ty::TyStr {
1561 span_lint_and_sugg(cx,
1564 &format!("you should use the `{}` method", suggest),
1566 format!("{}{}.{}({})",
1567 if info.eq { "" } else { "!" },
1568 snippet(cx, args[0][0].span, "_"),
1570 snippet(cx, arg_char[0].span, "_")));
1579 /// Checks for the `CHARS_NEXT_CMP` lint.
1580 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1581 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1584 /// Checks for the `CHARS_LAST_CMP` lint.
1585 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1586 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1589 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1593 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1594 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1595 cx: &LateContext<'a, 'tcx>,
1596 info: &BinaryExprInfo,
1597 chain_methods: &[&str],
1598 lint: &'static Lint,
1602 if let Some(args) = method_chain_args(info.chain, chain_methods);
1603 if let hir::ExprLit(ref lit) = info.other.node;
1604 if let ast::LitKind::Char(c) = lit.node;
1610 &format!("you should use the `{}` method", suggest),
1612 format!("{}{}.{}('{}')",
1613 if info.eq { "" } else { "!" },
1614 snippet(cx, args[0][0].span, "_"),
1626 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
1627 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1628 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
1631 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
1632 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
1633 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
1636 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
1640 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1641 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
1642 let parent_item = cx.tcx.hir.get_parent(arg.id);
1643 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1644 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1645 if let Ok(&ty::Const {
1646 val: ConstVal::Str(r),
1648 }) = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(arg)
1651 let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1654 SINGLE_CHAR_PATTERN,
1656 "single-character string constant used as pattern",
1658 db.span_suggestion(expr.span, "try using a char instead", hint);
1665 /// Checks for the `USELESS_ASREF` lint.
1666 fn lint_asref(cx: &LateContext, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
1667 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
1668 // check if the call is to the actual `AsRef` or `AsMut` trait
1669 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
1670 // check if the type after `as_ref` or `as_mut` is the same as before
1671 let recvr = &as_ref_args[0];
1672 let rcv_ty = cx.tables.expr_ty(recvr);
1673 let res_ty = cx.tables.expr_ty(expr);
1674 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
1675 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
1676 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
1681 &format!("this call to `{}` does nothing", call_name),
1683 snippet(cx, recvr.span, "_").into_owned(),
1689 /// Given a `Result<T, E>` type, return its error type (`E`).
1690 fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
1691 if let ty::TyAdt(_, substs) = ty.sty {
1692 if match_type(cx, ty, &paths::RESULT) {
1693 substs.types().nth(1)
1702 /// This checks whether a given type is known to implement Debug.
1703 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1704 match cx.tcx.lang_items().debug_trait() {
1705 Some(debug) => implements_trait(cx, ty, debug, &[]),
1712 StartsWith(&'static str),
1715 #[cfg_attr(rustfmt, rustfmt_skip)]
1716 const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
1717 (Convention::Eq("new"), &[SelfKind::No]),
1718 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1719 (Convention::StartsWith("from_"), &[SelfKind::No]),
1720 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1721 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1722 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1725 #[cfg_attr(rustfmt, rustfmt_skip)]
1726 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
1727 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1728 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1729 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1730 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1731 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1732 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1733 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1734 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1735 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1736 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1737 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1738 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1739 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1740 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1741 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1742 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1743 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1744 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1745 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1746 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1747 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1748 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1749 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1750 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1751 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1752 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1753 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1754 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1755 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1756 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1759 #[cfg_attr(rustfmt, rustfmt_skip)]
1760 const PATTERN_METHODS: [(&str, usize); 17] = [
1768 ("split_terminator", 1),
1769 ("rsplit_terminator", 1),
1774 ("match_indices", 1),
1775 ("rmatch_indices", 1),
1776 ("trim_left_matches", 1),
1777 ("trim_right_matches", 1),
1781 #[derive(Clone, Copy, PartialEq, Debug)]
1795 allow_value_for_ref: bool,
1796 generics: &hir::Generics,
1798 // Self types in the HIR are desugared to explicit self types. So it will
1801 // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
1802 // the impl is on `Foo`)
1803 // Thus, we only need to test equality against the impl self type or if it is
1805 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
1806 // `Self`, `&mut Self`,
1807 // and `Box<Self>`, including the equivalent types with `Foo`.
1809 let is_actually_self = |ty| is_self_ty(ty) || ty == self_ty;
1812 SelfKind::Value => is_actually_self(ty),
1813 SelfKind::Ref | SelfKind::RefMut => {
1814 if allow_value_for_ref && is_actually_self(ty) {
1818 hir::TyRptr(_, ref mt_ty) => {
1819 let mutability_match = if self == SelfKind::Ref {
1820 mt_ty.mutbl == hir::MutImmutable
1822 mt_ty.mutbl == hir::MutMutable
1824 is_actually_self(&mt_ty.ty) && mutability_match
1833 SelfKind::Value => false,
1834 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
1835 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
1836 SelfKind::No => true,
1841 fn description(&self) -> &'static str {
1843 SelfKind::Value => "self by value",
1844 SelfKind::Ref => "self by reference",
1845 SelfKind::RefMut => "self by mutable reference",
1846 SelfKind::No => "no self",
1851 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
1852 single_segment_ty(ty).map_or(false, |seg| {
1853 generics.ty_params().any(|param| {
1854 param.name == seg.name && param.bounds.iter().any(|bound| {
1855 if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
1856 let path = &ptr.trait_ref.path;
1857 match_path(path, name) && path.segments.last().map_or(false, |s| {
1858 if let Some(ref params) = s.parameters {
1859 if params.parenthesized {
1862 params.types.len() == 1
1863 && (is_self_ty(¶ms.types[0]) || is_ty(&*params.types[0], self_ty))
1877 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
1878 match (&ty.node, &self_ty.node) {
1880 &hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
1881 &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path)),
1885 .map(|seg| seg.name)
1886 .eq(self_ty_path.segments.iter().map(|seg| seg.name)),
1891 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
1892 if let hir::TyPath(ref path) = ty.node {
1893 single_segment_path(path)
1900 fn check(&self, other: &str) -> bool {
1902 Convention::Eq(this) => this == other,
1903 Convention::StartsWith(this) => other.starts_with(this) && this != other,
1908 impl fmt::Display for Convention {
1909 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1911 Convention::Eq(this) => this.fmt(f),
1912 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1917 #[derive(Clone, Copy)]
1926 fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1928 (&OutType::Unit, &hir::DefaultReturn(_)) => true,
1929 (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
1930 (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
1931 (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
1932 (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
1938 fn is_bool(ty: &hir::Ty) -> bool {
1939 if let hir::TyPath(ref p) = ty.node {
1940 match_qpath(p, &["bool"])