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;
10 use syntax::codemap::Span;
11 use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, match_path, match_trait_method,
12 match_type, method_chain_args, return_ty, same_tys, snippet, span_lint, span_lint_and_then,
13 span_lint_and_sugg, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, last_path_segment,
14 single_segment_path, match_def_path, is_self, is_self_ty, iter_input_pats, match_path_old};
21 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
23 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
24 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
25 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
26 /// `Allow` by default.
28 /// **Known problems:** None.
35 pub OPTION_UNWRAP_USED,
37 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
40 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
42 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
43 /// values. Normally, you want to implement more sophisticated error handling,
44 /// and propagate errors upwards with `try!`.
46 /// Even if you want to panic on errors, not all `Error`s implement good
47 /// messages on display. Therefore it may be beneficial to look at the places
48 /// where they may get displayed. Activate this lint to do just that.
50 /// **Known problems:** None.
57 pub RESULT_UNWRAP_USED,
59 "using `Result.unwrap()`, which might be better handled"
62 /// **What it does:** Checks for methods that should live in a trait
63 /// implementation of a `std` trait (see [llogiq's blog
64 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
65 /// information) instead of an inherent implementation.
67 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
68 /// the code, often with very little cost. Also people seeing a `mul(...)`
70 /// may expect `*` to work equally, so you should have good reason to disappoint
73 /// **Known problems:** None.
79 /// fn add(&self, other: &X) -> X { .. }
83 pub SHOULD_IMPLEMENT_TRAIT,
85 "defining a method that should be implementing a std trait"
88 /// **What it does:** Checks for methods with certain name prefixes and which
89 /// doesn't match how self is taken. The actual rules are:
91 /// |Prefix |`self` taken |
92 /// |-------|----------------------|
93 /// |`as_` |`&self` or `&mut self`|
96 /// |`is_` |`&self` or none |
99 /// **Why is this bad?** Consistency breeds readability. If you follow the
100 /// conventions, your users won't be surprised that they, e.g., need to supply a
101 /// mutable reference to a `as_..` function.
103 /// **Known problems:** None.
108 /// fn as_str(self) -> &str { .. }
112 pub WRONG_SELF_CONVENTION,
114 "defining a method named with an established prefix (like \"into_\") that takes \
115 `self` with the wrong convention"
118 /// **What it does:** This is the same as
119 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
121 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
123 /// **Known problems:** Actually *renaming* the function may break clients if
124 /// the function is part of the public interface. In that case, be mindful of
125 /// the stability guarantees you've given your users.
130 /// pub fn as_str(self) -> &str { .. }
134 pub WRONG_PUB_SELF_CONVENTION,
136 "defining a public method named with an established prefix (like \"into_\") that takes \
137 `self` with the wrong convention"
140 /// **What it does:** Checks for usage of `ok().expect(..)`.
142 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
143 /// directly to get a better error message.
145 /// **Known problems:** None.
149 /// x.ok().expect("why did I do this again?")
154 "using `ok().expect()`, which gives worse error messages than \
155 calling `expect` directly on the Result"
158 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
160 /// **Why is this bad?** Readability, this can be written more concisely as
161 /// `_.map_or(_, _)`.
163 /// **Known problems:** None.
167 /// x.map(|a| a + 1).unwrap_or(0)
170 pub OPTION_MAP_UNWRAP_OR,
172 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
176 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
178 /// **Why is this bad?** Readability, this can be written more concisely as
179 /// `_.map_or_else(_, _)`.
181 /// **Known problems:** None.
185 /// x.map(|a| a + 1).unwrap_or_else(some_function)
188 pub OPTION_MAP_UNWRAP_OR_ELSE,
190 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
194 /// **What it does:** Checks for usage of `_.filter(_).next()`.
196 /// **Why is this bad?** Readability, this can be written more concisely as
199 /// **Known problems:** None.
203 /// iter.filter(|x| x == 0).next()
208 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
211 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
212 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
214 /// **Why is this bad?** Readability, this can be written more concisely as a
215 /// single method call.
217 /// **Known problems:** Often requires a condition + Option/Iterator creation
218 /// inside the closure.
222 /// iter.filter(|x| x == 0).map(|x| x * 2)
227 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
228 usually be written as a single method call"
231 /// **What it does:** Checks for an iterator search (such as `find()`,
232 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
234 /// **Why is this bad?** Readability, this can be written more concisely as
237 /// **Known problems:** None.
241 /// iter.find(|x| x == 0).is_some()
246 "using an iterator search followed by `is_some()`, which is more succinctly \
247 expressed as a call to `any()`"
250 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
251 /// if it starts with a given char.
253 /// **Why is this bad?** Readability, this can be written more concisely as
254 /// `_.starts_with(_)`.
256 /// **Known problems:** None.
260 /// name.chars().next() == Some('_')
265 "using `.chars().next()` to check if a string starts with a char"
268 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
269 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
270 /// `unwrap_or_default` instead.
272 /// **Why is this bad?** The function will always be called and potentially
273 /// allocate an object acting as the default.
275 /// **Known problems:** If the function has side-effects, not calling it will
276 /// change the semantic of the program, but you shouldn't rely on that anyway.
280 /// foo.unwrap_or(String::new())
282 /// this can instead be written:
284 /// foo.unwrap_or_else(String::new)
288 /// foo.unwrap_or_default()
293 "using any `*or` method with a function call, which suggests `*or_else`"
296 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
298 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
299 /// generics, not for using the `clone` method on a concrete type.
301 /// **Known problems:** None.
310 "using `clone` on a `Copy` type"
313 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
315 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
316 /// cloning the underlying `T`.
318 /// **Known problems:** None.
325 /// let z = y.clone();
326 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
330 pub CLONE_DOUBLE_REF,
332 "using `clone` on `&&T`"
335 /// **What it does:** Checks for `new` not returning `Self`.
337 /// **Why is this bad?** As a convention, `new` methods are used to make a new
338 /// instance of a type.
340 /// **Known problems:** None.
345 /// fn new(..) -> NotAFoo {
352 "not returning `Self` in a `new` method"
355 /// **What it does:** Checks for string methods that receive a single-character
356 /// `str` as an argument, e.g. `_.split("x")`.
358 /// **Why is this bad?** Performing these methods using a `char` is faster than
361 /// **Known problems:** Does not catch multi-byte unicode characters.
364 /// `_.split("x")` could be `_.split('x')
366 pub SINGLE_CHAR_PATTERN,
368 "using a single-character str where a char could be used, e.g. \
372 /// **What it does:** Checks for getting the inner pointer of a temporary
375 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
376 /// as the `CString` is alive.
378 /// **Known problems:** None.
382 /// let c_str = CString::new("foo").unwrap().as_ptr();
384 /// call_some_ffi_func(c_str);
387 /// Here `c_str` point to a freed address. The correct use would be:
389 /// let c_str = CString::new("foo").unwrap();
391 /// call_some_ffi_func(c_str.as_ptr());
395 pub TEMPORARY_CSTRING_AS_PTR,
397 "getting the inner pointer of a temporary `CString`"
400 /// **What it does:** Checks for use of `.iter().nth()` (and the related
401 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
403 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
406 /// **Known problems:** None.
410 /// let some_vec = vec![0, 1, 2, 3];
411 /// let bad_vec = some_vec.iter().nth(3);
412 /// let bad_slice = &some_vec[..].iter().nth(3);
414 /// The correct use would be:
416 /// let some_vec = vec![0, 1, 2, 3];
417 /// let bad_vec = some_vec.get(3);
418 /// let bad_slice = &some_vec[..].get(3);
423 "using `.iter().nth()` on a standard library type with O(1) element access"
426 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
428 /// **Why is this bad?** `.nth(x)` is cleaner
430 /// **Known problems:** None.
434 /// let some_vec = vec![0, 1, 2, 3];
435 /// let bad_vec = some_vec.iter().skip(3).next();
436 /// let bad_slice = &some_vec[..].iter().skip(3).next();
438 /// The correct use would be:
440 /// let some_vec = vec![0, 1, 2, 3];
441 /// let bad_vec = some_vec.iter().nth(3);
442 /// let bad_slice = &some_vec[..].iter().nth(3);
447 "using `.skip(x).next()` on an iterator"
450 /// **What it does:** Checks for use of `.get().unwrap()` (or
451 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
453 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
456 /// **Known problems:** None.
460 /// let some_vec = vec![0, 1, 2, 3];
461 /// let last = some_vec.get(3).unwrap();
462 /// *some_vec.get_mut(0).unwrap() = 1;
464 /// The correct use would be:
466 /// let some_vec = vec![0, 1, 2, 3];
467 /// let last = some_vec[3];
473 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
476 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
477 /// `&str` or `String`.
479 /// **Why is this bad?** `.push_str(s)` is clearer
481 /// **Known problems:** None.
486 /// let def = String::from("def");
487 /// let mut s = String::new();
488 /// s.extend(abc.chars());
489 /// s.extend(def.chars());
491 /// The correct use would be:
494 /// let def = String::from("def");
495 /// let mut s = String::new();
497 /// s.push_str(&def));
500 pub STRING_EXTEND_CHARS,
502 "using `x.extend(s.chars())` where s is a `&str` or `String`"
505 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
508 /// **Why is this bad?** `.to_vec()` is clearer
510 /// **Known problems:** None.
514 /// let s = [1,2,3,4,5];
515 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
517 /// The better use would be:
519 /// let s = [1,2,3,4,5];
520 /// let s2 : Vec<isize> = s.to_vec();
523 pub ITER_CLONED_COLLECT,
525 "using `.cloned().collect()` on slice to create a `Vec`"
528 impl LintPass for Pass {
529 fn get_lints(&self) -> LintArray {
533 SHOULD_IMPLEMENT_TRAIT,
534 WRONG_SELF_CONVENTION,
535 WRONG_PUB_SELF_CONVENTION,
537 OPTION_MAP_UNWRAP_OR,
538 OPTION_MAP_UNWRAP_OR_ELSE,
546 TEMPORARY_CSTRING_AS_PTR,
558 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
559 #[allow(unused_attributes)]
560 // ^ required because `cyclomatic_complexity` attribute shows up as unused
561 #[cyclomatic_complexity = "30"]
562 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
563 if in_macro(expr.span) {
568 hir::ExprMethodCall(ref method_call, _, ref args) => {
570 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
571 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
572 lint_get_unwrap(cx, expr, arglists[0], false);
573 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
574 lint_get_unwrap(cx, expr, arglists[0], true);
575 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
576 lint_unwrap(cx, expr, arglists[0]);
577 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
578 lint_ok_expect(cx, expr, arglists[0]);
579 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
580 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
581 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
582 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
583 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
584 lint_filter_next(cx, expr, arglists[0]);
585 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
586 lint_filter_map(cx, expr, arglists[0], arglists[1]);
587 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
588 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
589 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
590 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
591 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
592 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
593 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
594 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
595 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
596 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
597 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
598 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
599 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
600 lint_extend(cx, expr, arglists[0]);
601 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
602 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
603 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
604 lint_iter_nth(cx, expr, arglists[0], false);
605 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
606 lint_iter_nth(cx, expr, arglists[0], true);
607 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
608 lint_iter_skip_next(cx, expr);
609 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
610 lint_iter_cloned_collect(cx, expr, arglists[0]);
613 lint_or_fun_call(cx, expr, &method_call.name.as_str(), args);
615 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
616 if args.len() == 1 && method_call.name == "clone" {
617 lint_clone_on_copy(cx, expr, &args[0], self_ty);
621 ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
622 for &(method, pos) in &PATTERN_METHODS {
623 if method_call.name == method && args.len() > pos {
624 lint_single_char_pattern(cx, expr, &args[pos]);
631 hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
632 if !lint_chars_next(cx, expr, lhs, rhs, op.node == hir::BiEq) {
633 lint_chars_next(cx, expr, rhs, lhs, op.node == hir::BiEq);
640 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
641 if in_external_macro(cx, implitem.span) {
644 let name = implitem.name;
645 let parent = cx.tcx.hir.get_parent(implitem.id);
646 let item = cx.tcx.hir.expect_item(parent);
648 let hir::ImplItemKind::Method(ref sig, id) = implitem.node,
649 let Some(first_arg_ty) = sig.decl.inputs.get(0),
650 let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next(),
651 let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node,
653 // check missing trait implementations
654 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
655 if name == method_name &&
656 sig.decl.inputs.len() == n_args &&
657 out_type.matches(&sig.decl.output) &&
658 self_kind.matches(first_arg_ty, first_arg, self_ty, false, &sig.generics) {
659 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
660 "defining a method called `{}` on this type; consider implementing \
661 the `{}` trait or choosing a less ambiguous name", name, trait_name));
665 // check conventions w.r.t. conversion method names and predicates
666 let def_id = cx.tcx.hir.local_def_id(item.id);
667 let ty = cx.tcx.type_of(def_id);
668 let is_copy = is_copy(cx, ty);
669 for &(ref conv, self_kinds) in &CONVENTIONS {
671 conv.check(&name.as_str()),
672 !self_kinds.iter().any(|k| k.matches(first_arg_ty, first_arg, self_ty, is_copy, &sig.generics)),
674 let lint = if item.vis == hir::Visibility::Public {
675 WRONG_PUB_SELF_CONVENTION
677 WRONG_SELF_CONVENTION
682 &format!("methods called `{}` usually take {}; consider choosing a less \
686 .map(|k| k.description())
692 let ret_ty = return_ty(cx, implitem.id);
694 !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
698 "methods called `new` usually return `Self`");
704 /// Checks for the `OR_FUN_CALL` lint.
705 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[hir::Expr]) {
706 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
707 fn check_unwrap_or_default(
711 self_expr: &hir::Expr,
720 if name == "unwrap_or" {
721 if let hir::ExprPath(ref qpath) = fun.node {
722 let path = &*last_path_segment(qpath).name.as_str();
724 if ["default", "new"].contains(&path) {
725 let arg_ty = cx.tables.expr_ty(arg);
726 let default_trait_id =
727 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
733 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
738 &format!("use of `{}` followed by a call to `{}`", name, path),
740 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
751 /// Check for `*or(foo())`.
752 fn check_general_case(
756 self_expr: &hir::Expr,
761 // don't lint for constant values
762 // FIXME: can we `expect` here instead of match?
763 let promotable = cx.tcx
764 .rvalue_promotable_to_static
773 // (path, fn_has_argument, methods, suffix)
774 let know_types: &[(&[_], _, &[_], _)] =
776 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
777 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
778 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
779 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
782 let self_ty = cx.tables.expr_ty(self_expr);
784 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
785 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
787 (fn_has_arguments, poss, suffix)
792 if !poss.contains(&name) {
796 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
797 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
798 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
799 (false, true) => snippet(cx, fun_span, ".."),
806 &format!("use of `{}` followed by a function call", name),
808 format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg),
814 hir::ExprCall(ref fun, ref or_args) => {
815 let or_has_args = !or_args.is_empty();
816 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
817 check_general_case(cx, name, fun.span, &args[0], &args[1], or_has_args, expr.span);
820 hir::ExprMethodCall(_, span, ref or_args) => {
821 check_general_case(cx, name, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
828 /// Checks for the `CLONE_ON_COPY` lint.
829 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
830 let ty = cx.tables.expr_ty(expr);
831 if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
832 if let ty::TyRef(..) = inner.sty {
837 "using `clone` on a double-reference; \
838 this will copy the reference instead of cloning the inner type",
839 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
840 db.span_suggestion(expr.span, "try dereferencing it", format!("({}).clone()", snip.deref()));
843 return; // don't report clone_on_copy
848 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
849 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
850 if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
851 db.span_suggestion(expr.span, "try dereferencing it", format!("{}", snip.deref()));
853 db.span_suggestion(expr.span, "try removing the `clone` call", format!("{}", snip));
860 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
862 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
863 let target = &arglists[0][0];
864 let (self_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(target));
865 let ref_str = if self_ty.sty == ty::TyStr {
867 } else if match_type(cx, self_ty, &paths::STRING) {
877 "calling `.extend(_.chars())`",
881 snippet(cx, args[0].span, "_"),
883 snippet(cx, target.span, "_")
889 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
890 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&args[0]));
891 if match_type(cx, obj_ty, &paths::STRING) {
892 lint_string_extend(cx, expr, args);
896 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
898 let hir::ExprCall(ref fun, ref args) = new.node,
900 let hir::ExprPath(ref path) = fun.node,
901 let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id),
902 match_def_path(cx.tcx, did, &paths::CSTRING_NEW)
904 span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
905 "you are getting the inner pointer of a temporary `CString`",
907 db.note("that pointer will be invalid outside this expression");
908 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
913 fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
914 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC) &&
915 derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
921 "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
927 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
928 let mut_str = if is_mut { "_mut" } else { "" };
929 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
931 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
933 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
936 return; // caller is not a type that we want to lint
944 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
951 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
952 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
953 // because they do not implement `IndexMut`
954 let expr_ty = cx.tables.expr_ty(&get_args[0]);
955 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
957 } else if match_type(cx, expr_ty, &paths::VEC) {
959 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
961 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
963 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
966 return; // caller is not a type that we want to lint
969 let mut_str = if is_mut { "_mut" } else { "" };
970 let borrow_str = if is_mut { "&mut " } else { "&" };
976 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
984 snippet(cx, get_args[0].span, "_"),
985 snippet(cx, get_args[1].span, "_")
990 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
991 // lint if caller of skip is an Iterator
992 if match_trait_method(cx, expr, &paths::ITERATOR) {
997 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1002 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
1003 fn may_slice(cx: &LateContext, ty: Ty) -> bool {
1005 ty::TySlice(_) => true,
1006 ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1007 ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1008 ty::TyArray(_, size) => size < 32,
1009 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => may_slice(cx, inner),
1014 if let hir::ExprMethodCall(ref path, _, ref args) = expr.node {
1015 if path.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1016 sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1022 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1023 ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1024 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => {
1025 if may_slice(cx, inner) {
1026 sugg::Sugg::hir_opt(cx, expr)
1036 /// lint use of `unwrap()` for `Option`s and `Result`s
1037 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1038 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&unwrap_args[0]));
1040 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1041 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1042 } else if match_type(cx, obj_ty, &paths::RESULT) {
1043 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1048 if let Some((lint, kind, none_value)) = mess {
1054 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1055 using expect() to provide a better panic \
1064 /// lint use of `ok().expect()` for `Result`s
1065 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1066 // lint if the caller of `ok()` is a `Result`
1067 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1068 let result_type = cx.tables.expr_ty(&ok_args[0]);
1069 if let Some(error_type) = get_error_type(cx, result_type) {
1070 if has_debug_impl(error_type, cx) {
1075 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1082 /// lint use of `map().unwrap_or()` for `Option`s
1083 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1084 // lint if the caller of `map()` is an `Option`
1085 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1087 let msg = "called `map(f).unwrap_or(a)` on an Option value. This can be done more directly by calling \
1088 `map_or(a, f)` instead";
1089 // get snippets for args to map() and unwrap_or()
1090 let map_snippet = snippet(cx, map_args[1].span, "..");
1091 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1092 // lint, with note if neither arg is > 1 line and both map() and
1093 // unwrap_or() have the same span
1094 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1095 let same_span = map_args[1].span.ctxt == unwrap_args[1].span.ctxt;
1096 if same_span && !multiline {
1099 OPTION_MAP_UNWRAP_OR,
1104 "replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
1109 } else if same_span && multiline {
1110 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1115 /// lint use of `map().unwrap_or_else()` for `Option`s
1116 fn lint_map_unwrap_or_else(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1117 // lint if the caller of `map()` is an `Option`
1118 if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1120 let msg = "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1121 `map_or_else(g, f)` instead";
1122 // get snippets for args to map() and unwrap_or_else()
1123 let map_snippet = snippet(cx, map_args[1].span, "..");
1124 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1125 // lint, with note if neither arg is > 1 line and both map() and
1126 // unwrap_or_else() have the same span
1127 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1128 let same_span = map_args[1].span.ctxt == unwrap_args[1].span.ctxt;
1129 if same_span && !multiline {
1132 OPTION_MAP_UNWRAP_OR_ELSE,
1137 "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
1142 } else if same_span && multiline {
1143 span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
1148 /// lint use of `filter().next()` for `Iterators`
1149 fn lint_filter_next(cx: &LateContext, expr: &hir::Expr, filter_args: &[hir::Expr]) {
1150 // lint if caller of `.filter().next()` is an Iterator
1151 if match_trait_method(cx, expr, &paths::ITERATOR) {
1152 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1153 `.find(p)` instead.";
1154 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1155 if filter_snippet.lines().count() <= 1 {
1156 // add note if not multi-line
1163 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1166 span_lint(cx, FILTER_NEXT, expr.span, msg);
1171 /// lint use of `filter().map()` for `Iterators`
1172 fn lint_filter_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1173 // lint if caller of `.filter().map()` is an Iterator
1174 if match_trait_method(cx, expr, &paths::ITERATOR) {
1175 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1176 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1177 span_lint(cx, FILTER_MAP, expr.span, msg);
1181 /// lint use of `filter().map()` for `Iterators`
1182 fn lint_filter_map_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1183 // lint if caller of `.filter().map()` is an Iterator
1184 if match_trait_method(cx, expr, &paths::ITERATOR) {
1185 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1186 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1187 span_lint(cx, FILTER_MAP, expr.span, msg);
1191 /// lint use of `filter().flat_map()` for `Iterators`
1192 fn lint_filter_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1193 // lint if caller of `.filter().flat_map()` is an Iterator
1194 if match_trait_method(cx, expr, &paths::ITERATOR) {
1195 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1196 This is more succinctly expressed by calling `.flat_map(..)` \
1197 and filtering by returning an empty Iterator.";
1198 span_lint(cx, FILTER_MAP, expr.span, msg);
1202 /// lint use of `filter_map().flat_map()` for `Iterators`
1203 fn lint_filter_map_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1204 // lint if caller of `.filter_map().flat_map()` is an Iterator
1205 if match_trait_method(cx, expr, &paths::ITERATOR) {
1206 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1207 This is more succinctly expressed by calling `.flat_map(..)` \
1208 and filtering by returning an empty Iterator.";
1209 span_lint(cx, FILTER_MAP, expr.span, msg);
1213 /// lint searching an Iterator followed by `is_some()`
1214 fn lint_search_is_some(
1217 search_method: &str,
1218 search_args: &[hir::Expr],
1219 is_some_args: &[hir::Expr],
1221 // lint if caller of search is an Iterator
1222 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1224 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1225 expressed by calling `any()`.",
1228 let search_snippet = snippet(cx, search_args[1].span, "..");
1229 if search_snippet.lines().count() <= 1 {
1230 // add note if not multi-line
1237 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1240 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1245 /// Checks for the `CHARS_NEXT_CMP` lint.
1246 fn lint_chars_next(cx: &LateContext, expr: &hir::Expr, chain: &hir::Expr, other: &hir::Expr, eq: bool) -> bool {
1248 let Some(args) = method_chain_args(chain, &["chars", "next"]),
1249 let hir::ExprCall(ref fun, ref arg_char) = other.node,
1250 arg_char.len() == 1,
1251 let hir::ExprPath(ref qpath) = fun.node,
1252 let Some(segment) = single_segment_path(qpath),
1253 segment.name == "Some"
1255 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1257 if self_ty.sty != ty::TyStr {
1261 span_lint_and_sugg(cx,
1264 "you should use the `starts_with` method",
1266 format!("{}{}.starts_with({})",
1267 if eq { "" } else { "!" },
1268 snippet(cx, args[0][0].span, "_"),
1269 snippet(cx, arg_char[0].span, "_")));
1277 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1278 fn lint_single_char_pattern(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1279 let parent_item = cx.tcx.hir.get_parent(arg.id);
1280 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1281 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1282 if let Ok(ConstVal::Str(r)) = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(arg) {
1284 let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1287 SINGLE_CHAR_PATTERN,
1289 "single-character string constant used as pattern",
1290 |db| { db.span_suggestion(expr.span, "try using a char instead", hint); },
1296 /// Given a `Result<T, E>` type, return its error type (`E`).
1297 fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
1298 if let ty::TyAdt(_, substs) = ty.sty {
1299 if match_type(cx, ty, &paths::RESULT) {
1300 substs.types().nth(1)
1309 /// This checks whether a given type is known to implement Debug.
1310 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1311 match cx.tcx.lang_items.debug_trait() {
1312 Some(debug) => implements_trait(cx, ty, debug, &[]),
1319 StartsWith(&'static str),
1322 #[cfg_attr(rustfmt, rustfmt_skip)]
1323 const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
1324 (Convention::Eq("new"), &[SelfKind::No]),
1325 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1326 (Convention::StartsWith("from_"), &[SelfKind::No]),
1327 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1328 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1329 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1332 #[cfg_attr(rustfmt, rustfmt_skip)]
1333 const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
1334 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1335 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1336 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1337 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1338 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1339 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1340 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1341 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1342 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1343 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1344 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1345 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1346 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1347 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1348 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1349 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1350 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1351 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1352 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1353 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1354 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1355 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1356 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1357 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1358 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1359 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1360 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1361 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1362 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1363 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1366 #[cfg_attr(rustfmt, rustfmt_skip)]
1367 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1375 ("split_terminator", 1),
1376 ("rsplit_terminator", 1),
1381 ("match_indices", 1),
1382 ("rmatch_indices", 1),
1383 ("trim_left_matches", 1),
1384 ("trim_right_matches", 1),
1388 #[derive(Clone, Copy, PartialEq, Debug)]
1402 allow_value_for_ref: bool,
1403 generics: &hir::Generics,
1405 // Self types in the HIR are desugared to explicit self types. So it will
1408 // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
1409 // the impl is on `Foo`)
1410 // Thus, we only need to test equality against the impl self type or if it is
1412 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
1413 // `Self`, `&mut Self`,
1414 // and `Box<Self>`, including the equivalent types with `Foo`.
1416 let is_actually_self = |ty| is_self_ty(ty) || ty == self_ty;
1419 SelfKind::Value => is_actually_self(ty),
1420 SelfKind::Ref | SelfKind::RefMut => {
1421 if allow_value_for_ref && is_actually_self(ty) {
1425 hir::TyRptr(_, ref mt_ty) => {
1426 let mutability_match = if self == SelfKind::Ref {
1427 mt_ty.mutbl == hir::MutImmutable
1429 mt_ty.mutbl == hir::MutMutable
1431 is_actually_self(&mt_ty.ty) && mutability_match
1440 SelfKind::Value => false,
1441 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
1442 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
1443 SelfKind::No => true,
1448 fn description(&self) -> &'static str {
1450 SelfKind::Value => "self by value",
1451 SelfKind::Ref => "self by reference",
1452 SelfKind::RefMut => "self by mutable reference",
1453 SelfKind::No => "no self",
1458 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
1459 single_segment_ty(ty).map_or(false, |seg| {
1460 generics.ty_params.iter().any(|param| {
1461 param.name == seg.name &&
1462 param.bounds.iter().any(|bound| {
1463 if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
1464 let path = &ptr.trait_ref.path;
1465 match_path_old(path, name) &&
1466 path.segments.last().map_or(false, |s| {
1467 if let hir::PathParameters::AngleBracketedParameters(ref data) = s.parameters {
1468 data.types.len() == 1 &&
1469 (is_self_ty(&data.types[0]) || is_ty(&*data.types[0], self_ty))
1482 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
1483 match (&ty.node, &self_ty.node) {
1484 (&hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
1485 &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path))) => {
1486 ty_path.segments.iter().map(|seg| seg.name).eq(
1487 self_ty_path.segments.iter().map(|seg| seg.name),
1494 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
1495 if let hir::TyPath(ref path) = ty.node {
1496 single_segment_path(path)
1503 fn check(&self, other: &str) -> bool {
1505 Convention::Eq(this) => this == other,
1506 Convention::StartsWith(this) => other.starts_with(this) && this != other,
1511 impl fmt::Display for Convention {
1512 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1514 Convention::Eq(this) => this.fmt(f),
1515 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1520 #[derive(Clone, Copy)]
1529 fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1531 (&OutType::Unit, &hir::DefaultReturn(_)) => true,
1532 (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
1533 (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
1534 (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
1535 (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
1541 fn is_bool(ty: &hir::Ty) -> bool {
1542 if let hir::TyPath(ref p) = ty.node {
1543 match_path(p, &["bool"])