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 `.expect(_)` with a more helpful message. Still, for a lot of quick-and-dirty code, `unwrap` is a good choice, which is why this lint is `Allow` by default.
27 /// **Known problems:** None
29 /// **Example:** `x.unwrap()`
31 pub OPTION_UNWRAP_USED, Allow,
32 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
35 /// **What it does:** This lint checks for `.unwrap()` calls on `Result`s.
37 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err` values. Normally, you want to implement more sophisticated error handling, and propagate errors upwards with `try!`.
39 /// Even if you want to panic on errors, not all `Error`s implement good messages on display. Therefore it may be beneficial to look at the places where they may get displayed. Activate this lint to do just that.
41 /// **Known problems:** None
43 /// **Example:** `x.unwrap()`
45 pub RESULT_UNWRAP_USED, Allow,
46 "using `Result.unwrap()`, which might be better handled"
49 /// **What it does:** This lint checks for methods that should live in a trait implementation of a `std` trait (see [llogiq's blog post](http://llogiq.github.io/2015/07/30/traits.html) for further information) instead of an inherent implementation.
51 /// **Why is this bad?** Implementing the traits improve ergonomics for users of the code, often with very little cost. Also people seeing a `mul(..)` method may expect `*` to work equally, so you should have good reason to disappoint them.
53 /// **Known problems:** None
59 /// fn add(&self, other: &X) -> X { .. }
63 pub SHOULD_IMPLEMENT_TRAIT, Warn,
64 "defining a method that should be implementing a std trait"
67 /// **What it does:** This lint checks for methods with certain name prefixes and which doesn't match how self is taken. The actual rules are:
69 /// |Prefix |`self` taken |
70 /// |-------|--------------------|
71 /// |`as_` |`&self` or &mut self|
74 /// |`is_` |`&self` or none |
77 /// **Why is this bad?** Consistency breeds readability. If you follow the conventions, your users won't be surprised that they, e.g., need to supply a mutable reference to a `as_..` function.
79 /// **Known problems:** None
85 /// fn as_str(self) -> &str { .. }
89 pub WRONG_SELF_CONVENTION, Warn,
90 "defining a method named with an established prefix (like \"into_\") that takes \
91 `self` with the wrong convention"
94 /// **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but for public items.
96 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
98 /// **Known problems:** Actually *renaming* the function may break clients if the function is part of the public interface. In that case, be mindful of the stability guarantees you've given your users.
103 /// pub fn as_str(self) -> &str { .. }
107 pub WRONG_PUB_SELF_CONVENTION, Allow,
108 "defining a public method named with an established prefix (like \"into_\") that takes \
109 `self` with the wrong convention"
112 /// **What it does:** This lint checks for usage of `ok().expect(..)`.
114 /// **Why is this bad?** Because you usually call `expect()` on the `Result` directly to get a good error message.
116 /// **Known problems:** None.
118 /// **Example:** `x.ok().expect("why did I do this again?")`
121 "using `ok().expect()`, which gives worse error messages than \
122 calling `expect` directly on the Result"
125 /// **What it does:** This lint checks for usage of `_.map(_).unwrap_or(_)`.
127 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or(_, _)`.
129 /// **Known problems:** None.
131 /// **Example:** `x.map(|a| a + 1).unwrap_or(0)`
133 pub OPTION_MAP_UNWRAP_OR, Warn,
134 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
138 /// **What it does:** This lint `Warn`s on `_.map(_).unwrap_or_else(_)`.
140 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or_else(_, _)`.
142 /// **Known problems:** None.
144 /// **Example:** `x.map(|a| a + 1).unwrap_or_else(some_function)`
146 pub OPTION_MAP_UNWRAP_OR_ELSE, Warn,
147 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
151 /// **What it does:** This lint `Warn`s on `_.filter(_).next()`.
153 /// **Why is this bad?** Readability, this can be written more concisely as `_.find(_)`.
155 /// **Known problems:** None.
157 /// **Example:** `iter.filter(|x| x == 0).next()`
159 pub FILTER_NEXT, Warn,
160 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
163 /// **What it does:** This lint `Warn`s on `_.filter(_).map(_)`, `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
165 /// **Why is this bad?** Readability, this can be written more concisely as a single method call
167 /// **Known problems:** Often requires a condition + Option/Iterator creation inside the closure
169 /// **Example:** `iter.filter(|x| x == 0).map(|x| x * 2)`
171 pub FILTER_MAP, Allow,
172 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
175 /// **What it does:** This lint `Warn`s on an iterator search (such as `find()`, `position()`, or
176 /// `rposition()`) followed by a call to `is_some()`.
178 /// **Why is this bad?** Readability, this can be written more concisely as `_.any(_)`.
180 /// **Known problems:** None.
182 /// **Example:** `iter.find(|x| x == 0).is_some()`
184 pub SEARCH_IS_SOME, Warn,
185 "using an iterator search followed by `is_some()`, which is more succinctly \
186 expressed as a call to `any()`"
189 /// **What it does:** This lint `Warn`s on using `.chars().next()` on a `str` to check if it
190 /// starts with a given char.
192 /// **Why is this bad?** Readability, this can be written more concisely as `_.starts_with(_)`.
194 /// **Known problems:** None.
196 /// **Example:** `name.chars().next() == Some('_')`
198 pub CHARS_NEXT_CMP, Warn,
199 "using `.chars().next()` to check if a string starts with a char"
202 /// **What it does:** This lint checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, etc., and
203 /// suggests to use `or_else`, `unwrap_or_else`, etc., or `unwrap_or_default` instead.
205 /// **Why is this bad?** The function will always be called and potentially allocate an object
206 /// in expressions such as:
208 /// foo.unwrap_or(String::new())
210 /// this can instead be written:
212 /// foo.unwrap_or_else(String::new)
216 /// foo.unwrap_or_default()
219 /// **Known problems:** If the function as side-effects, not calling it will change the semantic of
220 /// the program, but you shouldn't rely on that anyway.
222 pub OR_FUN_CALL, Warn,
223 "using any `*or` method when the `*or_else` would do"
226 /// **What it does:** This lint checks for usage of `.extend(s)` on a `Vec` to extend the vector by a slice.
228 /// **Why is this bad?** Since Rust 1.6, the `extend_from_slice(_)` method is stable and at least for now faster.
230 /// **Known problems:** None.
232 /// **Example:** `my_vec.extend(&xs)`
234 pub EXTEND_FROM_SLICE, Warn,
235 "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
238 /// **What it does:** This lint warns on using `.clone()` on a `Copy` type.
240 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for generics, not for
241 /// using the `clone` method on a concrete type.
243 /// **Known problems:** None.
245 /// **Example:** `42u64.clone()`
247 pub CLONE_ON_COPY, Warn, "using `clone` on a `Copy` type"
250 /// **What it does:** This lint warns on using `.clone()` on an `&&T`
252 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of cloning the underlying
255 /// **Known problems:** None.
262 /// let z = y.clone();
263 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
267 pub CLONE_DOUBLE_REF, Warn, "using `clone` on `&&T`"
270 /// **What it does:** This lint warns about `new` not returning `Self`.
272 /// **Why is this bad?** As a convention, `new` methods are used to make a new instance of a type.
274 /// **Known problems:** None.
279 /// fn new(..) -> NotAFoo {
284 pub NEW_RET_NO_SELF, Warn, "not returning `Self` in a `new` method"
287 /// **What it does:** This lint checks for string methods that receive a single-character `str` as an argument, e.g. `_.split("x")`.
289 /// **Why is this bad?** Performing these methods using a `char` is faster than using a `str`.
291 /// **Known problems:** Does not catch multi-byte unicode characters.
293 /// **Example:** `_.split("x")` could be `_.split('x')`
295 pub SINGLE_CHAR_PATTERN,
297 "using a single-character str where a char could be used, e.g. \
301 /// **What it does:** This lint checks for getting the inner pointer of a temporary `CString`.
303 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long as the `CString` is
306 /// **Known problems:** None.
310 /// let c_str = CString::new("foo").unwrap().as_ptr();
312 /// call_some_ffi_func(c_str);
315 /// Here `c_str` point to a freed address. The correct use would be:
317 /// let c_str = CString::new("foo").unwrap();
319 /// call_some_ffi_func(c_str.as_ptr());
323 pub TEMPORARY_CSTRING_AS_PTR,
325 "getting the inner pointer of a temporary `CString`"
328 /// **What it does:** This lint checks for use of `.iter().nth()` (and the related
329 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
331 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more readable.
333 /// **Known problems:** None.
337 /// let some_vec = vec![0, 1, 2, 3];
338 /// let bad_vec = some_vec.iter().nth(3);
339 /// let bad_slice = &some_vec[..].iter().nth(3);
341 /// The correct use would be:
343 /// let some_vec = vec![0, 1, 2, 3];
344 /// let bad_vec = some_vec.get(3);
345 /// let bad_slice = &some_vec[..].get(3);
350 "using `.iter().nth()` on a standard library type with O(1) element access"
353 impl LintPass for Pass {
354 fn get_lints(&self) -> LintArray {
355 lint_array!(EXTEND_FROM_SLICE,
358 SHOULD_IMPLEMENT_TRAIT,
359 WRONG_SELF_CONVENTION,
360 WRONG_PUB_SELF_CONVENTION,
362 OPTION_MAP_UNWRAP_OR,
363 OPTION_MAP_UNWRAP_OR_ELSE,
371 TEMPORARY_CSTRING_AS_PTR,
377 impl LateLintPass for Pass {
378 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
379 if in_macro(cx, expr.span) {
384 hir::ExprMethodCall(name, _, ref args) => {
386 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
387 lint_unwrap(cx, expr, arglists[0]);
388 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
389 lint_ok_expect(cx, expr, arglists[0]);
390 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
391 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
392 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
393 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
394 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
395 lint_filter_next(cx, expr, arglists[0]);
396 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
397 lint_filter_map(cx, expr, arglists[0], arglists[1]);
398 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
399 lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
400 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
401 lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
402 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
403 lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
404 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
405 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
406 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
407 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
408 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
409 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
410 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
411 lint_extend(cx, expr, arglists[0]);
412 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
413 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
414 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
415 lint_iter_nth(cx, expr, arglists[0], false);
416 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
417 lint_iter_nth(cx, expr, arglists[0], true);
420 lint_or_fun_call(cx, expr, &name.node.as_str(), args);
422 let self_ty = cx.tcx.expr_ty_adjusted(&args[0]);
423 if args.len() == 1 && name.node.as_str() == "clone" {
424 lint_clone_on_copy(cx, expr);
425 lint_clone_double_ref(cx, expr, &args[0], self_ty);
429 ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
430 for &(method, pos) in &PATTERN_METHODS {
431 if name.node.as_str() == method && args.len() > pos {
432 lint_single_char_pattern(cx, expr, &args[pos]);
439 hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
440 if !lint_chars_next(cx, expr, lhs, rhs, op.node == hir::BiEq) {
441 lint_chars_next(cx, expr, rhs, lhs, op.node == hir::BiEq);
448 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
449 if in_external_macro(cx, item.span) {
453 if let hir::ItemImpl(_, _, _, None, _, ref items) = item.node {
454 for implitem in items {
455 let name = implitem.name;
457 let hir::ImplItemKind::Method(ref sig, _) = implitem.node,
458 let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
460 // check missing trait implementations
461 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
462 if name.as_str() == method_name &&
463 sig.decl.inputs.len() == n_args &&
464 out_type.matches(&sig.decl.output) &&
465 self_kind.matches(&explicit_self, false) {
466 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
467 "defining a method called `{}` on this type; consider implementing \
468 the `{}` trait or choosing a less ambiguous name", name, trait_name));
472 // check conventions w.r.t. conversion method names and predicates
473 let ty = cx.tcx.lookup_item_type(cx.tcx.map.local_def_id(item.id)).ty;
474 let is_copy = is_copy(cx, ty, item.id);
475 for &(ref conv, self_kinds) in &CONVENTIONS {
477 conv.check(&name.as_str()),
478 let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
479 !self_kinds.iter().any(|k| k.matches(&explicit_self, is_copy)),
481 let lint = if item.vis == hir::Visibility::Public {
482 WRONG_PUB_SELF_CONVENTION
484 WRONG_SELF_CONVENTION
489 &format!("methods called `{}` usually take {}; consider choosing a less \
493 .map(|k| k.description())
499 let ret_ty = return_ty(cx, implitem.id);
500 if &name.as_str() == &"new" &&
501 !ret_ty.map_or(false, |ret_ty| ret_ty.walk().any(|t| same_tys(cx, t, ty, implitem.id))) {
505 "methods called `new` usually return `Self`");
513 /// Checks for the `OR_FUN_CALL` lint.
514 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[P<hir::Expr>]) {
515 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
516 fn check_unwrap_or_default(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr,
517 or_has_args: bool, span: Span)
523 if name == "unwrap_or" {
524 if let hir::ExprPath(_, ref path) = fun.node {
525 let path: &str = &path.segments
527 .expect("A path must have at least one segment")
531 if ["default", "new"].contains(&path) {
532 let arg_ty = cx.tcx.expr_ty(arg);
533 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
539 if implements_trait(cx, arg_ty, default_trait_id, Vec::new()) {
540 span_lint_and_then(cx,
543 &format!("use of `{}` followed by a call to `{}`", name, path),
545 db.span_suggestion(span, "try this",
546 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")));
557 /// Check for `*or(foo())`.
558 fn check_general_case(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr, or_has_args: bool,
560 // don't lint for constant values
561 // FIXME: can we `expect` here instead of match?
562 if let Some(qualif) = cx.tcx.const_qualif_map.borrow().get(&arg.id) {
563 if !qualif.contains(ConstQualif::NOT_CONST) {
567 // (path, fn_has_argument, methods, suffix)
568 let know_types: &[(&[_], _, &[_], _)] = &[(&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
569 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
572 &["map_or", "ok_or", "or", "unwrap_or"],
574 (&paths::RESULT, true, &["or", "unwrap_or"], "else")];
576 let self_ty = cx.tcx.expr_ty(self_expr);
578 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
579 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0)) {
580 (fn_has_arguments, poss, suffix)
585 if !poss.contains(&name) {
589 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
590 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
591 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
592 (false, true) => snippet(cx, fun.span, ".."),
595 span_lint_and_then(cx, OR_FUN_CALL, span, &format!("use of `{}` followed by a function call", name), |db| {
596 db.span_suggestion(span,
598 format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg));
603 if let hir::ExprCall(ref fun, ref or_args) = args[1].node {
604 let or_has_args = !or_args.is_empty();
605 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
606 check_general_case(cx, name, fun, &args[0], &args[1], or_has_args, expr.span);
612 /// Checks for the `CLONE_ON_COPY` lint.
613 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr) {
614 let ty = cx.tcx.expr_ty(expr);
615 let parent = cx.tcx.map.get_parent(expr.id);
616 let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, parent);
618 if !ty.moves_by_default(cx.tcx.global_tcx(), ¶meter_environment, expr.span) {
619 span_lint(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type");
623 /// Checks for the `CLONE_DOUBLE_REF` lint.
624 fn lint_clone_double_ref(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, ty: ty::Ty) {
625 if let ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) = ty.sty {
626 if let ty::TyRef(..) = inner.sty {
627 span_lint_and_then(cx,
630 "using `clone` on a double-reference; \
631 this will copy the reference instead of cloning the inner type",
632 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
633 db.span_suggestion(expr.span, "try dereferencing it", format!("({}).clone()", snip.deref()));
639 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &MethodArgs) {
640 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.expr_ty(&args[0]));
641 if !match_type(cx, obj_ty, &paths::VEC) {
644 let arg_ty = cx.tcx.expr_ty(&args[1]);
645 if let Some(slice) = derefs_to_slice(cx, &args[1], &arg_ty) {
646 span_lint_and_then(cx, EXTEND_FROM_SLICE, expr.span, "use of `extend` to extend a Vec by a slice", |db| {
647 db.span_suggestion(expr.span,
649 format!("{}.extend_from_slice({})",
650 snippet(cx, args[0].span, "_"),
656 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
658 let hir::ExprCall(ref fun, ref args) = new.node,
660 let hir::ExprPath(None, ref path) = fun.node,
661 match_path(path, &paths::CSTRING_NEW),
663 span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
664 "you are getting the inner pointer of a temporary `CString`",
666 db.note("that pointer will be invalid outside this expression");
667 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
673 // Type of MethodArgs is potentially a Vec
674 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &MethodArgs, is_mut: bool){
675 let mut_str = if is_mut { "_mut" } else {""};
676 let caller_type = if let Some(_) = derefs_to_slice(cx, &iter_args[0], &cx.tcx.expr_ty(&iter_args[0])) {
679 else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC) {
682 else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
686 return; // caller is not a type that we want to lint
693 &format!("called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
694 mut_str, caller_type)
698 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: &ty::Ty) -> Option<sugg::Sugg<'static>> {
699 fn may_slice(cx: &LateContext, ty: &ty::Ty) -> bool {
701 ty::TySlice(_) => true,
702 ty::TyStruct(..) => match_type(cx, ty, &paths::VEC),
703 ty::TyArray(_, size) => size < 32,
704 ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) |
705 ty::TyBox(ref inner) => may_slice(cx, inner),
710 if let hir::ExprMethodCall(name, _, ref args) = expr.node {
711 if &name.node.as_str() == &"iter" && may_slice(cx, &cx.tcx.expr_ty(&args[0])) {
712 sugg::Sugg::hir_opt(cx, &*args[0]).map(|sugg| {
720 ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
721 ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) |
722 ty::TyBox(ref inner) => {
723 if may_slice(cx, inner) {
724 sugg::Sugg::hir_opt(cx, expr)
735 // Type of MethodArgs is potentially a Vec
736 /// lint use of `unwrap()` for `Option`s and `Result`s
737 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &MethodArgs) {
738 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.expr_ty(&unwrap_args[0]));
740 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
741 Some((OPTION_UNWRAP_USED, "an Option", "None"))
742 } else if match_type(cx, obj_ty, &paths::RESULT) {
743 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
748 if let Some((lint, kind, none_value)) = mess {
752 &format!("used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
753 using expect() to provide a better panic
761 // Type of MethodArgs is potentially a Vec
762 /// lint use of `ok().expect()` for `Result`s
763 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &MethodArgs) {
764 // lint if the caller of `ok()` is a `Result`
765 if match_type(cx, cx.tcx.expr_ty(&ok_args[0]), &paths::RESULT) {
766 let result_type = cx.tcx.expr_ty(&ok_args[0]);
767 if let Some(error_type) = get_error_type(cx, result_type) {
768 if has_debug_impl(error_type, cx) {
772 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`");
779 // Type of MethodArgs is potentially a Vec
780 /// lint use of `map().unwrap_or()` for `Option`s
781 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
782 // lint if the caller of `map()` is an `Option`
783 if match_type(cx, cx.tcx.expr_ty(&map_args[0]), &paths::OPTION) {
785 let msg = "called `map(f).unwrap_or(a)` on an Option value. This can be done more directly by calling \
786 `map_or(a, f)` instead";
787 // get snippets for args to map() and unwrap_or()
788 let map_snippet = snippet(cx, map_args[1].span, "..");
789 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
790 // lint, with note if neither arg is > 1 line and both map() and
791 // unwrap_or() have the same span
792 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
793 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
794 if same_span && !multiline {
795 span_note_and_lint(cx,
796 OPTION_MAP_UNWRAP_OR,
800 &format!("replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
803 } else if same_span && multiline {
804 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
810 // Type of MethodArgs is potentially a Vec
811 /// lint use of `map().unwrap_or_else()` for `Option`s
812 fn lint_map_unwrap_or_else(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
813 // lint if the caller of `map()` is an `Option`
814 if match_type(cx, cx.tcx.expr_ty(&map_args[0]), &paths::OPTION) {
816 let msg = "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
817 `map_or_else(g, f)` instead";
818 // get snippets for args to map() and unwrap_or_else()
819 let map_snippet = snippet(cx, map_args[1].span, "..");
820 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
821 // lint, with note if neither arg is > 1 line and both map() and
822 // unwrap_or_else() have the same span
823 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
824 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
825 if same_span && !multiline {
826 span_note_and_lint(cx,
827 OPTION_MAP_UNWRAP_OR_ELSE,
831 &format!("replace `map({0}).unwrap_or_else({1})` with `with map_or_else({1}, {0})`",
834 } else if same_span && multiline {
835 span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
841 // Type of MethodArgs is potentially a Vec
842 /// lint use of `filter().next()` for `Iterators`
843 fn lint_filter_next(cx: &LateContext, expr: &hir::Expr, filter_args: &MethodArgs) {
844 // lint if caller of `.filter().next()` is an Iterator
845 if match_trait_method(cx, expr, &paths::ITERATOR) {
846 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling `.find(p)` \
848 let filter_snippet = snippet(cx, filter_args[1].span, "..");
849 if filter_snippet.lines().count() <= 1 {
850 // add note if not multi-line
851 span_note_and_lint(cx,
856 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet));
858 span_lint(cx, FILTER_NEXT, expr.span, msg);
863 // Type of MethodArgs is potentially a Vec
864 /// lint use of `filter().map()` for `Iterators`
865 fn lint_filter_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
866 // lint if caller of `.filter().map()` is an Iterator
867 if match_trait_method(cx, expr, &paths::ITERATOR) {
868 let msg = "called `filter(p).map(q)` on an `Iterator`. \
869 This is more succinctly expressed by calling `.filter_map(..)` instead.";
870 span_lint(cx, FILTER_MAP, expr.span, msg);
874 // Type of MethodArgs is potentially a Vec
875 /// lint use of `filter().map()` for `Iterators`
876 fn lint_filter_map_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
877 // lint if caller of `.filter().map()` is an Iterator
878 if match_trait_method(cx, expr, &paths::ITERATOR) {
879 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
880 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
881 span_lint(cx, FILTER_MAP, expr.span, msg);
885 // Type of MethodArgs is potentially a Vec
886 /// lint use of `filter().flat_map()` for `Iterators`
887 fn lint_filter_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
888 // lint if caller of `.filter().flat_map()` is an Iterator
889 if match_trait_method(cx, expr, &paths::ITERATOR) {
890 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
891 This is more succinctly expressed by calling `.flat_map(..)` \
892 and filtering by returning an empty Iterator.";
893 span_lint(cx, FILTER_MAP, expr.span, msg);
897 // Type of MethodArgs is potentially a Vec
898 /// lint use of `filter_map().flat_map()` for `Iterators`
899 fn lint_filter_map_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
900 // lint if caller of `.filter_map().flat_map()` is an Iterator
901 if match_trait_method(cx, expr, &paths::ITERATOR) {
902 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
903 This is more succinctly expressed by calling `.flat_map(..)` \
904 and filtering by returning an empty Iterator.";
905 span_lint(cx, FILTER_MAP, expr.span, msg);
910 // Type of MethodArgs is potentially a Vec
911 /// lint searching an Iterator followed by `is_some()`
912 fn lint_search_is_some(cx: &LateContext, expr: &hir::Expr, search_method: &str, search_args: &MethodArgs,
913 is_some_args: &MethodArgs) {
914 // lint if caller of search is an Iterator
915 if match_trait_method(cx, &*is_some_args[0], &paths::ITERATOR) {
916 let msg = format!("called `is_some()` after searching an `Iterator` with {}. This is more succinctly expressed \
917 by calling `any()`.",
919 let search_snippet = snippet(cx, search_args[1].span, "..");
920 if search_snippet.lines().count() <= 1 {
921 // add note if not multi-line
922 span_note_and_lint(cx,
927 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet));
929 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
934 /// Checks for the `CHARS_NEXT_CMP` lint.
935 fn lint_chars_next(cx: &LateContext, expr: &hir::Expr, chain: &hir::Expr, other: &hir::Expr, eq: bool) -> bool {
937 let Some(args) = method_chain_args(chain, &["chars", "next"]),
938 let hir::ExprCall(ref fun, ref arg_char) = other.node,
940 let hir::ExprPath(None, ref path) = fun.node,
941 path.segments.len() == 1 && path.segments[0].name.as_str() == "Some"
943 let self_ty = walk_ptrs_ty(cx.tcx.expr_ty_adjusted(&args[0][0]));
945 if self_ty.sty != ty::TyStr {
949 span_lint_and_then(cx,
952 "you should use the `starts_with` method",
954 let sugg = format!("{}{}.starts_with({})",
955 if eq { "" } else { "!" },
956 snippet(cx, args[0][0].span, "_"),
957 snippet(cx, arg_char[0].span, "_")
960 db.span_suggestion(expr.span, "like this", sugg);
969 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
970 fn lint_single_char_pattern(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
971 if let Ok(ConstVal::Str(r)) = eval_const_expr_partial(cx.tcx, arg, ExprTypeChecked, None) {
973 let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
974 span_lint_and_then(cx,
977 "single-character string constant used as pattern",
979 db.span_suggestion(expr.span, "try using a char instead:", hint);
985 /// Given a `Result<T, E>` type, return its error type (`E`).
986 fn get_error_type<'a>(cx: &LateContext, ty: ty::Ty<'a>) -> Option<ty::Ty<'a>> {
987 if !match_type(cx, ty, &paths::RESULT) {
990 if let ty::TyEnum(_, substs) = ty.sty {
991 if let Some(err_ty) = substs.types.opt_get(TypeSpace, 1) {
998 /// This checks whether a given type is known to implement Debug.
999 fn has_debug_impl<'a, 'b>(ty: ty::Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1000 match cx.tcx.lang_items.debug_trait() {
1001 Some(debug) => implements_trait(cx, ty, debug, Vec::new()),
1008 StartsWith(&'static str),
1011 #[cfg_attr(rustfmt, rustfmt_skip)]
1012 const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
1013 (Convention::Eq("new"), &[SelfKind::No]),
1014 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1015 (Convention::StartsWith("from_"), &[SelfKind::No]),
1016 (Convention::StartsWith("into_"), &[SelfKind::Value]),
1017 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1018 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1021 #[cfg_attr(rustfmt, rustfmt_skip)]
1022 const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
1023 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1024 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1025 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1026 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1027 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1028 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1029 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1030 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1031 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1032 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1033 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1034 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1035 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1036 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1037 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1038 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1039 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1040 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1041 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1042 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1043 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1044 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1045 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1046 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1047 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1048 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1049 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1050 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1051 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1052 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1055 #[cfg_attr(rustfmt, rustfmt_skip)]
1056 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1064 ("split_terminator", 1),
1065 ("rsplit_terminator", 1),
1070 ("match_indices", 1),
1071 ("rmatch_indices", 1),
1072 ("trim_left_matches", 1),
1073 ("trim_right_matches", 1),
1077 #[derive(Clone, Copy)]
1086 fn matches(self, slf: &hir::ExplicitSelf, allow_value_for_ref: bool) -> bool {
1087 match (self, &slf.node) {
1088 (SelfKind::Value, &hir::SelfKind::Value(_)) |
1089 (SelfKind::Ref, &hir::SelfKind::Region(_, hir::Mutability::MutImmutable)) |
1090 (SelfKind::RefMut, &hir::SelfKind::Region(_, hir::Mutability::MutMutable)) => true,
1091 (SelfKind::Ref, &hir::SelfKind::Value(_)) |
1092 (SelfKind::RefMut, &hir::SelfKind::Value(_)) => allow_value_for_ref,
1093 (_, &hir::SelfKind::Explicit(ref ty, _)) => self.matches_explicit_type(ty, allow_value_for_ref),
1099 fn matches_explicit_type(self, ty: &hir::Ty, allow_value_for_ref: bool) -> bool {
1100 match (self, &ty.node) {
1101 (SelfKind::Value, &hir::TyPath(..)) |
1102 (SelfKind::Ref, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutImmutable, .. })) |
1103 (SelfKind::RefMut, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutMutable, .. })) => true,
1104 (SelfKind::Ref, &hir::TyPath(..)) |
1105 (SelfKind::RefMut, &hir::TyPath(..)) => allow_value_for_ref,
1110 fn description(&self) -> &'static str {
1112 SelfKind::Value => "self by value",
1113 SelfKind::Ref => "self by reference",
1114 SelfKind::RefMut => "self by mutable reference",
1115 SelfKind::No => "no self",
1121 fn check(&self, other: &str) -> bool {
1123 Convention::Eq(this) => this == other,
1124 Convention::StartsWith(this) => other.starts_with(this),
1129 impl fmt::Display for Convention {
1130 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1132 Convention::Eq(this) => this.fmt(f),
1133 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1138 #[derive(Clone, Copy)]
1147 fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1149 (&OutType::Unit, &hir::DefaultReturn(_)) => true,
1150 (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
1151 (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
1152 (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
1153 (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
1159 fn is_bool(ty: &hir::Ty) -> bool {
1160 if let hir::TyPath(None, ref p) = ty.node {
1161 match_path(p, &["bool"])