4 use rustc::{declare_lint, lint_array};
5 use if_chain::if_chain;
6 use rustc::ty::{self, Ty};
7 use rustc::hir::def::Def;
12 use syntax::codemap::{Span, BytePos};
13 use crate::utils::{get_arg_name, get_trait_def_id, implements_trait, in_macro, is_copy, is_expn_of, is_self,
14 is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
15 match_type, method_chain_args, match_var, return_ty, remove_blocks, same_tys, single_segment_path, snippet,
16 span_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq};
17 use crate::utils::paths;
18 use crate::utils::sugg;
19 use crate::consts::{constant, Constant};
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.
37 declare_clippy_lint! {
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.
59 declare_clippy_lint! {
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 { .. }
85 declare_clippy_lint! {
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 { .. }
114 declare_clippy_lint! {
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 { .. }
136 declare_clippy_lint! {
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:** The error type needs to implement `Debug`
152 /// x.ok().expect("why did I do this again?")
154 declare_clippy_lint! {
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:** The order of the arguments is not in execution order
170 /// x.map(|a| a + 1).unwrap_or(0)
172 declare_clippy_lint! {
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:** The order of the arguments is not in execution order.
188 /// x.map(|a| a + 1).unwrap_or_else(some_function)
190 declare_clippy_lint! {
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)
208 declare_clippy_lint! {
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:** The order of the arguments is not in execution order.
224 /// opt.map_or(None, |a| a + 1)
226 declare_clippy_lint! {
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()
244 declare_clippy_lint! {
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)
263 declare_clippy_lint! {
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()
282 declare_clippy_lint! {
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('_')
301 declare_clippy_lint! {
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()
329 declare_clippy_lint! {
332 "using any `*or` method with a function call, which suggests `*or_else`"
335 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
336 /// etc., and suggests to use `unwrap_or_else` instead
338 /// **Why is this bad?** The function will always be called.
340 /// **Known problems:** If the function has side-effects, not calling it will
341 /// change the semantic of the program, but you shouldn't rely on that anyway.
345 /// foo.expect(&format("Err {}: {}", err_code, err_msg))
349 /// foo.expect(format("Err {}: {}", err_code, err_msg).as_str())
351 /// this can instead be written:
353 /// foo.unwrap_or_else(|_| panic!("Err {}: {}", err_code, err_msg))
357 /// foo.unwrap_or_else(|_| panic!(format("Err {}: {}", err_code, err_msg).as_str()))
359 declare_clippy_lint! {
362 "using any `expect` method with a function call"
365 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
367 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
368 /// generics, not for using the `clone` method on a concrete type.
370 /// **Known problems:** None.
376 declare_clippy_lint! {
379 "using `clone` on a `Copy` type"
382 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
383 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
384 /// function syntax instead (e.g. `Rc::clone(foo)`).
386 /// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
387 /// can obscure the fact that only the pointer is being cloned, not the underlying
394 declare_clippy_lint! {
395 pub CLONE_ON_REF_PTR,
397 "using 'clone' on a ref-counted pointer"
400 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
402 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
403 /// cloning the underlying `T`.
405 /// **Known problems:** None.
412 /// let z = y.clone();
413 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
416 declare_clippy_lint! {
417 pub CLONE_DOUBLE_REF,
419 "using `clone` on `&&T`"
422 /// **What it does:** Checks for `new` not returning `Self`.
424 /// **Why is this bad?** As a convention, `new` methods are used to make a new
425 /// instance of a type.
427 /// **Known problems:** None.
432 /// fn new(..) -> NotAFoo {
436 declare_clippy_lint! {
439 "not returning `Self` in a `new` method"
442 /// **What it does:** Checks for string methods that receive a single-character
443 /// `str` as an argument, e.g. `_.split("x")`.
445 /// **Why is this bad?** Performing these methods using a `char` is faster than
448 /// **Known problems:** Does not catch multi-byte unicode characters.
451 /// `_.split("x")` could be `_.split('x')
452 declare_clippy_lint! {
453 pub SINGLE_CHAR_PATTERN,
455 "using a single-character str where a char could be used, e.g. \
459 /// **What it does:** Checks for getting the inner pointer of a temporary
462 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
463 /// as the `CString` is alive.
465 /// **Known problems:** None.
469 /// let c_str = CString::new("foo").unwrap().as_ptr();
471 /// call_some_ffi_func(c_str);
474 /// Here `c_str` point to a freed address. The correct use would be:
476 /// let c_str = CString::new("foo").unwrap();
478 /// call_some_ffi_func(c_str.as_ptr());
481 declare_clippy_lint! {
482 pub TEMPORARY_CSTRING_AS_PTR,
484 "getting the inner pointer of a temporary `CString`"
487 /// **What it does:** Checks for use of `.iter().nth()` (and the related
488 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
490 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
493 /// **Known problems:** None.
497 /// let some_vec = vec![0, 1, 2, 3];
498 /// let bad_vec = some_vec.iter().nth(3);
499 /// let bad_slice = &some_vec[..].iter().nth(3);
501 /// The correct use would be:
503 /// let some_vec = vec![0, 1, 2, 3];
504 /// let bad_vec = some_vec.get(3);
505 /// let bad_slice = &some_vec[..].get(3);
507 declare_clippy_lint! {
510 "using `.iter().nth()` on a standard library type with O(1) element access"
513 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
515 /// **Why is this bad?** `.nth(x)` is cleaner
517 /// **Known problems:** None.
521 /// let some_vec = vec![0, 1, 2, 3];
522 /// let bad_vec = some_vec.iter().skip(3).next();
523 /// let bad_slice = &some_vec[..].iter().skip(3).next();
525 /// The correct use would be:
527 /// let some_vec = vec![0, 1, 2, 3];
528 /// let bad_vec = some_vec.iter().nth(3);
529 /// let bad_slice = &some_vec[..].iter().nth(3);
531 declare_clippy_lint! {
534 "using `.skip(x).next()` on an iterator"
537 /// **What it does:** Checks for use of `.get().unwrap()` (or
538 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
540 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
543 /// **Known problems:** None.
547 /// let some_vec = vec![0, 1, 2, 3];
548 /// let last = some_vec.get(3).unwrap();
549 /// *some_vec.get_mut(0).unwrap() = 1;
551 /// The correct use would be:
553 /// let some_vec = vec![0, 1, 2, 3];
554 /// let last = some_vec[3];
557 declare_clippy_lint! {
560 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
563 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
564 /// `&str` or `String`.
566 /// **Why is this bad?** `.push_str(s)` is clearer
568 /// **Known problems:** None.
573 /// let def = String::from("def");
574 /// let mut s = String::new();
575 /// s.extend(abc.chars());
576 /// s.extend(def.chars());
578 /// The correct use would be:
581 /// let def = String::from("def");
582 /// let mut s = String::new();
584 /// s.push_str(&def));
586 declare_clippy_lint! {
587 pub STRING_EXTEND_CHARS,
589 "using `x.extend(s.chars())` where s is a `&str` or `String`"
592 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
595 /// **Why is this bad?** `.to_vec()` is clearer
597 /// **Known problems:** None.
601 /// let s = [1,2,3,4,5];
602 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
604 /// The better use would be:
606 /// let s = [1,2,3,4,5];
607 /// let s2 : Vec<isize> = s.to_vec();
609 declare_clippy_lint! {
610 pub ITER_CLONED_COLLECT,
612 "using `.cloned().collect()` on slice to create a `Vec`"
615 /// **What it does:** Checks for usage of `.chars().last()` or
616 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
618 /// **Why is this bad?** Readability, this can be written more concisely as
619 /// `_.ends_with(_)`.
621 /// **Known problems:** None.
625 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
627 declare_clippy_lint! {
630 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
633 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
634 /// types before and after the call are the same.
636 /// **Why is this bad?** The call is unnecessary.
638 /// **Known problems:** None.
642 /// let x: &[i32] = &[1,2,3,4,5];
643 /// do_stuff(x.as_ref());
645 /// The correct use would be:
647 /// let x: &[i32] = &[1,2,3,4,5];
650 declare_clippy_lint! {
653 "using `as_ref` where the types before and after the call are the same"
657 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
658 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
659 /// `sum` or `product`.
661 /// **Why is this bad?** Readability.
663 /// **Known problems:** None.
667 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
669 /// This could be written as:
671 /// let _ = (0..3).any(|x| x > 2);
673 declare_clippy_lint! {
674 pub UNNECESSARY_FOLD,
676 "using `fold` when a more succinct alternative exists"
679 impl LintPass for Pass {
680 fn get_lints(&self) -> LintArray {
684 SHOULD_IMPLEMENT_TRAIT,
685 WRONG_SELF_CONVENTION,
686 WRONG_PUB_SELF_CONVENTION,
688 OPTION_MAP_UNWRAP_OR,
689 OPTION_MAP_UNWRAP_OR_ELSE,
690 RESULT_MAP_UNWRAP_OR_ELSE,
702 TEMPORARY_CSTRING_AS_PTR,
716 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
717 #[allow(cyclomatic_complexity)]
718 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
719 if in_macro(expr.span) {
724 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
726 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
727 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
728 lint_get_unwrap(cx, expr, arglists[0], false);
729 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
730 lint_get_unwrap(cx, expr, arglists[0], true);
731 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
732 lint_unwrap(cx, expr, arglists[0]);
733 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
734 lint_ok_expect(cx, expr, arglists[0]);
735 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
736 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
737 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
738 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
739 } else if let Some(arglists) = method_chain_args(expr, &["map_or"]) {
740 lint_map_or_none(cx, expr, arglists[0]);
741 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
742 lint_filter_next(cx, expr, arglists[0]);
743 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
744 lint_filter_map(cx, expr, arglists[0], arglists[1]);
745 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
746 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
747 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
748 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
749 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
750 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
751 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
752 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
753 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
754 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
755 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
756 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
757 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
758 lint_extend(cx, expr, arglists[0]);
759 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
760 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
761 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
762 lint_iter_nth(cx, expr, arglists[0], false);
763 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
764 lint_iter_nth(cx, expr, arglists[0], true);
765 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
766 lint_iter_skip_next(cx, expr);
767 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
768 lint_iter_cloned_collect(cx, expr, arglists[0]);
769 } else if let Some(arglists) = method_chain_args(expr, &["as_ref"]) {
770 lint_asref(cx, expr, "as_ref", arglists[0]);
771 } else if let Some(arglists) = method_chain_args(expr, &["as_mut"]) {
772 lint_asref(cx, expr, "as_mut", arglists[0]);
773 } else if let Some(arglists) = method_chain_args(expr, &["fold"]) {
774 lint_unnecessary_fold(cx, expr, arglists[0]);
777 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
778 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
780 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
781 if args.len() == 1 && method_call.ident.name == "clone" {
782 lint_clone_on_copy(cx, expr, &args[0], self_ty);
783 lint_clone_on_ref_ptr(cx, expr, &args[0]);
787 ty::TyRef(_, ty, _) if ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
788 if method_call.ident.name == method && args.len() > pos {
789 lint_single_char_pattern(cx, expr, &args[pos]);
795 hir::ExprKind::Binary(op, ref lhs, ref rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
796 let mut info = BinaryExprInfo {
800 eq: op.node == hir::BinOpKind::Eq,
802 lint_binary_expr_with_method_call(cx, &mut info);
808 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
809 if in_external_macro(cx.sess(), implitem.span) {
812 let name = implitem.ident.name;
813 let parent = cx.tcx.hir.get_parent(implitem.id);
814 let item = cx.tcx.hir.expect_item(parent);
816 if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
817 if let Some(first_arg_ty) = sig.decl.inputs.get(0);
818 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
819 if let hir::ItemKind::Impl(_, _, _, _, None, ref self_ty, _) = item.node;
821 if cx.access_levels.is_exported(implitem.id) {
822 // check missing trait implementations
823 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
824 if name == method_name &&
825 sig.decl.inputs.len() == n_args &&
826 out_type.matches(cx, &sig.decl.output) &&
827 self_kind.matches(cx, first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
828 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
829 "defining a method called `{}` on this type; consider implementing \
830 the `{}` trait or choosing a less ambiguous name", name, trait_name));
835 // check conventions w.r.t. conversion method names and predicates
836 let def_id = cx.tcx.hir.local_def_id(item.id);
837 let ty = cx.tcx.type_of(def_id);
838 let is_copy = is_copy(cx, ty);
839 for &(ref conv, self_kinds) in &CONVENTIONS {
841 if conv.check(&name.as_str());
844 .any(|k| k.matches(cx, first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics));
846 let lint = if item.vis.node.is_pub() {
847 WRONG_PUB_SELF_CONVENTION
849 WRONG_SELF_CONVENTION
854 &format!("methods called `{}` usually take {}; consider choosing a less \
858 .map(|k| k.description())
865 let ret_ty = return_ty(cx, implitem.id);
867 !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
871 "methods called `new` usually return `Self`");
878 /// Checks for the `OR_FUN_CALL` lint.
879 fn lint_or_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
880 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
881 fn check_unwrap_or_default(
882 cx: &LateContext<'_, '_>,
885 self_expr: &hir::Expr,
894 if name == "unwrap_or" {
895 if let hir::ExprKind::Path(ref qpath) = fun.node {
896 let path = &*last_path_segment(qpath).ident.as_str();
898 if ["default", "new"].contains(&path) {
899 let arg_ty = cx.tables.expr_ty(arg);
900 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
906 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
911 &format!("use of `{}` followed by a call to `{}`", name, path),
913 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
924 /// Check for `*or(foo())`.
925 #[allow(too_many_arguments)]
926 fn check_general_case(
927 cx: &LateContext<'_, '_>,
931 self_expr: &hir::Expr,
936 // (path, fn_has_argument, methods, suffix)
937 let know_types: &[(&[_], _, &[_], _)] = &[
938 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
939 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
940 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
941 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
944 // early check if the name is one we care about
945 if know_types.iter().all(|k| !k.2.contains(&name)) {
949 // don't lint for constant values
950 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
951 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
956 let self_ty = cx.tables.expr_ty(self_expr);
958 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
959 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
961 (fn_has_arguments, poss, suffix)
966 if !poss.contains(&name) {
970 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
971 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
972 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
973 (false, true) => snippet(cx, fun_span, ".."),
975 let span_replace_word = method_span.with_hi(span.hi());
980 &format!("use of `{}` followed by a function call", name),
982 format!("{}_{}({})", name, suffix, sugg),
988 hir::ExprKind::Call(ref fun, ref or_args) => {
989 let or_has_args = !or_args.is_empty();
990 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
991 check_general_case(cx, name, method_span, fun.span, &args[0], &args[1], or_has_args, expr.span);
994 hir::ExprKind::MethodCall(_, span, ref or_args) => {
995 check_general_case(cx, name, method_span, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
1002 /// Checks for the `EXPECT_FUN_CALL` lint.
1003 fn lint_expect_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
1004 fn extract_format_args(arg: &hir::Expr) -> Option<&hir::HirVec<hir::Expr>> {
1005 if let hir::ExprKind::AddrOf(_, ref addr_of) = arg.node {
1006 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = addr_of.node {
1007 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1 {
1008 if let hir::ExprKind::Call(_, ref format_args) = inner_args[0].node {
1009 return Some(format_args);
1018 fn generate_format_arg_snippet(cx: &LateContext<'_, '_>, a: &hir::Expr) -> String {
1019 if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
1020 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
1021 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
1022 return snippet(cx, format_arg_expr_tup[0].span, "..").into_owned();
1027 snippet(cx, a.span, "..").into_owned()
1030 fn check_general_case(
1031 cx: &LateContext<'_, '_>,
1034 self_expr: &hir::Expr,
1038 if name != "expect" {
1042 let self_type = cx.tables.expr_ty(self_expr);
1043 let known_types = &[&paths::OPTION, &paths::RESULT];
1045 // if not a known type, return early
1046 if known_types.iter().all(|&k| !match_type(cx, self_type, k)) {
1050 // don't lint for constant values
1051 let owner_def = cx.tcx.hir.get_parent_did(arg.id);
1052 let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
1057 let closure = if match_type(cx, self_type, &paths::OPTION) { "||" } else { "|_|" };
1058 let span_replace_word = method_span.with_hi(span.hi());
1060 if let Some(format_args) = extract_format_args(arg) {
1061 let args_len = format_args.len();
1062 let args: Vec<String> = format_args
1065 .map(|a| generate_format_arg_snippet(cx, a))
1068 let sugg = args.join(", ");
1074 &format!("use of `{}` followed by a function call", name),
1076 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1082 let sugg: Cow<'_, _> = snippet(cx, arg.span, "..");
1088 &format!("use of `{}` followed by a function call", name),
1090 format!("unwrap_or_else({} panic!({}))", closure, sugg),
1094 if args.len() == 2 {
1095 match args[1].node {
1096 hir::ExprKind::Lit(_) => {},
1097 _ => check_general_case(cx, name, method_span, &args[0], &args[1], expr.span),
1102 /// Checks for the `CLONE_ON_COPY` lint.
1103 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty<'_>) {
1104 let ty = cx.tables.expr_ty(expr);
1105 if let ty::TyRef(_, inner, _) = arg_ty.sty {
1106 if let ty::TyRef(_, innermost, _) = inner.sty {
1111 "using `clone` on a double-reference; \
1112 this will copy the reference instead of cloning the inner type",
1113 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1114 let mut ty = innermost;
1116 while let ty::TyRef(_, inner, _) = ty.sty {
1120 let refs: String = iter::repeat('&').take(n + 1).collect();
1121 let derefs: String = iter::repeat('*').take(n).collect();
1122 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1123 db.span_suggestion(expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()));
1124 db.span_suggestion(expr.span, "or try being explicit about what type to clone", explicit);
1127 return; // don't report clone_on_copy
1131 if is_copy(cx, ty) {
1133 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1134 if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
1135 let parent = cx.tcx.hir.get_parent_node(expr.id);
1136 match cx.tcx.hir.get(parent) {
1137 hir::map::NodeExpr(parent) => match parent.node {
1138 // &*x is a nop, &x.clone() is not
1139 hir::ExprKind::AddrOf(..) |
1140 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1141 hir::ExprKind::MethodCall(..) => return,
1144 hir::map::NodeStmt(stmt) => {
1145 if let hir::StmtKind::Decl(ref decl, _) = stmt.node {
1146 if let hir::DeclKind::Local(ref loc) = decl.node {
1147 if let hir::PatKind::Ref(..) = loc.pat.node {
1148 // let ref y = *x borrows x, let ref y = x.clone() does not
1156 snip = Some(("try dereferencing it", format!("{}", snippet.deref())));
1158 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1163 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1164 if let Some((text, snip)) = snip {
1165 db.span_suggestion(expr.span, text, snip);
1171 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr) {
1172 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1174 if let ty::TyAdt(_, subst) = obj_ty.sty {
1175 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1177 } else if match_type(cx, obj_ty, &paths::ARC) {
1179 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1189 "using '.clone()' on a ref-counted pointer",
1191 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1197 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1199 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1200 let target = &arglists[0][0];
1201 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1202 let ref_str = if self_ty.sty == ty::TyStr {
1204 } else if match_type(cx, self_ty, &paths::STRING) {
1212 STRING_EXTEND_CHARS,
1214 "calling `.extend(_.chars())`",
1217 "{}.push_str({}{})",
1218 snippet(cx, args[0].span, "_"),
1220 snippet(cx, target.span, "_")
1226 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1227 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
1228 if match_type(cx, obj_ty, &paths::STRING) {
1229 lint_string_extend(cx, expr, args);
1233 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1235 if let hir::ExprKind::Call(ref fun, ref args) = new.node;
1237 if let hir::ExprKind::Path(ref path) = fun.node;
1238 if let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id);
1239 if match_def_path(cx.tcx, did, &paths::CSTRING_NEW);
1243 TEMPORARY_CSTRING_AS_PTR,
1245 "you are getting the inner pointer of a temporary `CString`",
1247 db.note("that pointer will be invalid outside this expression");
1248 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1254 fn lint_iter_cloned_collect(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr]) {
1255 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
1256 && derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
1260 ITER_CLONED_COLLECT,
1262 "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1268 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1269 // Check that this is a call to Iterator::fold rather than just some function called fold
1270 if !match_trait_method(cx, expr, &paths::ITERATOR) {
1274 assert!(fold_args.len() == 3,
1275 "Expected fold_args to have three entries - the receiver, the initial value and the closure");
1277 fn check_fold_with_op(
1278 cx: &LateContext<'_, '_>,
1279 fold_args: &[hir::Expr],
1281 replacement_method_name: &str,
1282 replacement_has_args: bool) {
1285 // Extract the body of the closure passed to fold
1286 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].node;
1287 let closure_body = cx.tcx.hir.body(body_id);
1288 let closure_expr = remove_blocks(&closure_body.value);
1290 // Check if the closure body is of the form `acc <op> some_expr(x)`
1291 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1292 if bin_op.node == op;
1294 // Extract the names of the two arguments to the closure
1295 if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1296 if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1298 if match_var(&*left_expr, first_arg_ident);
1299 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1302 // Span containing `.fold(...)`
1303 let next_point = cx.sess().codemap().next_point(fold_args[0].span);
1304 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1306 let sugg = if replacement_has_args {
1308 ".{replacement}(|{s}| {r})",
1309 replacement = replacement_method_name,
1310 s = second_arg_ident,
1311 r = snippet(cx, right_expr.span, "EXPR"),
1316 replacement = replacement_method_name,
1324 // TODO #2371 don't suggest e.g. .any(|x| f(x)) if we can suggest .any(f)
1325 "this `.fold` can be written more succinctly using another method",
1333 // Check if the first argument to .fold is a suitable literal
1334 match fold_args[1].node {
1335 hir::ExprKind::Lit(ref lit) => {
1337 ast::LitKind::Bool(false) => check_fold_with_op(
1338 cx, fold_args, hir::BinOpKind::Or, "any", true
1340 ast::LitKind::Bool(true) => check_fold_with_op(
1341 cx, fold_args, hir::BinOpKind::And, "all", true
1343 ast::LitKind::Int(0, _) => check_fold_with_op(
1344 cx, fold_args, hir::BinOpKind::Add, "sum", false
1346 ast::LitKind::Int(1, _) => check_fold_with_op(
1347 cx, fold_args, hir::BinOpKind::Mul, "product", false
1356 fn lint_iter_nth(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
1357 let mut_str = if is_mut { "_mut" } else { "" };
1358 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1360 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1362 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1365 return; // caller is not a type that we want to lint
1373 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1380 fn lint_get_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
1381 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1382 // because they do not implement `IndexMut`
1383 let expr_ty = cx.tables.expr_ty(&get_args[0]);
1384 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1386 } else if match_type(cx, expr_ty, &paths::VEC) {
1388 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1390 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1392 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1395 return; // caller is not a type that we want to lint
1398 let mut_str = if is_mut { "_mut" } else { "" };
1399 let borrow_str = if is_mut { "&mut " } else { "&" };
1405 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1413 snippet(cx, get_args[0].span, "_"),
1414 snippet(cx, get_args[1].span, "_")
1419 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr) {
1420 // lint if caller of skip is an Iterator
1421 if match_trait_method(cx, expr, &paths::ITERATOR) {
1426 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1431 fn derefs_to_slice(cx: &LateContext<'_, '_>, expr: &hir::Expr, ty: Ty<'_>) -> Option<sugg::Sugg<'static>> {
1432 fn may_slice(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1434 ty::TySlice(_) => true,
1435 ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1436 ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1437 ty::TyArray(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
1438 ty::TyRef(_, inner, _) => may_slice(cx, inner),
1443 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.node {
1444 if path.ident.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1445 sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1451 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1452 ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1453 ty::TyRef(_, inner, _) => if may_slice(cx, inner) {
1454 sugg::Sugg::hir_opt(cx, expr)
1463 /// lint use of `unwrap()` for `Option`s and `Result`s
1464 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1465 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
1467 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1468 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1469 } else if match_type(cx, obj_ty, &paths::RESULT) {
1470 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1475 if let Some((lint, kind, none_value)) = mess {
1481 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1482 using expect() to provide a better panic \
1491 /// lint use of `ok().expect()` for `Result`s
1492 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1493 // lint if the caller of `ok()` is a `Result`
1494 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1495 let result_type = cx.tables.expr_ty(&ok_args[0]);
1496 if let Some(error_type) = get_error_type(cx, result_type) {
1497 if has_debug_impl(error_type, cx) {
1502 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1509 /// lint use of `map().unwrap_or()` for `Option`s
1510 fn lint_map_unwrap_or(cx: &LateContext<'_, '_>, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1511 // lint if the caller of `map()` is an `Option`
1512 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1513 // get snippets for args to map() and unwrap_or()
1514 let map_snippet = snippet(cx, map_args[1].span, "..");
1515 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1517 // comparing the snippet from source to raw text ("None") below is safe
1518 // because we already have checked the type.
1519 let arg = if unwrap_snippet == "None" {
1524 let suggest = if unwrap_snippet == "None" {
1530 "called `map(f).unwrap_or({})` on an Option value. \
1531 This can be done more directly by calling `{}` instead",
1535 // lint, with note if neither arg is > 1 line and both map() and
1536 // unwrap_or() have the same span
1537 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1538 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1539 if same_span && !multiline {
1540 let suggest = if unwrap_snippet == "None" {
1541 format!("and_then({})", map_snippet)
1543 format!("map_or({}, {})", unwrap_snippet, map_snippet)
1546 "replace `map({}).unwrap_or({})` with `{}`",
1551 span_note_and_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg, expr.span, ¬e);
1552 } else if same_span && multiline {
1553 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1558 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1559 fn lint_map_unwrap_or_else<'a, 'tcx>(
1560 cx: &LateContext<'a, 'tcx>,
1561 expr: &'tcx hir::Expr,
1562 map_args: &'tcx [hir::Expr],
1563 unwrap_args: &'tcx [hir::Expr],
1565 // lint if the caller of `map()` is an `Option`
1566 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1567 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1568 if is_option || is_result {
1570 let msg = if is_option {
1571 "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1572 `map_or_else(g, f)` instead"
1574 "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1575 `ok().map_or_else(g, f)` instead"
1577 // get snippets for args to map() and unwrap_or_else()
1578 let map_snippet = snippet(cx, map_args[1].span, "..");
1579 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1580 // lint, with note if neither arg is > 1 line and both map() and
1581 // unwrap_or_else() have the same span
1582 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1583 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1584 if same_span && !multiline {
1588 OPTION_MAP_UNWRAP_OR_ELSE
1590 RESULT_MAP_UNWRAP_OR_ELSE
1596 "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1599 if is_result { "ok()." } else { "" }
1602 } else if same_span && multiline {
1606 OPTION_MAP_UNWRAP_OR_ELSE
1608 RESULT_MAP_UNWRAP_OR_ELSE
1617 /// lint use of `_.map_or(None, _)` for `Option`s
1618 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1619 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1620 // check if the first non-self argument to map_or() is None
1621 let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].node {
1622 match_qpath(qpath, &paths::OPTION_NONE)
1627 if map_or_arg_is_none {
1629 let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1630 `and_then(f)` instead";
1631 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1632 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1633 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1634 span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1635 db.span_suggestion(expr.span, "try using and_then instead", hint);
1641 /// lint use of `filter().next()` for `Iterators`
1642 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
1643 // lint if caller of `.filter().next()` is an Iterator
1644 if match_trait_method(cx, expr, &paths::ITERATOR) {
1645 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1646 `.find(p)` instead.";
1647 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1648 if filter_snippet.lines().count() <= 1 {
1649 // add note if not multi-line
1656 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1659 span_lint(cx, FILTER_NEXT, expr.span, msg);
1664 /// lint use of `filter().map()` for `Iterators`
1665 fn lint_filter_map<'a, 'tcx>(
1666 cx: &LateContext<'a, 'tcx>,
1667 expr: &'tcx hir::Expr,
1668 _filter_args: &'tcx [hir::Expr],
1669 _map_args: &'tcx [hir::Expr],
1671 // lint if caller of `.filter().map()` is an Iterator
1672 if match_trait_method(cx, expr, &paths::ITERATOR) {
1673 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1674 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1675 span_lint(cx, FILTER_MAP, expr.span, msg);
1679 /// lint use of `filter().map()` for `Iterators`
1680 fn lint_filter_map_map<'a, 'tcx>(
1681 cx: &LateContext<'a, 'tcx>,
1682 expr: &'tcx hir::Expr,
1683 _filter_args: &'tcx [hir::Expr],
1684 _map_args: &'tcx [hir::Expr],
1686 // lint if caller of `.filter().map()` is an Iterator
1687 if match_trait_method(cx, expr, &paths::ITERATOR) {
1688 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1689 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1690 span_lint(cx, FILTER_MAP, expr.span, msg);
1694 /// lint use of `filter().flat_map()` for `Iterators`
1695 fn lint_filter_flat_map<'a, 'tcx>(
1696 cx: &LateContext<'a, 'tcx>,
1697 expr: &'tcx hir::Expr,
1698 _filter_args: &'tcx [hir::Expr],
1699 _map_args: &'tcx [hir::Expr],
1701 // lint if caller of `.filter().flat_map()` is an Iterator
1702 if match_trait_method(cx, expr, &paths::ITERATOR) {
1703 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1704 This is more succinctly expressed by calling `.flat_map(..)` \
1705 and filtering by returning an empty Iterator.";
1706 span_lint(cx, FILTER_MAP, expr.span, msg);
1710 /// lint use of `filter_map().flat_map()` for `Iterators`
1711 fn lint_filter_map_flat_map<'a, 'tcx>(
1712 cx: &LateContext<'a, 'tcx>,
1713 expr: &'tcx hir::Expr,
1714 _filter_args: &'tcx [hir::Expr],
1715 _map_args: &'tcx [hir::Expr],
1717 // lint if caller of `.filter_map().flat_map()` is an Iterator
1718 if match_trait_method(cx, expr, &paths::ITERATOR) {
1719 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1720 This is more succinctly expressed by calling `.flat_map(..)` \
1721 and filtering by returning an empty Iterator.";
1722 span_lint(cx, FILTER_MAP, expr.span, msg);
1726 /// lint searching an Iterator followed by `is_some()`
1727 fn lint_search_is_some<'a, 'tcx>(
1728 cx: &LateContext<'a, 'tcx>,
1729 expr: &'tcx hir::Expr,
1730 search_method: &str,
1731 search_args: &'tcx [hir::Expr],
1732 is_some_args: &'tcx [hir::Expr],
1734 // lint if caller of search is an Iterator
1735 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1737 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1738 expressed by calling `any()`.",
1741 let search_snippet = snippet(cx, search_args[1].span, "..");
1742 if search_snippet.lines().count() <= 1 {
1743 // add note if not multi-line
1750 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1753 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1758 /// Used for `lint_binary_expr_with_method_call`.
1759 #[derive(Copy, Clone)]
1760 struct BinaryExprInfo<'a> {
1761 expr: &'a hir::Expr,
1762 chain: &'a hir::Expr,
1763 other: &'a hir::Expr,
1767 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
1768 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
1769 macro_rules! lint_with_both_lhs_and_rhs {
1770 ($func:ident, $cx:expr, $info:ident) => {
1771 if !$func($cx, $info) {
1772 ::std::mem::swap(&mut $info.chain, &mut $info.other);
1773 if $func($cx, $info) {
1780 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
1781 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
1782 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
1783 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
1786 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
1788 cx: &LateContext<'_, '_>,
1789 info: &BinaryExprInfo<'_>,
1790 chain_methods: &[&str],
1791 lint: &'static Lint,
1795 if let Some(args) = method_chain_args(info.chain, chain_methods);
1796 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.node;
1797 if arg_char.len() == 1;
1798 if let hir::ExprKind::Path(ref qpath) = fun.node;
1799 if let Some(segment) = single_segment_path(qpath);
1800 if segment.ident.name == "Some";
1802 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1804 if self_ty.sty != ty::TyStr {
1808 span_lint_and_sugg(cx,
1811 &format!("you should use the `{}` method", suggest),
1813 format!("{}{}.{}({})",
1814 if info.eq { "" } else { "!" },
1815 snippet(cx, args[0][0].span, "_"),
1817 snippet(cx, arg_char[0].span, "_")));
1826 /// Checks for the `CHARS_NEXT_CMP` lint.
1827 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1828 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
1831 /// Checks for the `CHARS_LAST_CMP` lint.
1832 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1833 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
1836 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_NEXT_CMP, "ends_with")
1840 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
1841 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
1842 cx: &LateContext<'a, 'tcx>,
1843 info: &BinaryExprInfo<'_>,
1844 chain_methods: &[&str],
1845 lint: &'static Lint,
1849 if let Some(args) = method_chain_args(info.chain, chain_methods);
1850 if let hir::ExprKind::Lit(ref lit) = info.other.node;
1851 if let ast::LitKind::Char(c) = lit.node;
1857 &format!("you should use the `{}` method", suggest),
1859 format!("{}{}.{}('{}')",
1860 if info.eq { "" } else { "!" },
1861 snippet(cx, args[0][0].span, "_"),
1873 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
1874 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1875 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
1878 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
1879 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
1880 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
1883 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
1887 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1888 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
1889 if let Some((Constant::Str(r), _)) = constant(cx, cx.tables, arg) {
1891 let c = r.chars().next().unwrap();
1892 let snip = snippet(cx, expr.span, "..");
1893 let hint = snip.replace(
1894 &format!("\"{}\"", c.escape_default()),
1895 &format!("'{}'", c.escape_default()));
1898 SINGLE_CHAR_PATTERN,
1900 "single-character string constant used as pattern",
1902 db.span_suggestion(expr.span, "try using a char instead", hint);
1909 /// Checks for the `USELESS_ASREF` lint.
1910 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
1911 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
1912 // check if the call is to the actual `AsRef` or `AsMut` trait
1913 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
1914 // check if the type after `as_ref` or `as_mut` is the same as before
1915 let recvr = &as_ref_args[0];
1916 let rcv_ty = cx.tables.expr_ty(recvr);
1917 let res_ty = cx.tables.expr_ty(expr);
1918 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
1919 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
1920 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
1925 &format!("this call to `{}` does nothing", call_name),
1927 snippet(cx, recvr.span, "_").into_owned(),
1933 /// Given a `Result<T, E>` type, return its error type (`E`).
1934 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
1935 if let ty::TyAdt(_, substs) = ty.sty {
1936 if match_type(cx, ty, &paths::RESULT) {
1937 substs.types().nth(1)
1946 /// This checks whether a given type is known to implement Debug.
1947 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1948 match cx.tcx.lang_items().debug_trait() {
1949 Some(debug) => implements_trait(cx, ty, debug, &[]),
1956 StartsWith(&'static str),
1959 #[cfg_attr(rustfmt, rustfmt_skip)]
1960 const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
1961 (Convention::Eq("new"), &[SelfKind::No]),
1962 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1963 (Convention::StartsWith("from_"), &[SelfKind::No]),
1964 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1965 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1966 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1969 #[cfg_attr(rustfmt, rustfmt_skip)]
1970 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
1971 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1972 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1973 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1974 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1975 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1976 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1977 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1978 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1979 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1980 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1981 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1982 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1983 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1984 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1985 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1986 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1987 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1988 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1989 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1990 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1991 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1992 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1993 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1994 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1995 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1996 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1997 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1998 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1999 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
2000 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
2003 #[cfg_attr(rustfmt, rustfmt_skip)]
2004 const PATTERN_METHODS: [(&str, usize); 17] = [
2012 ("split_terminator", 1),
2013 ("rsplit_terminator", 1),
2018 ("match_indices", 1),
2019 ("rmatch_indices", 1),
2020 ("trim_left_matches", 1),
2021 ("trim_right_matches", 1),
2025 #[derive(Clone, Copy, PartialEq, Debug)]
2036 cx: &LateContext<'_, '_>,
2040 allow_value_for_ref: bool,
2041 generics: &hir::Generics,
2043 // Self types in the HIR are desugared to explicit self types. So it will
2046 // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
2047 // the impl is on `Foo`)
2048 // Thus, we only need to test equality against the impl self type or if it is
2050 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
2051 // `Self`, `&mut Self`,
2052 // and `Box<Self>`, including the equivalent types with `Foo`.
2054 let is_actually_self = |ty| is_self_ty(ty) || SpanlessEq::new(cx).eq_ty(ty, self_ty);
2057 SelfKind::Value => is_actually_self(ty),
2058 SelfKind::Ref | SelfKind::RefMut => {
2059 if allow_value_for_ref && is_actually_self(ty) {
2063 hir::TyKind::Rptr(_, ref mt_ty) => {
2064 let mutability_match = if self == SelfKind::Ref {
2065 mt_ty.mutbl == hir::MutImmutable
2067 mt_ty.mutbl == hir::MutMutable
2069 is_actually_self(&mt_ty.ty) && mutability_match
2078 SelfKind::Value => false,
2079 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
2080 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
2081 SelfKind::No => true,
2086 fn description(self) -> &'static str {
2088 SelfKind::Value => "self by value",
2089 SelfKind::Ref => "self by reference",
2090 SelfKind::RefMut => "self by mutable reference",
2091 SelfKind::No => "no self",
2096 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
2097 single_segment_ty(ty).map_or(false, |seg| {
2098 generics.params.iter().any(|param| match param.kind {
2099 hir::GenericParamKind::Type { .. } => {
2100 param.name.ident().name == seg.ident.name && param.bounds.iter().any(|bound| {
2101 if let hir::GenericBound::Trait(ref ptr, ..) = *bound {
2102 let path = &ptr.trait_ref.path;
2103 match_path(path, name) && path.segments.last().map_or(false, |s| {
2104 if let Some(ref params) = s.args {
2105 if params.parenthesized {
2108 // FIXME(flip1995): messy, improve if there is a better option
2110 let types: Vec<_> = params.args.iter().filter_map(|arg| match arg {
2111 hir::GenericArg::Type(ty) => Some(ty),
2115 && (is_self_ty(&types[0]) || is_ty(&*types[0], self_ty))
2131 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
2132 match (&ty.node, &self_ty.node) {
2134 &hir::TyKind::Path(hir::QPath::Resolved(_, ref ty_path)),
2135 &hir::TyKind::Path(hir::QPath::Resolved(_, ref self_ty_path)),
2139 .map(|seg| seg.ident.name)
2140 .eq(self_ty_path.segments.iter().map(|seg| seg.ident.name)),
2145 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2146 if let hir::TyKind::Path(ref path) = ty.node {
2147 single_segment_path(path)
2154 fn check(&self, other: &str) -> bool {
2156 Convention::Eq(this) => this == other,
2157 Convention::StartsWith(this) => other.starts_with(this) && this != other,
2162 impl fmt::Display for Convention {
2163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
2165 Convention::Eq(this) => this.fmt(f),
2166 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2171 #[derive(Clone, Copy)]
2180 fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FunctionRetTy) -> bool {
2181 let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
2183 (OutType::Unit, &hir::DefaultReturn(_)) => true,
2184 (OutType::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,
2185 (OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2186 (OutType::Any, &hir::Return(ref ty)) if !is_unit(ty) => true,
2187 (OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyKind::Rptr(_, _)),
2193 fn is_bool(ty: &hir::Ty) -> bool {
2194 if let hir::TyKind::Path(ref p) = ty.node {
2195 match_qpath(p, &["bool"])