3 use rustc::middle::const_val::ConstVal;
4 use rustc::middle::const_qualif::ConstQualif;
5 use rustc::ty::subst::TypeSpace;
7 use rustc_const_eval::EvalHint::ExprTypeChecked;
8 use rustc_const_eval::eval_const_expr_partial;
11 use syntax::codemap::Span;
13 use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, match_path,
14 match_trait_method, match_type, method_chain_args, return_ty, same_tys, snippet,
15 span_lint, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
16 use utils::MethodArgs;
23 /// **What it does:** This lint checks for `.unwrap()` calls on `Option`s.
25 /// **Why is this bad?** Usually it is better to handle the `None` case, or to at least call
26 /// `.expect(_)` with a more helpful message. Still, for a lot of quick-and-dirty code, `unwrap` is
27 /// a good choice, which is why this lint is `Allow` by default.
29 /// **Known problems:** None
36 pub OPTION_UNWRAP_USED, Allow,
37 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
40 /// **What it does:** This lint checks for `.unwrap()` calls on `Result`s.
42 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err` values. Normally, you
43 /// want to implement more sophisticated error handling, and propagate errors upwards with `try!`.
45 /// Even if you want to panic on errors, not all `Error`s implement good messages on display.
46 /// Therefore it may be beneficial to look at the places where they may get displayed. Activate
47 /// this lint to do just that.
49 /// **Known problems:** None
56 pub RESULT_UNWRAP_USED, Allow,
57 "using `Result.unwrap()`, which might be better handled"
60 /// **What it does:** This lint checks for methods that should live in a trait implementation of a
61 /// `std` trait (see [llogiq's blog post](http://llogiq.github.io/2015/07/30/traits.html) for
62 /// further information) instead of an inherent implementation.
64 /// **Why is this bad?** Implementing the traits improve ergonomics for users of the code, often
65 /// with very little cost. Also people seeing a `mul(..)` method may expect `*` to work equally, so
66 /// you should have good reason to disappoint them.
68 /// **Known problems:** None
74 /// fn add(&self, other: &X) -> X { .. }
78 pub SHOULD_IMPLEMENT_TRAIT, Warn,
79 "defining a method that should be implementing a std trait"
82 /// **What it does:** This lint checks for methods with certain name prefixes and which doesn't
83 /// match how self is taken. The actual rules are:
85 /// |Prefix |`self` taken |
86 /// |-------|----------------------|
87 /// |`as_` |`&self` or `&mut self`|
90 /// |`is_` |`&self` or none |
93 /// **Why is this bad?** Consistency breeds readability. If you follow the conventions, your users
94 /// won't be surprised that they, e.g., need to supply a mutable reference to a `as_..` function.
96 /// **Known problems:** None
102 /// fn as_str(self) -> &str { .. }
106 pub WRONG_SELF_CONVENTION, Warn,
107 "defining a method named with an established prefix (like \"into_\") that takes \
108 `self` with the wrong convention"
111 /// **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but
112 /// for public items.
114 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
116 /// **Known problems:** Actually *renaming* the function may break clients if the function is part
117 /// of the public interface. In that case, be mindful of the stability guarantees you've given your
123 /// pub fn as_str(self) -> &str { .. }
127 pub WRONG_PUB_SELF_CONVENTION, Allow,
128 "defining a public method named with an established prefix (like \"into_\") that takes \
129 `self` with the wrong convention"
132 /// **What it does:** This lint checks for usage of `ok().expect(..)`.
134 /// **Why is this bad?** Because you usually call `expect()` on the `Result` directly to get a good
137 /// **Known problems:** None.
141 /// x.ok().expect("why did I do this again?")
145 "using `ok().expect()`, which gives worse error messages than \
146 calling `expect` directly on the Result"
149 /// **What it does:** This lint checks for usage of `_.map(_).unwrap_or(_)`.
151 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or(_, _)`.
153 /// **Known problems:** None.
157 /// x.map(|a| a + 1).unwrap_or(0)
160 pub OPTION_MAP_UNWRAP_OR, Warn,
161 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
165 /// **What it does:** This lint `Warn`s on `_.map(_).unwrap_or_else(_)`.
167 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or_else(_, _)`.
169 /// **Known problems:** None.
173 /// x.map(|a| a + 1).unwrap_or_else(some_function)
176 pub OPTION_MAP_UNWRAP_OR_ELSE, Warn,
177 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
181 /// **What it does:** This lint `Warn`s on `_.filter(_).next()`.
183 /// **Why is this bad?** Readability, this can be written more concisely as `_.find(_)`.
185 /// **Known problems:** None.
189 /// iter.filter(|x| x == 0).next()
192 pub FILTER_NEXT, Warn,
193 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
196 /// **What it does:** This lint `Warn`s on `_.filter(_).map(_)`, `_.filter(_).flat_map(_)`,
197 /// `_.filter_map(_).flat_map(_)` and similar.
199 /// **Why is this bad?** Readability, this can be written more concisely as a single method call
201 /// **Known problems:** Often requires a condition + Option/Iterator creation inside the closure
205 /// iter.filter(|x| x == 0).map(|x| x * 2)
208 pub FILTER_MAP, Allow,
209 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
212 /// **What it does:** This lint `Warn`s on an iterator search (such as `find()`, `position()`, or
213 /// `rposition()`) followed by a call to `is_some()`.
215 /// **Why is this bad?** Readability, this can be written more concisely as `_.any(_)`.
217 /// **Known problems:** None.
221 /// iter.find(|x| x == 0).is_some()
224 pub SEARCH_IS_SOME, Warn,
225 "using an iterator search followed by `is_some()`, which is more succinctly \
226 expressed as a call to `any()`"
229 /// **What it does:** This lint `Warn`s on using `.chars().next()` on a `str` to check if it
230 /// starts with a given char.
232 /// **Why is this bad?** Readability, this can be written more concisely as `_.starts_with(_)`.
234 /// **Known problems:** None.
238 /// name.chars().next() == Some('_')
241 pub CHARS_NEXT_CMP, Warn,
242 "using `.chars().next()` to check if a string starts with a char"
245 /// **What it does:** This lint checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, etc., and
246 /// suggests to use `or_else`, `unwrap_or_else`, etc., or `unwrap_or_default` instead.
248 /// **Why is this bad?** The function will always be called and potentially allocate an object
249 /// in expressions such as:
251 /// foo.unwrap_or(String::new())
253 /// this can instead be written:
255 /// foo.unwrap_or_else(String::new)
259 /// foo.unwrap_or_default()
262 /// **Known problems:** If the function as side-effects, not calling it will change the semantic of
263 /// the program, but you shouldn't rely on that anyway.
265 pub OR_FUN_CALL, Warn,
266 "using any `*or` method when the `*or_else` would do"
269 /// **What it does:** This lint checks for usage of `.extend(s)` on a `Vec` to extend the vector by a slice.
271 /// **Why is this bad?** Since Rust 1.6, the `extend_from_slice(_)` method is stable and at least for now faster.
273 /// **Known problems:** None.
277 /// my_vec.extend(&xs)
280 pub EXTEND_FROM_SLICE, Warn,
281 "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
284 /// **What it does:** This lint warns on using `.clone()` on a `Copy` type.
286 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for generics, not for
287 /// using the `clone` method on a concrete type.
289 /// **Known problems:** None.
296 pub CLONE_ON_COPY, Warn, "using `clone` on a `Copy` type"
299 /// **What it does:** This lint warns on using `.clone()` on an `&&T`
301 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of cloning the underlying
304 /// **Known problems:** None.
311 /// let z = y.clone();
312 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
316 pub CLONE_DOUBLE_REF, Warn, "using `clone` on `&&T`"
319 /// **What it does:** This lint warns about `new` not returning `Self`.
321 /// **Why is this bad?** As a convention, `new` methods are used to make a new instance of a type.
323 /// **Known problems:** None.
328 /// fn new(..) -> NotAFoo {
333 pub NEW_RET_NO_SELF, Warn, "not returning `Self` in a `new` method"
336 /// **What it does:** This lint checks for string methods that receive a single-character `str` as an argument, e.g. `_.split("x")`.
338 /// **Why is this bad?** Performing these methods using a `char` is faster than using a `str`.
340 /// **Known problems:** Does not catch multi-byte unicode characters.
344 /// _.split("x")` could be `_.split('x')
347 pub SINGLE_CHAR_PATTERN,
349 "using a single-character str where a char could be used, e.g. \
353 /// **What it does:** This lint checks for getting the inner pointer of a temporary `CString`.
355 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long as the `CString` is
358 /// **Known problems:** None.
362 /// let c_str = CString::new("foo").unwrap().as_ptr();
364 /// call_some_ffi_func(c_str);
367 /// Here `c_str` point to a freed address. The correct use would be:
369 /// let c_str = CString::new("foo").unwrap();
371 /// call_some_ffi_func(c_str.as_ptr());
375 pub TEMPORARY_CSTRING_AS_PTR,
377 "getting the inner pointer of a temporary `CString`"
380 /// **What it does:** This lint checks for use of `.iter().nth()` (and the related
381 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
383 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more readable.
385 /// **Known problems:** None.
389 /// let some_vec = vec![0, 1, 2, 3];
390 /// let bad_vec = some_vec.iter().nth(3);
391 /// let bad_slice = &some_vec[..].iter().nth(3);
393 /// The correct use would be:
395 /// let some_vec = vec![0, 1, 2, 3];
396 /// let bad_vec = some_vec.get(3);
397 /// let bad_slice = &some_vec[..].get(3);
402 "using `.iter().nth()` on a standard library type with O(1) element access"
405 impl LintPass for Pass {
406 fn get_lints(&self) -> LintArray {
407 lint_array!(EXTEND_FROM_SLICE,
410 SHOULD_IMPLEMENT_TRAIT,
411 WRONG_SELF_CONVENTION,
412 WRONG_PUB_SELF_CONVENTION,
414 OPTION_MAP_UNWRAP_OR,
415 OPTION_MAP_UNWRAP_OR_ELSE,
423 TEMPORARY_CSTRING_AS_PTR,
429 impl LateLintPass for Pass {
430 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
431 if in_macro(cx, expr.span) {
436 hir::ExprMethodCall(name, _, ref args) => {
438 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
439 lint_unwrap(cx, expr, arglists[0]);
440 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
441 lint_ok_expect(cx, expr, arglists[0]);
442 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
443 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
444 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
445 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
446 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
447 lint_filter_next(cx, expr, arglists[0]);
448 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
449 lint_filter_map(cx, expr, arglists[0], arglists[1]);
450 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
451 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
452 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
453 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
454 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
455 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
456 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
457 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
458 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
459 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
460 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
461 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
462 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
463 lint_extend(cx, expr, arglists[0]);
464 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
465 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
466 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
467 lint_iter_nth(cx, expr, arglists[0], false);
468 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
469 lint_iter_nth(cx, expr, arglists[0], true);
472 lint_or_fun_call(cx, expr, &name.node.as_str(), args);
474 let self_ty = cx.tcx.expr_ty_adjusted(&args[0]);
475 if args.len() == 1 && name.node.as_str() == "clone" {
476 lint_clone_on_copy(cx, expr);
477 lint_clone_double_ref(cx, expr, &args[0], self_ty);
481 ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
482 for &(method, pos) in &PATTERN_METHODS {
483 if name.node.as_str() == method && args.len() > pos {
484 lint_single_char_pattern(cx, expr, &args[pos]);
491 hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
492 if !lint_chars_next(cx, expr, lhs, rhs, op.node == hir::BiEq) {
493 lint_chars_next(cx, expr, rhs, lhs, op.node == hir::BiEq);
500 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
501 if in_external_macro(cx, item.span) {
505 if let hir::ItemImpl(_, _, _, None, _, ref items) = item.node {
506 for implitem in items {
507 let name = implitem.name;
509 let hir::ImplItemKind::Method(ref sig, _) = implitem.node,
510 let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
512 // check missing trait implementations
513 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
514 if name.as_str() == method_name &&
515 sig.decl.inputs.len() == n_args &&
516 out_type.matches(&sig.decl.output) &&
517 self_kind.matches(&explicit_self, false) {
518 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
519 "defining a method called `{}` on this type; consider implementing \
520 the `{}` trait or choosing a less ambiguous name", name, trait_name));
524 // check conventions w.r.t. conversion method names and predicates
525 let ty = cx.tcx.lookup_item_type(cx.tcx.map.local_def_id(item.id)).ty;
526 let is_copy = is_copy(cx, ty, item.id);
527 for &(ref conv, self_kinds) in &CONVENTIONS {
529 conv.check(&name.as_str()),
530 let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
531 !self_kinds.iter().any(|k| k.matches(&explicit_self, is_copy)),
533 let lint = if item.vis == hir::Visibility::Public {
534 WRONG_PUB_SELF_CONVENTION
536 WRONG_SELF_CONVENTION
541 &format!("methods called `{}` usually take {}; consider choosing a less \
545 .map(|k| k.description())
551 let ret_ty = return_ty(cx, implitem.id);
552 if &name.as_str() == &"new" &&
553 !ret_ty.map_or(false, |ret_ty| ret_ty.walk().any(|t| same_tys(cx, t, ty, implitem.id))) {
557 "methods called `new` usually return `Self`");
565 /// Checks for the `OR_FUN_CALL` lint.
566 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[P<hir::Expr>]) {
567 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
568 fn check_unwrap_or_default(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr,
569 or_has_args: bool, span: Span)
575 if name == "unwrap_or" {
576 if let hir::ExprPath(_, ref path) = fun.node {
577 let path: &str = &path.segments
579 .expect("A path must have at least one segment")
583 if ["default", "new"].contains(&path) {
584 let arg_ty = cx.tcx.expr_ty(arg);
585 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
591 if implements_trait(cx, arg_ty, default_trait_id, Vec::new()) {
592 span_lint_and_then(cx,
595 &format!("use of `{}` followed by a call to `{}`", name, path),
597 db.span_suggestion(span, "try this",
598 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")));
609 /// Check for `*or(foo())`.
610 fn check_general_case(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr, or_has_args: bool,
612 // don't lint for constant values
613 // FIXME: can we `expect` here instead of match?
614 if let Some(qualif) = cx.tcx.const_qualif_map.borrow().get(&arg.id) {
615 if !qualif.contains(ConstQualif::NOT_CONST) {
619 // (path, fn_has_argument, methods, suffix)
620 let know_types: &[(&[_], _, &[_], _)] = &[(&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
621 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
624 &["map_or", "ok_or", "or", "unwrap_or"],
626 (&paths::RESULT, true, &["or", "unwrap_or"], "else")];
628 let self_ty = cx.tcx.expr_ty(self_expr);
630 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
631 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0)) {
632 (fn_has_arguments, poss, suffix)
637 if !poss.contains(&name) {
641 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
642 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
643 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
644 (false, true) => snippet(cx, fun.span, ".."),
647 span_lint_and_then(cx, OR_FUN_CALL, span, &format!("use of `{}` followed by a function call", name), |db| {
648 db.span_suggestion(span,
650 format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg));
655 if let hir::ExprCall(ref fun, ref or_args) = args[1].node {
656 let or_has_args = !or_args.is_empty();
657 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
658 check_general_case(cx, name, fun, &args[0], &args[1], or_has_args, expr.span);
664 /// Checks for the `CLONE_ON_COPY` lint.
665 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr) {
666 let ty = cx.tcx.expr_ty(expr);
667 let parent = cx.tcx.map.get_parent(expr.id);
668 let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, parent);
670 if !ty.moves_by_default(cx.tcx.global_tcx(), ¶meter_environment, expr.span) {
671 span_lint(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type");
675 /// Checks for the `CLONE_DOUBLE_REF` lint.
676 fn lint_clone_double_ref(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, ty: ty::Ty) {
677 if let ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) = ty.sty {
678 if let ty::TyRef(..) = inner.sty {
679 span_lint_and_then(cx,
682 "using `clone` on a double-reference; \
683 this will copy the reference instead of cloning the inner type",
684 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
685 db.span_suggestion(expr.span, "try dereferencing it", format!("({}).clone()", snip.deref()));
691 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &MethodArgs) {
692 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.expr_ty(&args[0]));
693 if !match_type(cx, obj_ty, &paths::VEC) {
696 let arg_ty = cx.tcx.expr_ty(&args[1]);
697 if let Some(slice) = derefs_to_slice(cx, &args[1], &arg_ty) {
698 span_lint_and_then(cx, EXTEND_FROM_SLICE, expr.span, "use of `extend` to extend a Vec by a slice", |db| {
699 db.span_suggestion(expr.span,
701 format!("{}.extend_from_slice({})",
702 snippet(cx, args[0].span, "_"),
708 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
710 let hir::ExprCall(ref fun, ref args) = new.node,
712 let hir::ExprPath(None, ref path) = fun.node,
713 match_path(path, &paths::CSTRING_NEW),
715 span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
716 "you are getting the inner pointer of a temporary `CString`",
718 db.note("that pointer will be invalid outside this expression");
719 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
725 // Type of MethodArgs is potentially a Vec
726 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &MethodArgs, is_mut: bool){
727 let mut_str = if is_mut { "_mut" } else {""};
728 let caller_type = if let Some(_) = derefs_to_slice(cx, &iter_args[0], &cx.tcx.expr_ty(&iter_args[0])) {
731 else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC) {
734 else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
738 return; // caller is not a type that we want to lint
745 &format!("called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
746 mut_str, caller_type)
750 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: &ty::Ty) -> Option<sugg::Sugg<'static>> {
751 fn may_slice(cx: &LateContext, ty: &ty::Ty) -> bool {
753 ty::TySlice(_) => true,
754 ty::TyStruct(..) => match_type(cx, ty, &paths::VEC),
755 ty::TyArray(_, size) => size < 32,
756 ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) |
757 ty::TyBox(ref inner) => may_slice(cx, inner),
762 if let hir::ExprMethodCall(name, _, ref args) = expr.node {
763 if &name.node.as_str() == &"iter" && may_slice(cx, &cx.tcx.expr_ty(&args[0])) {
764 sugg::Sugg::hir_opt(cx, &*args[0]).map(|sugg| {
772 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
773 ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) |
774 ty::TyBox(ref inner) => {
775 if may_slice(cx, inner) {
776 sugg::Sugg::hir_opt(cx, expr)
787 // Type of MethodArgs is potentially a Vec
788 /// lint use of `unwrap()` for `Option`s and `Result`s
789 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &MethodArgs) {
790 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.expr_ty(&unwrap_args[0]));
792 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
793 Some((OPTION_UNWRAP_USED, "an Option", "None"))
794 } else if match_type(cx, obj_ty, &paths::RESULT) {
795 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
800 if let Some((lint, kind, none_value)) = mess {
804 &format!("used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
805 using expect() to provide a better panic
813 // Type of MethodArgs is potentially a Vec
814 /// lint use of `ok().expect()` for `Result`s
815 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &MethodArgs) {
816 // lint if the caller of `ok()` is a `Result`
817 if match_type(cx, cx.tcx.expr_ty(&ok_args[0]), &paths::RESULT) {
818 let result_type = cx.tcx.expr_ty(&ok_args[0]);
819 if let Some(error_type) = get_error_type(cx, result_type) {
820 if has_debug_impl(error_type, cx) {
824 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`");
831 // Type of MethodArgs is potentially a Vec
832 /// lint use of `map().unwrap_or()` for `Option`s
833 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
834 // lint if the caller of `map()` is an `Option`
835 if match_type(cx, cx.tcx.expr_ty(&map_args[0]), &paths::OPTION) {
837 let msg = "called `map(f).unwrap_or(a)` on an Option value. This can be done more directly by calling \
838 `map_or(a, f)` instead";
839 // get snippets for args to map() and unwrap_or()
840 let map_snippet = snippet(cx, map_args[1].span, "..");
841 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
842 // lint, with note if neither arg is > 1 line and both map() and
843 // unwrap_or() have the same span
844 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
845 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
846 if same_span && !multiline {
847 span_note_and_lint(cx,
848 OPTION_MAP_UNWRAP_OR,
852 &format!("replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
855 } else if same_span && multiline {
856 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
862 // Type of MethodArgs is potentially a Vec
863 /// lint use of `map().unwrap_or_else()` for `Option`s
864 fn lint_map_unwrap_or_else(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
865 // lint if the caller of `map()` is an `Option`
866 if match_type(cx, cx.tcx.expr_ty(&map_args[0]), &paths::OPTION) {
868 let msg = "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
869 `map_or_else(g, f)` instead";
870 // get snippets for args to map() and unwrap_or_else()
871 let map_snippet = snippet(cx, map_args[1].span, "..");
872 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
873 // lint, with note if neither arg is > 1 line and both map() and
874 // unwrap_or_else() have the same span
875 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
876 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
877 if same_span && !multiline {
878 span_note_and_lint(cx,
879 OPTION_MAP_UNWRAP_OR_ELSE,
883 &format!("replace `map({0}).unwrap_or_else({1})` with `with map_or_else({1}, {0})`",
886 } else if same_span && multiline {
887 span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
893 // Type of MethodArgs is potentially a Vec
894 /// lint use of `filter().next()` for `Iterators`
895 fn lint_filter_next(cx: &LateContext, expr: &hir::Expr, filter_args: &MethodArgs) {
896 // lint if caller of `.filter().next()` is an Iterator
897 if match_trait_method(cx, expr, &paths::ITERATOR) {
898 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling `.find(p)` \
900 let filter_snippet = snippet(cx, filter_args[1].span, "..");
901 if filter_snippet.lines().count() <= 1 {
902 // add note if not multi-line
903 span_note_and_lint(cx,
908 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet));
910 span_lint(cx, FILTER_NEXT, expr.span, msg);
915 // Type of MethodArgs is potentially a Vec
916 /// lint use of `filter().map()` for `Iterators`
917 fn lint_filter_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
918 // lint if caller of `.filter().map()` is an Iterator
919 if match_trait_method(cx, expr, &paths::ITERATOR) {
920 let msg = "called `filter(p).map(q)` on an `Iterator`. \
921 This is more succinctly expressed by calling `.filter_map(..)` instead.";
922 span_lint(cx, FILTER_MAP, expr.span, msg);
926 // Type of MethodArgs is potentially a Vec
927 /// lint use of `filter().map()` for `Iterators`
928 fn lint_filter_map_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
929 // lint if caller of `.filter().map()` is an Iterator
930 if match_trait_method(cx, expr, &paths::ITERATOR) {
931 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
932 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
933 span_lint(cx, FILTER_MAP, expr.span, msg);
937 // Type of MethodArgs is potentially a Vec
938 /// lint use of `filter().flat_map()` for `Iterators`
939 fn lint_filter_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
940 // lint if caller of `.filter().flat_map()` is an Iterator
941 if match_trait_method(cx, expr, &paths::ITERATOR) {
942 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
943 This is more succinctly expressed by calling `.flat_map(..)` \
944 and filtering by returning an empty Iterator.";
945 span_lint(cx, FILTER_MAP, expr.span, msg);
949 // Type of MethodArgs is potentially a Vec
950 /// lint use of `filter_map().flat_map()` for `Iterators`
951 fn lint_filter_map_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
952 // lint if caller of `.filter_map().flat_map()` is an Iterator
953 if match_trait_method(cx, expr, &paths::ITERATOR) {
954 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
955 This is more succinctly expressed by calling `.flat_map(..)` \
956 and filtering by returning an empty Iterator.";
957 span_lint(cx, FILTER_MAP, expr.span, msg);
962 // Type of MethodArgs is potentially a Vec
963 /// lint searching an Iterator followed by `is_some()`
964 fn lint_search_is_some(cx: &LateContext, expr: &hir::Expr, search_method: &str, search_args: &MethodArgs,
965 is_some_args: &MethodArgs) {
966 // lint if caller of search is an Iterator
967 if match_trait_method(cx, &*is_some_args[0], &paths::ITERATOR) {
968 let msg = format!("called `is_some()` after searching an `Iterator` with {}. This is more succinctly expressed \
969 by calling `any()`.",
971 let search_snippet = snippet(cx, search_args[1].span, "..");
972 if search_snippet.lines().count() <= 1 {
973 // add note if not multi-line
974 span_note_and_lint(cx,
979 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet));
981 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
986 /// Checks for the `CHARS_NEXT_CMP` lint.
987 fn lint_chars_next(cx: &LateContext, expr: &hir::Expr, chain: &hir::Expr, other: &hir::Expr, eq: bool) -> bool {
989 let Some(args) = method_chain_args(chain, &["chars", "next"]),
990 let hir::ExprCall(ref fun, ref arg_char) = other.node,
992 let hir::ExprPath(None, ref path) = fun.node,
993 path.segments.len() == 1 && path.segments[0].name.as_str() == "Some"
995 let self_ty = walk_ptrs_ty(cx.tcx.expr_ty_adjusted(&args[0][0]));
997 if self_ty.sty != ty::TyStr {
1001 span_lint_and_then(cx,
1004 "you should use the `starts_with` method",
1006 let sugg = format!("{}{}.starts_with({})",
1007 if eq { "" } else { "!" },
1008 snippet(cx, args[0][0].span, "_"),
1009 snippet(cx, arg_char[0].span, "_")
1012 db.span_suggestion(expr.span, "like this", sugg);
1021 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1022 fn lint_single_char_pattern(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1023 if let Ok(ConstVal::Str(r)) = eval_const_expr_partial(cx.tcx, arg, ExprTypeChecked, None) {
1025 let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1026 span_lint_and_then(cx,
1027 SINGLE_CHAR_PATTERN,
1029 "single-character string constant used as pattern",
1031 db.span_suggestion(expr.span, "try using a char instead:", hint);
1037 /// Given a `Result<T, E>` type, return its error type (`E`).
1038 fn get_error_type<'a>(cx: &LateContext, ty: ty::Ty<'a>) -> Option<ty::Ty<'a>> {
1039 if !match_type(cx, ty, &paths::RESULT) {
1042 if let ty::TyEnum(_, substs) = ty.sty {
1043 if let Some(err_ty) = substs.types.opt_get(TypeSpace, 1) {
1044 return Some(err_ty);
1050 /// This checks whether a given type is known to implement Debug.
1051 fn has_debug_impl<'a, 'b>(ty: ty::Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1052 match cx.tcx.lang_items.debug_trait() {
1053 Some(debug) => implements_trait(cx, ty, debug, Vec::new()),
1060 StartsWith(&'static str),
1063 #[cfg_attr(rustfmt, rustfmt_skip)]
1064 const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
1065 (Convention::Eq("new"), &[SelfKind::No]),
1066 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1067 (Convention::StartsWith("from_"), &[SelfKind::No]),
1068 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1069 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1070 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1073 #[cfg_attr(rustfmt, rustfmt_skip)]
1074 const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
1075 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1076 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1077 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1078 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1079 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1080 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1081 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1082 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1083 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1084 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1085 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1086 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1087 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1088 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1089 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1090 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1091 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1092 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1093 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1094 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1095 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1096 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1097 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1098 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1099 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1100 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1101 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1102 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1103 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1104 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1107 #[cfg_attr(rustfmt, rustfmt_skip)]
1108 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1116 ("split_terminator", 1),
1117 ("rsplit_terminator", 1),
1122 ("match_indices", 1),
1123 ("rmatch_indices", 1),
1124 ("trim_left_matches", 1),
1125 ("trim_right_matches", 1),
1129 #[derive(Clone, Copy)]
1138 fn matches(self, slf: &hir::ExplicitSelf, allow_value_for_ref: bool) -> bool {
1139 match (self, &slf.node) {
1140 (SelfKind::Value, &hir::SelfKind::Value(_)) |
1141 (SelfKind::Ref, &hir::SelfKind::Region(_, hir::Mutability::MutImmutable)) |
1142 (SelfKind::RefMut, &hir::SelfKind::Region(_, hir::Mutability::MutMutable)) => true,
1143 (SelfKind::Ref, &hir::SelfKind::Value(_)) |
1144 (SelfKind::RefMut, &hir::SelfKind::Value(_)) => allow_value_for_ref,
1145 (_, &hir::SelfKind::Explicit(ref ty, _)) => self.matches_explicit_type(ty, allow_value_for_ref),
1151 fn matches_explicit_type(self, ty: &hir::Ty, allow_value_for_ref: bool) -> bool {
1152 match (self, &ty.node) {
1153 (SelfKind::Value, &hir::TyPath(..)) |
1154 (SelfKind::Ref, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutImmutable, .. })) |
1155 (SelfKind::RefMut, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutMutable, .. })) => true,
1156 (SelfKind::Ref, &hir::TyPath(..)) |
1157 (SelfKind::RefMut, &hir::TyPath(..)) => allow_value_for_ref,
1162 fn description(&self) -> &'static str {
1164 SelfKind::Value => "self by value",
1165 SelfKind::Ref => "self by reference",
1166 SelfKind::RefMut => "self by mutable reference",
1167 SelfKind::No => "no self",
1173 fn check(&self, other: &str) -> bool {
1175 Convention::Eq(this) => this == other,
1176 Convention::StartsWith(this) => other.starts_with(this),
1181 impl fmt::Display for Convention {
1182 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1184 Convention::Eq(this) => this.fmt(f),
1185 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1190 #[derive(Clone, Copy)]
1199 fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1201 (&OutType::Unit, &hir::DefaultReturn(_)) => true,
1202 (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
1203 (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
1204 (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
1205 (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
1211 fn is_bool(ty: &hir::Ty) -> bool {
1212 if let hir::TyPath(None, ref p) = ty.node {
1213 match_path(p, &["bool"])