3 use rustc::middle::const_val::ConstVal;
4 use rustc::middle::const_qualif::ConstQualif;
6 use rustc_const_eval::EvalHint::ExprTypeChecked;
7 use rustc_const_eval::eval_const_expr_partial;
10 use syntax::codemap::Span;
12 use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, match_path,
13 match_trait_method, match_type, method_chain_args, return_ty, same_tys, snippet,
14 span_lint, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
15 use utils::MethodArgs;
22 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
24 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
25 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
26 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
27 /// `Allow` by default.
29 /// **Known problems:** None.
36 pub OPTION_UNWRAP_USED,
38 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
41 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
43 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
44 /// values. Normally, you want to implement more sophisticated error handling,
45 /// and propagate errors upwards with `try!`.
47 /// Even if you want to panic on errors, not all `Error`s implement good
48 /// messages on display. Therefore it may be beneficial to look at the places
49 /// where they may get displayed. Activate this lint to do just that.
51 /// **Known problems:** None.
58 pub RESULT_UNWRAP_USED,
60 "using `Result.unwrap()`, which might be better handled"
63 /// **What it does:** Checks for methods that should live in a trait
64 /// implementation of a `std` trait (see [llogiq's blog
65 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
66 /// information) instead of an inherent implementation.
68 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
69 /// the code, often with very little cost. Also people seeing a `mul(...)` method
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 `.extend(s)` on a `Vec` to extend the
297 /// vector by a slice.
299 /// **Why is this bad?** Since Rust 1.6, the `extend_from_slice(_)` method is
300 /// stable and at least for now faster.
302 /// **Known problems:** None.
306 /// my_vec.extend(&xs)
309 pub EXTEND_FROM_SLICE,
311 "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
314 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
316 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
317 /// generics, not for using the `clone` method on a concrete type.
319 /// **Known problems:** None.
328 "using `clone` on a `Copy` type"
331 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
333 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
334 /// cloning the underlying `T`.
336 /// **Known problems:** None.
343 /// let z = y.clone();
344 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
348 pub CLONE_DOUBLE_REF,
350 "using `clone` on `&&T`"
353 /// **What it does:** Checks for `new` not returning `Self`.
355 /// **Why is this bad?** As a convention, `new` methods are used to make a new
356 /// instance of a type.
358 /// **Known problems:** None.
363 /// fn new(..) -> NotAFoo {
370 "not returning `Self` in a `new` method"
373 /// **What it does:** Checks for string methods that receive a single-character
374 /// `str` as an argument, e.g. `_.split("x")`.
376 /// **Why is this bad?** Performing these methods using a `char` is faster than
379 /// **Known problems:** Does not catch multi-byte unicode characters.
382 /// `_.split("x")` could be `_.split('x')
384 pub SINGLE_CHAR_PATTERN,
386 "using a single-character str where a char could be used, e.g. \
390 /// **What it does:** Checks for getting the inner pointer of a temporary `CString`.
392 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
393 /// as the `CString` is alive.
395 /// **Known problems:** None.
399 /// let c_str = CString::new("foo").unwrap().as_ptr();
401 /// call_some_ffi_func(c_str);
404 /// Here `c_str` point to a freed address. The correct use would be:
406 /// let c_str = CString::new("foo").unwrap();
408 /// call_some_ffi_func(c_str.as_ptr());
412 pub TEMPORARY_CSTRING_AS_PTR,
414 "getting the inner pointer of a temporary `CString`"
417 /// **What it does:** Checks for use of `.iter().nth()` (and the related
418 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
420 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
423 /// **Known problems:** None.
427 /// let some_vec = vec![0, 1, 2, 3];
428 /// let bad_vec = some_vec.iter().nth(3);
429 /// let bad_slice = &some_vec[..].iter().nth(3);
431 /// The correct use would be:
433 /// let some_vec = vec![0, 1, 2, 3];
434 /// let bad_vec = some_vec.get(3);
435 /// let bad_slice = &some_vec[..].get(3);
440 "using `.iter().nth()` on a standard library type with O(1) element access"
443 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
445 /// **Why is this bad?** `.nth(x)` is cleaner
447 /// **Known problems:** None.
451 /// let some_vec = vec![0, 1, 2, 3];
452 /// let bad_vec = some_vec.iter().skip(3).next();
453 /// let bad_slice = &some_vec[..].iter().skip(3).next();
455 /// The correct use would be:
457 /// let some_vec = vec![0, 1, 2, 3];
458 /// let bad_vec = some_vec.iter().nth(3);
459 /// let bad_slice = &some_vec[..].iter().nth(3);
464 "using `.skip(x).next()` on an iterator"
467 /// **What it does:** Checks for use of `.get().unwrap()` (or
468 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
470 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
473 /// **Known problems:** None.
477 /// let some_vec = vec![0, 1, 2, 3];
478 /// let last = some_vec.get(3).unwrap();
479 /// *some_vec.get_mut(0).unwrap() = 1;
481 /// The correct use would be:
483 /// let some_vec = vec![0, 1, 2, 3];
484 /// let last = some_vec[3];
490 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
494 impl LintPass for Pass {
495 fn get_lints(&self) -> LintArray {
496 lint_array!(EXTEND_FROM_SLICE,
499 SHOULD_IMPLEMENT_TRAIT,
500 WRONG_SELF_CONVENTION,
501 WRONG_PUB_SELF_CONVENTION,
503 OPTION_MAP_UNWRAP_OR,
504 OPTION_MAP_UNWRAP_OR_ELSE,
512 TEMPORARY_CSTRING_AS_PTR,
521 impl LateLintPass for Pass {
522 #[allow(unused_attributes)]
523 // ^ required because `cyclomatic_complexity` attribute shows up as unused
524 #[cyclomatic_complexity = "30"]
525 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
526 if in_macro(cx, expr.span) {
531 hir::ExprMethodCall(name, _, ref args) => {
533 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
534 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
535 lint_get_unwrap(cx, expr, arglists[0], false);
536 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
537 lint_get_unwrap(cx, expr, arglists[0], true);
538 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
539 lint_unwrap(cx, expr, arglists[0]);
540 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
541 lint_ok_expect(cx, expr, arglists[0]);
542 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
543 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
544 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
545 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
546 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
547 lint_filter_next(cx, expr, arglists[0]);
548 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
549 lint_filter_map(cx, expr, arglists[0], arglists[1]);
550 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
551 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
552 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
553 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
554 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
555 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
556 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
557 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
558 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
559 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
560 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
561 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
562 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
563 lint_extend(cx, expr, arglists[0]);
564 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
565 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
566 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
567 lint_iter_nth(cx, expr, arglists[0], false);
568 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
569 lint_iter_nth(cx, expr, arglists[0], true);
570 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
571 lint_iter_skip_next(cx, expr);
574 lint_or_fun_call(cx, expr, &name.node.as_str(), args);
576 let self_ty = cx.tcx.tables().expr_ty_adjusted(&args[0]);
577 if args.len() == 1 && name.node.as_str() == "clone" {
578 lint_clone_on_copy(cx, expr, &args[0], self_ty);
582 ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
583 for &(method, pos) in &PATTERN_METHODS {
584 if name.node.as_str() == method && args.len() > pos {
585 lint_single_char_pattern(cx, expr, &args[pos]);
592 hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
593 if !lint_chars_next(cx, expr, lhs, rhs, op.node == hir::BiEq) {
594 lint_chars_next(cx, expr, rhs, lhs, op.node == hir::BiEq);
601 fn check_impl_item(&mut self, cx: &LateContext, implitem: &hir::ImplItem) {
602 if in_external_macro(cx, implitem.span) {
605 let name = implitem.name;
606 let parent = cx.tcx.map.get_parent(implitem.id);
607 let item = cx.tcx.map.expect_item(parent);
609 let hir::ImplItemKind::Method(ref sig, _) = implitem.node,
610 let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
611 let hir::ItemImpl(_, _, _, None, _, _) = item.node,
613 // check missing trait implementations
614 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
615 if name.as_str() == method_name &&
616 sig.decl.inputs.len() == n_args &&
617 out_type.matches(&sig.decl.output) &&
618 self_kind.matches(&explicit_self, false) {
619 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
620 "defining a method called `{}` on this type; consider implementing \
621 the `{}` trait or choosing a less ambiguous name", name, trait_name));
625 // check conventions w.r.t. conversion method names and predicates
626 let ty = cx.tcx.item_type(cx.tcx.map.local_def_id(item.id));
627 let is_copy = is_copy(cx, ty, item.id);
628 for &(ref conv, self_kinds) in &CONVENTIONS {
630 conv.check(&name.as_str()),
631 let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
632 !self_kinds.iter().any(|k| k.matches(&explicit_self, is_copy)),
634 let lint = if item.vis == hir::Visibility::Public {
635 WRONG_PUB_SELF_CONVENTION
637 WRONG_SELF_CONVENTION
642 &format!("methods called `{}` usually take {}; consider choosing a less \
646 .map(|k| k.description())
652 let ret_ty = return_ty(cx, implitem.id);
653 if &name.as_str() == &"new" &&
654 !ret_ty.walk().any(|t| same_tys(cx, t, ty, implitem.id)) {
658 "methods called `new` usually return `Self`");
664 /// Checks for the `OR_FUN_CALL` lint.
665 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[P<hir::Expr>]) {
666 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
667 fn check_unwrap_or_default(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr,
668 or_has_args: bool, span: Span)
674 if name == "unwrap_or" {
675 if let hir::ExprPath(_, ref path) = fun.node {
676 let path: &str = &path.segments
678 .expect("A path must have at least one segment")
682 if ["default", "new"].contains(&path) {
683 let arg_ty = cx.tcx.tables().expr_ty(arg);
684 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
690 if implements_trait(cx, arg_ty, default_trait_id, Vec::new()) {
691 span_lint_and_then(cx,
694 &format!("use of `{}` followed by a call to `{}`", name, path),
696 db.span_suggestion(span, "try this",
697 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")));
708 /// Check for `*or(foo())`.
709 fn check_general_case(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr, or_has_args: bool,
711 // don't lint for constant values
712 // FIXME: can we `expect` here instead of match?
713 if let Some(qualif) = cx.tcx.const_qualif_map.borrow().get(&arg.id) {
714 if !qualif.contains(ConstQualif::NOT_CONST) {
718 // (path, fn_has_argument, methods, suffix)
719 let know_types: &[(&[_], _, &[_], _)] = &[(&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
720 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
723 &["map_or", "ok_or", "or", "unwrap_or"],
725 (&paths::RESULT, true, &["or", "unwrap_or"], "else")];
727 let self_ty = cx.tcx.tables().expr_ty(self_expr);
729 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
730 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0)) {
731 (fn_has_arguments, poss, suffix)
736 if !poss.contains(&name) {
740 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
741 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
742 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
743 (false, true) => snippet(cx, fun.span, ".."),
746 span_lint_and_then(cx, OR_FUN_CALL, span, &format!("use of `{}` followed by a function call", name), |db| {
747 db.span_suggestion(span,
749 format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg));
754 if let hir::ExprCall(ref fun, ref or_args) = args[1].node {
755 let or_has_args = !or_args.is_empty();
756 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
757 check_general_case(cx, name, fun, &args[0], &args[1], or_has_args, expr.span);
763 /// Checks for the `CLONE_ON_COPY` lint.
764 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: ty::Ty) {
765 let ty = cx.tcx.tables().expr_ty(expr);
766 let parent = cx.tcx.map.get_parent(expr.id);
767 let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, parent);
768 if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
769 if let ty::TyRef(..) = inner.sty {
770 span_lint_and_then(cx,
773 "using `clone` on a double-reference; \
774 this will copy the reference instead of cloning the inner type",
775 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
776 db.span_suggestion(expr.span, "try dereferencing it", format!("({}).clone()", snip.deref()));
778 return; // don't report clone_on_copy
782 if !ty.moves_by_default(cx.tcx.global_tcx(), ¶meter_environment, expr.span) {
783 span_lint_and_then(cx,
786 "using `clone` on a `Copy` type",
787 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
788 if let ty::TyRef(..) = cx.tcx.tables().expr_ty(arg).sty {
789 db.span_suggestion(expr.span, "try dereferencing it", format!("{}", snip.deref()));
791 db.span_suggestion(expr.span, "try removing the `clone` call", format!("{}", snip));
797 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &MethodArgs) {
798 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.tables().expr_ty(&args[0]));
799 if !match_type(cx, obj_ty, &paths::VEC) {
802 let arg_ty = cx.tcx.tables().expr_ty(&args[1]);
803 if let Some(slice) = derefs_to_slice(cx, &args[1], arg_ty) {
804 span_lint_and_then(cx, EXTEND_FROM_SLICE, expr.span, "use of `extend` to extend a Vec by a slice", |db| {
805 db.span_suggestion(expr.span,
807 format!("{}.extend_from_slice({})",
808 snippet(cx, args[0].span, "_"),
814 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
816 let hir::ExprCall(ref fun, ref args) = new.node,
818 let hir::ExprPath(None, ref path) = fun.node,
819 match_path(path, &paths::CSTRING_NEW),
821 span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
822 "you are getting the inner pointer of a temporary `CString`",
824 db.note("that pointer will be invalid outside this expression");
825 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
831 // Type of MethodArgs is potentially a Vec
832 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &MethodArgs, is_mut: bool){
833 let mut_str = if is_mut { "_mut" } else {""};
834 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tcx.tables().expr_ty(&iter_args[0])).is_some() {
837 else if match_type(cx, cx.tcx.tables().expr_ty(&iter_args[0]), &paths::VEC) {
840 else if match_type(cx, cx.tcx.tables().expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
844 return; // caller is not a type that we want to lint
851 &format!("called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
852 mut_str, caller_type)
856 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &MethodArgs, is_mut: bool) {
857 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
858 // because they do not implement `IndexMut`
859 let expr_ty = cx.tcx.tables().expr_ty(&get_args[0]);
860 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
862 } else if match_type(cx, expr_ty, &paths::VEC) {
864 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
866 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
868 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
871 return; // caller is not a type that we want to lint
874 let mut_str = if is_mut { "_mut" } else { "" };
875 let borrow_str = if is_mut { "&mut " } else { "&" };
880 &format!("called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
881 mut_str, caller_type),
886 format!("{}{}[{}]", borrow_str, snippet(cx, get_args[0].span, "_"),
887 snippet(cx, get_args[1].span, "_"))
893 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr){
894 // lint if caller of skip is an Iterator
895 if match_trait_method(cx, expr, &paths::ITERATOR) {
900 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`"
905 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: ty::Ty) -> Option<sugg::Sugg<'static>> {
906 fn may_slice(cx: &LateContext, ty: ty::Ty) -> bool {
908 ty::TySlice(_) => true,
909 ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
910 ty::TyArray(_, size) => size < 32,
911 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) |
912 ty::TyBox(inner) => may_slice(cx, inner),
917 if let hir::ExprMethodCall(name, _, ref args) = expr.node {
918 if &name.node.as_str() == &"iter" && may_slice(cx, cx.tcx.tables().expr_ty(&args[0])) {
919 sugg::Sugg::hir_opt(cx, &*args[0]).map(|sugg| {
927 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
928 ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) |
929 ty::TyBox(inner) => {
930 if may_slice(cx, inner) {
931 sugg::Sugg::hir_opt(cx, expr)
942 // Type of MethodArgs is potentially a Vec
943 /// lint use of `unwrap()` for `Option`s and `Result`s
944 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &MethodArgs) {
945 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.tables().expr_ty(&unwrap_args[0]));
947 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
948 Some((OPTION_UNWRAP_USED, "an Option", "None"))
949 } else if match_type(cx, obj_ty, &paths::RESULT) {
950 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
955 if let Some((lint, kind, none_value)) = mess {
959 &format!("used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
960 using expect() to provide a better panic
968 // Type of MethodArgs is potentially a Vec
969 /// lint use of `ok().expect()` for `Result`s
970 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &MethodArgs) {
971 // lint if the caller of `ok()` is a `Result`
972 if match_type(cx, cx.tcx.tables().expr_ty(&ok_args[0]), &paths::RESULT) {
973 let result_type = cx.tcx.tables().expr_ty(&ok_args[0]);
974 if let Some(error_type) = get_error_type(cx, result_type) {
975 if has_debug_impl(error_type, cx) {
979 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`");
986 // Type of MethodArgs is potentially a Vec
987 /// lint use of `map().unwrap_or()` for `Option`s
988 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
989 // lint if the caller of `map()` is an `Option`
990 if match_type(cx, cx.tcx.tables().expr_ty(&map_args[0]), &paths::OPTION) {
992 let msg = "called `map(f).unwrap_or(a)` on an Option value. This can be done more directly by calling \
993 `map_or(a, f)` instead";
994 // get snippets for args to map() and unwrap_or()
995 let map_snippet = snippet(cx, map_args[1].span, "..");
996 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
997 // lint, with note if neither arg is > 1 line and both map() and
998 // unwrap_or() have the same span
999 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1000 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
1001 if same_span && !multiline {
1002 span_note_and_lint(cx,
1003 OPTION_MAP_UNWRAP_OR,
1007 &format!("replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
1010 } else if same_span && multiline {
1011 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1017 // Type of MethodArgs is potentially a Vec
1018 /// lint use of `map().unwrap_or_else()` for `Option`s
1019 fn lint_map_unwrap_or_else(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
1020 // lint if the caller of `map()` is an `Option`
1021 if match_type(cx, cx.tcx.tables().expr_ty(&map_args[0]), &paths::OPTION) {
1023 let msg = "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1024 `map_or_else(g, f)` instead";
1025 // get snippets for args to map() and unwrap_or_else()
1026 let map_snippet = snippet(cx, map_args[1].span, "..");
1027 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1028 // lint, with note if neither arg is > 1 line and both map() and
1029 // unwrap_or_else() have the same span
1030 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1031 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
1032 if same_span && !multiline {
1033 span_note_and_lint(cx,
1034 OPTION_MAP_UNWRAP_OR_ELSE,
1038 &format!("replace `map({0}).unwrap_or_else({1})` with `with map_or_else({1}, {0})`",
1041 } else if same_span && multiline {
1042 span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
1048 // Type of MethodArgs is potentially a Vec
1049 /// lint use of `filter().next()` for `Iterators`
1050 fn lint_filter_next(cx: &LateContext, expr: &hir::Expr, filter_args: &MethodArgs) {
1051 // lint if caller of `.filter().next()` is an Iterator
1052 if match_trait_method(cx, expr, &paths::ITERATOR) {
1053 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling `.find(p)` \
1055 let filter_snippet = snippet(cx, filter_args[1].span, "..");
1056 if filter_snippet.lines().count() <= 1 {
1057 // add note if not multi-line
1058 span_note_and_lint(cx,
1063 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet));
1065 span_lint(cx, FILTER_NEXT, expr.span, msg);
1070 // Type of MethodArgs is potentially a Vec
1071 /// lint use of `filter().map()` for `Iterators`
1072 fn lint_filter_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1073 // lint if caller of `.filter().map()` is an Iterator
1074 if match_trait_method(cx, expr, &paths::ITERATOR) {
1075 let msg = "called `filter(p).map(q)` on an `Iterator`. \
1076 This is more succinctly expressed by calling `.filter_map(..)` instead.";
1077 span_lint(cx, FILTER_MAP, expr.span, msg);
1081 // Type of MethodArgs is potentially a Vec
1082 /// lint use of `filter().map()` for `Iterators`
1083 fn lint_filter_map_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1084 // lint if caller of `.filter().map()` is an Iterator
1085 if match_trait_method(cx, expr, &paths::ITERATOR) {
1086 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1087 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1088 span_lint(cx, FILTER_MAP, expr.span, msg);
1092 // Type of MethodArgs is potentially a Vec
1093 /// lint use of `filter().flat_map()` for `Iterators`
1094 fn lint_filter_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1095 // lint if caller of `.filter().flat_map()` is an Iterator
1096 if match_trait_method(cx, expr, &paths::ITERATOR) {
1097 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1098 This is more succinctly expressed by calling `.flat_map(..)` \
1099 and filtering by returning an empty Iterator.";
1100 span_lint(cx, FILTER_MAP, expr.span, msg);
1104 // Type of MethodArgs is potentially a Vec
1105 /// lint use of `filter_map().flat_map()` for `Iterators`
1106 fn lint_filter_map_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1107 // lint if caller of `.filter_map().flat_map()` is an Iterator
1108 if match_trait_method(cx, expr, &paths::ITERATOR) {
1109 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1110 This is more succinctly expressed by calling `.flat_map(..)` \
1111 and filtering by returning an empty Iterator.";
1112 span_lint(cx, FILTER_MAP, expr.span, msg);
1117 // Type of MethodArgs is potentially a Vec
1118 /// lint searching an Iterator followed by `is_some()`
1119 fn lint_search_is_some(cx: &LateContext, expr: &hir::Expr, search_method: &str, search_args: &MethodArgs,
1120 is_some_args: &MethodArgs) {
1121 // lint if caller of search is an Iterator
1122 if match_trait_method(cx, &*is_some_args[0], &paths::ITERATOR) {
1123 let msg = format!("called `is_some()` after searching an `Iterator` with {}. This is more succinctly expressed \
1124 by calling `any()`.",
1126 let search_snippet = snippet(cx, search_args[1].span, "..");
1127 if search_snippet.lines().count() <= 1 {
1128 // add note if not multi-line
1129 span_note_and_lint(cx,
1134 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet));
1136 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1141 /// Checks for the `CHARS_NEXT_CMP` lint.
1142 fn lint_chars_next(cx: &LateContext, expr: &hir::Expr, chain: &hir::Expr, other: &hir::Expr, eq: bool) -> bool {
1144 let Some(args) = method_chain_args(chain, &["chars", "next"]),
1145 let hir::ExprCall(ref fun, ref arg_char) = other.node,
1146 arg_char.len() == 1,
1147 let hir::ExprPath(None, ref path) = fun.node,
1148 path.segments.len() == 1 && path.segments[0].name.as_str() == "Some"
1150 let self_ty = walk_ptrs_ty(cx.tcx.tables().expr_ty_adjusted(&args[0][0]));
1152 if self_ty.sty != ty::TyStr {
1156 span_lint_and_then(cx,
1159 "you should use the `starts_with` method",
1161 let sugg = format!("{}{}.starts_with({})",
1162 if eq { "" } else { "!" },
1163 snippet(cx, args[0][0].span, "_"),
1164 snippet(cx, arg_char[0].span, "_")
1167 db.span_suggestion(expr.span, "like this", sugg);
1176 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1177 fn lint_single_char_pattern(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1178 if let Ok(ConstVal::Str(r)) = eval_const_expr_partial(cx.tcx, arg, ExprTypeChecked, None) {
1180 let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1181 span_lint_and_then(cx,
1182 SINGLE_CHAR_PATTERN,
1184 "single-character string constant used as pattern",
1186 db.span_suggestion(expr.span, "try using a char instead:", hint);
1192 /// Given a `Result<T, E>` type, return its error type (`E`).
1193 fn get_error_type<'a>(cx: &LateContext, ty: ty::Ty<'a>) -> Option<ty::Ty<'a>> {
1194 if let ty::TyAdt(_, substs) = ty.sty {
1195 if match_type(cx, ty, &paths::RESULT) {
1196 substs.types().nth(1)
1205 /// This checks whether a given type is known to implement Debug.
1206 fn has_debug_impl<'a, 'b>(ty: ty::Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1207 match cx.tcx.lang_items.debug_trait() {
1208 Some(debug) => implements_trait(cx, ty, debug, Vec::new()),
1215 StartsWith(&'static str),
1218 #[cfg_attr(rustfmt, rustfmt_skip)]
1219 const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
1220 (Convention::Eq("new"), &[SelfKind::No]),
1221 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1222 (Convention::StartsWith("from_"), &[SelfKind::No]),
1223 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1224 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1225 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1228 #[cfg_attr(rustfmt, rustfmt_skip)]
1229 const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
1230 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1231 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1232 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1233 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1234 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1235 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1236 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1237 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1238 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1239 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1240 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1241 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1242 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1243 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1244 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1245 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1246 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1247 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1248 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1249 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1250 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1251 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1252 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1253 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1254 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1255 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1256 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1257 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1258 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1259 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1262 #[cfg_attr(rustfmt, rustfmt_skip)]
1263 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1271 ("split_terminator", 1),
1272 ("rsplit_terminator", 1),
1277 ("match_indices", 1),
1278 ("rmatch_indices", 1),
1279 ("trim_left_matches", 1),
1280 ("trim_right_matches", 1),
1284 #[derive(Clone, Copy)]
1293 fn matches(self, slf: &hir::ExplicitSelf, allow_value_for_ref: bool) -> bool {
1294 match (self, &slf.node) {
1295 (SelfKind::Value, &hir::SelfKind::Value(_)) |
1296 (SelfKind::Ref, &hir::SelfKind::Region(_, hir::Mutability::MutImmutable)) |
1297 (SelfKind::RefMut, &hir::SelfKind::Region(_, hir::Mutability::MutMutable)) => true,
1298 (SelfKind::Ref, &hir::SelfKind::Value(_)) |
1299 (SelfKind::RefMut, &hir::SelfKind::Value(_)) => allow_value_for_ref,
1300 (_, &hir::SelfKind::Explicit(ref ty, _)) => self.matches_explicit_type(ty, allow_value_for_ref),
1306 fn matches_explicit_type(self, ty: &hir::Ty, allow_value_for_ref: bool) -> bool {
1307 match (self, &ty.node) {
1308 (SelfKind::Value, &hir::TyPath(..)) |
1309 (SelfKind::Ref, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutImmutable, .. })) |
1310 (SelfKind::RefMut, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutMutable, .. })) => true,
1311 (SelfKind::Ref, &hir::TyPath(..)) |
1312 (SelfKind::RefMut, &hir::TyPath(..)) => allow_value_for_ref,
1317 fn description(&self) -> &'static str {
1319 SelfKind::Value => "self by value",
1320 SelfKind::Ref => "self by reference",
1321 SelfKind::RefMut => "self by mutable reference",
1322 SelfKind::No => "no self",
1328 fn check(&self, other: &str) -> bool {
1330 Convention::Eq(this) => this == other,
1331 Convention::StartsWith(this) => other.starts_with(this) && this != other,
1336 impl fmt::Display for Convention {
1337 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1339 Convention::Eq(this) => this.fmt(f),
1340 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1345 #[derive(Clone, Copy)]
1354 fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1356 (&OutType::Unit, &hir::DefaultReturn(_)) => true,
1357 (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
1358 (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
1359 (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
1360 (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
1366 fn is_bool(ty: &hir::Ty) -> bool {
1367 if let hir::TyPath(None, ref p) = ty.node {
1368 match_path(p, &["bool"])