3 use rustc::middle::const_val::ConstVal;
4 use rustc::middle::const_qualif::ConstQualif;
5 use rustc::ty::subst::{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, match_path, match_trait_method,
14 match_type, method_chain_args, return_ty, same_tys, snippet, snippet_opt, span_lint,
15 span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
16 use utils::MethodArgs;
20 pub struct MethodsPass;
22 /// **What it does:** This lint checks for `.unwrap()` calls on `Option`s.
24 /// **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.
26 /// **Known problems:** None
28 /// **Example:** `x.unwrap()`
30 pub OPTION_UNWRAP_USED, Allow,
31 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
34 /// **What it does:** This lint checks for `.unwrap()` calls on `Result`s.
36 /// **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!`.
38 /// 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.
40 /// **Known problems:** None
42 /// **Example:** `x.unwrap()`
44 pub RESULT_UNWRAP_USED, Allow,
45 "using `Result.unwrap()`, which might be better handled"
48 /// **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.
50 /// **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.
52 /// **Known problems:** None
58 /// fn add(&self, other: &X) -> X { .. }
62 pub SHOULD_IMPLEMENT_TRAIT, Warn,
63 "defining a method that should be implementing a std trait"
66 /// **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:
68 /// |Prefix |`self` taken |
69 /// |-------|--------------------|
70 /// |`as_` |`&self` or &mut self|
73 /// |`is_` |`&self` or none |
76 /// **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.
78 /// **Known problems:** None
84 /// fn as_str(self) -> &str { .. }
88 pub WRONG_SELF_CONVENTION, Warn,
89 "defining a method named with an established prefix (like \"into_\") that takes \
90 `self` with the wrong convention"
93 /// **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but for public items.
95 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
97 /// **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.
102 /// pub fn as_str(self) -> &str { .. }
106 pub WRONG_PUB_SELF_CONVENTION, Allow,
107 "defining a public method named with an established prefix (like \"into_\") that takes \
108 `self` with the wrong convention"
111 /// **What it does:** This lint checks for usage of `ok().expect(..)`.
113 /// **Why is this bad?** Because you usually call `expect()` on the `Result` directly to get a good error message.
115 /// **Known problems:** None.
117 /// **Example:** `x.ok().expect("why did I do this again?")`
120 "using `ok().expect()`, which gives worse error messages than \
121 calling `expect` directly on the Result"
124 /// **What it does:** This lint checks for usage of `_.map(_).unwrap_or(_)`.
126 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or(_, _)`.
128 /// **Known problems:** None.
130 /// **Example:** `x.map(|a| a + 1).unwrap_or(0)`
132 pub OPTION_MAP_UNWRAP_OR, Warn,
133 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
137 /// **What it does:** This lint `Warn`s on `_.map(_).unwrap_or_else(_)`.
139 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or_else(_, _)`.
141 /// **Known problems:** None.
143 /// **Example:** `x.map(|a| a + 1).unwrap_or_else(some_function)`
145 pub OPTION_MAP_UNWRAP_OR_ELSE, Warn,
146 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
150 /// **What it does:** This lint `Warn`s on `_.filter(_).next()`.
152 /// **Why is this bad?** Readability, this can be written more concisely as `_.find(_)`.
154 /// **Known problems:** None.
156 /// **Example:** `iter.filter(|x| x == 0).next()`
158 pub FILTER_NEXT, Warn,
159 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
162 /// **What it does:** This lint `Warn`s on an iterator search (such as `find()`, `position()`, or
163 /// `rposition()`) followed by a call to `is_some()`.
165 /// **Why is this bad?** Readability, this can be written more concisely as `_.any(_)`.
167 /// **Known problems:** None.
169 /// **Example:** `iter.find(|x| x == 0).is_some()`
171 pub SEARCH_IS_SOME, Warn,
172 "using an iterator search followed by `is_some()`, which is more succinctly \
173 expressed as a call to `any()`"
176 /// **What it does:** This lint `Warn`s on using `.chars().next()` on a `str` to check if it
177 /// starts with a given char.
179 /// **Why is this bad?** Readability, this can be written more concisely as `_.starts_with(_)`.
181 /// **Known problems:** None.
183 /// **Example:** `name.chars().next() == Some('_')`
185 pub CHARS_NEXT_CMP, Warn,
186 "using `.chars().next()` to check if a string starts with a char"
189 /// **What it does:** This lint checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, etc., and
190 /// suggests to use `or_else`, `unwrap_or_else`, etc., or `unwrap_or_default` instead.
192 /// **Why is this bad?** The function will always be called and potentially allocate an object
193 /// in expressions such as:
195 /// foo.unwrap_or(String::new())
197 /// this can instead be written:
199 /// foo.unwrap_or_else(String::new)
203 /// foo.unwrap_or_default()
206 /// **Known problems:** If the function as side-effects, not calling it will change the semantic of
207 /// the program, but you shouldn't rely on that anyway.
209 pub OR_FUN_CALL, Warn,
210 "using any `*or` method when the `*or_else` would do"
213 /// **What it does:** This lint checks for usage of `.extend(s)` on a `Vec` to extend the vector by a slice.
215 /// **Why is this bad?** Since Rust 1.6, the `extend_from_slice(_)` method is stable and at least for now faster.
217 /// **Known problems:** None.
219 /// **Example:** `my_vec.extend(&xs)`
221 pub EXTEND_FROM_SLICE, Warn,
222 "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
225 /// **What it does:** This lint warns on using `.clone()` on a `Copy` type.
227 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for generics, not for
228 /// using the `clone` method on a concrete type.
230 /// **Known problems:** None.
232 /// **Example:** `42u64.clone()`
234 pub CLONE_ON_COPY, Warn, "using `clone` on a `Copy` type"
237 /// **What it does:** This lint warns on using `.clone()` on an `&&T`
239 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of cloning the underlying
242 /// **Known problems:** None.
249 /// let z = y.clone();
250 /// println!("{:p} {:p}",*y, z); // prints out the same pointer
254 pub CLONE_DOUBLE_REF, Warn, "using `clone` on `&&T`"
257 /// **What it does:** This lint warns about `new` not returning `Self`.
259 /// **Why is this bad?** As a convention, `new` methods are used to make a new instance of a type.
261 /// **Known problems:** None.
266 /// fn new(..) -> NotAFoo {
271 pub NEW_RET_NO_SELF, Warn, "not returning `Self` in a `new` method"
274 /// **What it does:** This lint checks for string methods that receive a single-character `str` as an argument, e.g. `_.split("x")`.
276 /// **Why is this bad?** Performing these methods using a `char` is faster than using a `str`.
278 /// **Known problems:** Does not catch multi-byte unicode characters.
280 /// **Example:** `_.split("x")` could be `_.split('x')`
282 pub SINGLE_CHAR_PATTERN,
284 "using a single-character str where a char could be used, e.g. \
288 /// **What it does:** This lint checks for getting the inner pointer of a temporary `CString`.
290 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long as the `CString` is
293 /// **Known problems:** None.
297 /// let c_str = CString::new("foo").unwrap().as_ptr();
299 /// call_some_ffi_func(c_str);
302 /// Here `c_str` point to a freed address. The correct use would be:
304 /// let c_str = CString::new("foo").unwrap();
306 /// call_some_ffi_func(c_str.as_ptr());
310 pub TEMPORARY_CSTRING_AS_PTR,
312 "getting the inner pointer of a temporary `CString`"
315 impl LintPass for MethodsPass {
316 fn get_lints(&self) -> LintArray {
317 lint_array!(EXTEND_FROM_SLICE,
320 SHOULD_IMPLEMENT_TRAIT,
321 WRONG_SELF_CONVENTION,
322 WRONG_PUB_SELF_CONVENTION,
324 OPTION_MAP_UNWRAP_OR,
325 OPTION_MAP_UNWRAP_OR_ELSE,
333 TEMPORARY_CSTRING_AS_PTR)
337 impl LateLintPass for MethodsPass {
338 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
339 if in_macro(cx, expr.span) {
344 ExprMethodCall(name, _, ref args) => {
346 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
347 lint_unwrap(cx, expr, arglists[0]);
348 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
349 lint_ok_expect(cx, expr, arglists[0]);
350 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
351 lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
352 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
353 lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
354 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
355 lint_filter_next(cx, expr, arglists[0]);
356 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
357 lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
358 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
359 lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
360 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
361 lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
362 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
363 lint_extend(cx, expr, arglists[0]);
364 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
365 lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
368 lint_or_fun_call(cx, expr, &name.node.as_str(), args);
370 let self_ty = cx.tcx.expr_ty_adjusted(&args[0]);
371 if args.len() == 1 && name.node.as_str() == "clone" {
372 lint_clone_on_copy(cx, expr);
373 lint_clone_double_ref(cx, expr, &args[0], self_ty);
377 ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
378 for &(method, pos) in &PATTERN_METHODS {
379 if name.node.as_str() == method && args.len() > pos {
380 lint_single_char_pattern(cx, expr, &args[pos]);
387 ExprBinary(op, ref lhs, ref rhs) if op.node == BiEq || op.node == BiNe => {
388 if !lint_chars_next(cx, expr, lhs, rhs, op.node == BiEq) {
389 lint_chars_next(cx, expr, rhs, lhs, op.node == BiEq);
396 fn check_item(&mut self, cx: &LateContext, item: &Item) {
397 if in_external_macro(cx, item.span) {
401 if let ItemImpl(_, _, _, None, _, ref items) = item.node {
402 for implitem in items {
403 let name = implitem.name;
404 if let ImplItemKind::Method(ref sig, _) = implitem.node {
405 // check missing trait implementations
406 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
409 name.as_str() == method_name,
410 sig.decl.inputs.len() == n_args,
411 out_type.matches(&sig.decl.output),
412 self_kind.matches(&sig.explicit_self.node, false)
414 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
415 "defining a method called `{}` on this type; consider implementing \
416 the `{}` trait or choosing a less ambiguous name", name, trait_name));
421 // check conventions w.r.t. conversion method names and predicates
422 let ty = cx.tcx.lookup_item_type(cx.tcx.map.local_def_id(item.id)).ty;
423 let is_copy = is_copy(cx, ty, item);
424 for &(ref conv, self_kinds) in &CONVENTIONS {
425 if conv.check(&name.as_str()) &&
426 !self_kinds.iter().any(|k| k.matches(&sig.explicit_self.node, is_copy)) {
427 let lint = if item.vis == Visibility::Public {
428 WRONG_PUB_SELF_CONVENTION
430 WRONG_SELF_CONVENTION
434 sig.explicit_self.span,
435 &format!("methods called `{}` usually take {}; consider choosing a less \
439 .map(|k| k.description())
445 let ret_ty = return_ty(cx, implitem.id);
446 if &name.as_str() == &"new" &&
447 !ret_ty.map_or(false, |ret_ty| ret_ty.walk().any(|t| same_tys(cx, t, ty, implitem.id))) {
450 sig.explicit_self.span,
451 "methods called `new` usually return `Self`");
459 /// Checks for the `OR_FUN_CALL` lint.
460 fn lint_or_fun_call(cx: &LateContext, expr: &Expr, name: &str, args: &[P<Expr>]) {
461 /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
462 fn check_unwrap_or_default(cx: &LateContext, name: &str, fun: &Expr, self_expr: &Expr, arg: &Expr,
463 or_has_args: bool, span: Span)
469 if name == "unwrap_or" {
470 if let ExprPath(_, ref path) = fun.node {
471 let path: &str = &path.segments
473 .expect("A path must have at least one segment")
478 if ["default", "new"].contains(&path) {
479 let arg_ty = cx.tcx.expr_ty(arg);
480 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
486 if implements_trait(cx, arg_ty, default_trait_id, Vec::new()) {
490 &format!("use of `{}` followed by a call to `{}`", name, path))
491 .span_suggestion(span,
493 format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")));
503 /// Check for `*or(foo())`.
504 fn check_general_case(cx: &LateContext, name: &str, fun: &Expr, self_expr: &Expr, arg: &Expr, or_has_args: bool,
506 // don't lint for constant values
507 // FIXME: can we `expect` here instead of match?
508 if let Some(qualif) = cx.tcx.const_qualif_map.borrow().get(&arg.id) {
509 if !qualif.contains(ConstQualif::NOT_CONST) {
513 // (path, fn_has_argument, methods)
514 let know_types: &[(&[_], _, &[_], _)] = &[(&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
515 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
518 &["map_or", "ok_or", "or", "unwrap_or"],
520 (&paths::RESULT, true, &["or", "unwrap_or"], "else")];
522 let self_ty = cx.tcx.expr_ty(self_expr);
524 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
525 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0)) {
526 (fn_has_arguments, poss, suffix)
531 if !poss.contains(&name) {
535 let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
536 (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
537 (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
538 (false, true) => snippet(cx, fun.span, ".."),
541 span_lint(cx, OR_FUN_CALL, span, &format!("use of `{}` followed by a function call", name))
542 .span_suggestion(span,
544 format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg));
548 if let ExprCall(ref fun, ref or_args) = args[1].node {
549 let or_has_args = !or_args.is_empty();
550 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
551 check_general_case(cx, name, fun, &args[0], &args[1], or_has_args, expr.span);
557 /// Checks for the `CLONE_ON_COPY` lint.
558 fn lint_clone_on_copy(cx: &LateContext, expr: &Expr) {
559 let ty = cx.tcx.expr_ty(expr);
560 let parent = cx.tcx.map.get_parent(expr.id);
561 let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, parent);
563 if !ty.moves_by_default(cx.tcx.global_tcx(), ¶meter_environment, expr.span) {
564 span_lint(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type");
568 /// Checks for the `CLONE_DOUBLE_REF` lint.
569 fn lint_clone_double_ref(cx: &LateContext, expr: &Expr, arg: &Expr, ty: ty::Ty) {
570 if let ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) = ty.sty {
571 if let ty::TyRef(..) = inner.sty {
572 let mut db = span_lint(cx,
575 "using `clone` on a double-reference; \
576 this will copy the reference instead of cloning \
578 if let Some(snip) = snippet_opt(cx, arg.span) {
579 db.span_suggestion(expr.span, "try dereferencing it", format!("(*{}).clone()", snip));
585 fn lint_extend(cx: &LateContext, expr: &Expr, args: &MethodArgs) {
586 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.expr_ty(&args[0]));
587 if !match_type(cx, obj_ty, &paths::VEC) {
590 let arg_ty = cx.tcx.expr_ty(&args[1]);
591 if let Some((span, r)) = derefs_to_slice(cx, &args[1], &arg_ty) {
592 span_lint(cx, EXTEND_FROM_SLICE, expr.span, "use of `extend` to extend a Vec by a slice")
593 .span_suggestion(expr.span,
595 format!("{}.extend_from_slice({}{})",
596 snippet(cx, args[0].span, "_"),
598 snippet(cx, span, "_")));
602 fn lint_cstring_as_ptr(cx: &LateContext, expr: &Expr, new: &Expr, unwrap: &Expr) {
604 let ExprCall(ref fun, ref args) = new.node,
606 let ExprPath(None, ref path) = fun.node,
607 match_path(path, &paths::CSTRING_NEW),
609 span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
610 "you are getting the inner pointer of a temporary `CString`",
612 db.note("that pointer will be invalid outside this expression");
613 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
618 fn derefs_to_slice(cx: &LateContext, expr: &Expr, ty: &ty::Ty) -> Option<(Span, &'static str)> {
619 fn may_slice(cx: &LateContext, ty: &ty::Ty) -> bool {
621 ty::TySlice(_) => true,
622 ty::TyStruct(..) => match_type(cx, ty, &paths::VEC),
623 ty::TyArray(_, size) => size < 32,
624 ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) |
625 ty::TyBox(ref inner) => may_slice(cx, inner),
629 if let ExprMethodCall(name, _, ref args) = expr.node {
630 if &name.node.as_str() == &"iter" && may_slice(cx, &cx.tcx.expr_ty(&args[0])) {
631 Some((args[0].span, "&"))
637 ty::TySlice(_) => Some((expr.span, "")),
638 ty::TyRef(_, ty::TypeAndMut { ty: ref inner, .. }) |
639 ty::TyBox(ref inner) => {
640 if may_slice(cx, inner) {
641 Some((expr.span, ""))
652 // Type of MethodArgs is potentially a Vec
653 /// lint use of `unwrap()` for `Option`s and `Result`s
654 fn lint_unwrap(cx: &LateContext, expr: &Expr, unwrap_args: &MethodArgs) {
655 let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.expr_ty(&unwrap_args[0]));
657 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
658 Some((OPTION_UNWRAP_USED, "an Option", "None"))
659 } else if match_type(cx, obj_ty, &paths::RESULT) {
660 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
665 if let Some((lint, kind, none_value)) = mess {
669 &format!("used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
670 using expect() to provide a better panic
678 // Type of MethodArgs is potentially a Vec
679 /// lint use of `ok().expect()` for `Result`s
680 fn lint_ok_expect(cx: &LateContext, expr: &Expr, ok_args: &MethodArgs) {
681 // lint if the caller of `ok()` is a `Result`
682 if match_type(cx, cx.tcx.expr_ty(&ok_args[0]), &paths::RESULT) {
683 let result_type = cx.tcx.expr_ty(&ok_args[0]);
684 if let Some(error_type) = get_error_type(cx, result_type) {
685 if has_debug_impl(error_type, cx) {
689 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`");
696 // Type of MethodArgs is potentially a Vec
697 /// lint use of `map().unwrap_or()` for `Option`s
698 fn lint_map_unwrap_or(cx: &LateContext, expr: &Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
699 // lint if the caller of `map()` is an `Option`
700 if match_type(cx, cx.tcx.expr_ty(&map_args[0]), &paths::OPTION) {
702 let msg = "called `map(f).unwrap_or(a)` on an Option value. This can be done more directly by calling \
703 `map_or(a, f)` instead";
704 // get snippets for args to map() and unwrap_or()
705 let map_snippet = snippet(cx, map_args[1].span, "..");
706 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
707 // lint, with note if neither arg is > 1 line and both map() and
708 // unwrap_or() have the same span
709 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
710 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
711 if same_span && !multiline {
712 span_note_and_lint(cx,
713 OPTION_MAP_UNWRAP_OR,
717 &format!("replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
720 } else if same_span && multiline {
721 span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
727 // Type of MethodArgs is potentially a Vec
728 /// lint use of `map().unwrap_or_else()` for `Option`s
729 fn lint_map_unwrap_or_else(cx: &LateContext, expr: &Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
730 // lint if the caller of `map()` is an `Option`
731 if match_type(cx, cx.tcx.expr_ty(&map_args[0]), &paths::OPTION) {
733 let msg = "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
734 `map_or_else(g, f)` instead";
735 // get snippets for args to map() and unwrap_or_else()
736 let map_snippet = snippet(cx, map_args[1].span, "..");
737 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
738 // lint, with note if neither arg is > 1 line and both map() and
739 // unwrap_or_else() have the same span
740 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
741 let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
742 if same_span && !multiline {
743 span_note_and_lint(cx,
744 OPTION_MAP_UNWRAP_OR_ELSE,
748 &format!("replace `map({0}).unwrap_or_else({1})` with `with map_or_else({1}, {0})`",
751 } else if same_span && multiline {
752 span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
758 // Type of MethodArgs is potentially a Vec
759 /// lint use of `filter().next() for Iterators`
760 fn lint_filter_next(cx: &LateContext, expr: &Expr, filter_args: &MethodArgs) {
761 // lint if caller of `.filter().next()` is an Iterator
762 if match_trait_method(cx, expr, &paths::ITERATOR) {
763 let msg = "called `filter(p).next()` on an Iterator. This is more succinctly expressed by calling `.find(p)` \
765 let filter_snippet = snippet(cx, filter_args[1].span, "..");
766 if filter_snippet.lines().count() <= 1 {
767 // add note if not multi-line
768 span_note_and_lint(cx,
773 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet));
775 span_lint(cx, FILTER_NEXT, expr.span, msg);
781 // Type of MethodArgs is potentially a Vec
782 /// lint searching an Iterator followed by `is_some()`
783 fn lint_search_is_some(cx: &LateContext, expr: &Expr, search_method: &str, search_args: &MethodArgs,
784 is_some_args: &MethodArgs) {
785 // lint if caller of search is an Iterator
786 if match_trait_method(cx, &*is_some_args[0], &paths::ITERATOR) {
787 let msg = format!("called `is_some()` after searching an iterator with {}. This is more succinctly expressed \
788 by calling `any()`.",
790 let search_snippet = snippet(cx, search_args[1].span, "..");
791 if search_snippet.lines().count() <= 1 {
792 // add note if not multi-line
793 span_note_and_lint(cx,
798 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet));
800 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
805 /// Checks for the `CHARS_NEXT_CMP` lint.
806 fn lint_chars_next(cx: &LateContext, expr: &Expr, chain: &Expr, other: &Expr, eq: bool) -> bool {
808 let Some(args) = method_chain_args(chain, &["chars", "next"]),
809 let ExprCall(ref fun, ref arg_char) = other.node,
811 let ExprPath(None, ref path) = fun.node,
812 path.segments.len() == 1 && path.segments[0].identifier.name.as_str() == "Some"
814 let self_ty = walk_ptrs_ty(cx.tcx.expr_ty_adjusted(&args[0][0]));
816 if self_ty.sty != ty::TyStr {
820 span_lint_and_then(cx,
823 "you should use the `starts_with` method",
825 let sugg = format!("{}{}.starts_with({})",
826 if eq { "" } else { "!" },
827 snippet(cx, args[0][0].span, "_"),
828 snippet(cx, arg_char[0].span, "_")
831 db.span_suggestion(expr.span, "like this", sugg);
840 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
841 fn lint_single_char_pattern(cx: &LateContext, expr: &Expr, arg: &Expr) {
842 if let Ok(ConstVal::Str(r)) = eval_const_expr_partial(cx.tcx, arg, ExprTypeChecked, None) {
844 let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
845 span_lint_and_then(cx,
848 "single-character string constant used as pattern",
850 db.span_suggestion(expr.span, "try using a char instead:", hint);
856 /// Given a `Result<T, E>` type, return its error type (`E`).
857 fn get_error_type<'a>(cx: &LateContext, ty: ty::Ty<'a>) -> Option<ty::Ty<'a>> {
858 if !match_type(cx, ty, &paths::RESULT) {
861 if let ty::TyEnum(_, substs) = ty.sty {
862 if let Some(err_ty) = substs.types.opt_get(TypeSpace, 1) {
869 /// This checks whether a given type is known to implement Debug.
870 fn has_debug_impl<'a, 'b>(ty: ty::Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
871 match cx.tcx.lang_items.debug_trait() {
872 Some(debug) => implements_trait(cx, ty, debug, Vec::new()),
879 StartsWith(&'static str),
882 #[cfg_attr(rustfmt, rustfmt_skip)]
883 const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
884 (Convention::Eq("new"), &[SelfKind::No]),
885 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
886 (Convention::StartsWith("from_"), &[SelfKind::No]),
887 (Convention::StartsWith("into_"), &[SelfKind::Value]),
888 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
889 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
892 #[cfg_attr(rustfmt, rustfmt_skip)]
893 const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
894 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
895 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
896 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
897 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
898 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
899 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
900 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
901 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
902 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
903 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
904 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
905 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
906 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
907 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
908 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
909 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
910 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
911 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
912 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
913 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
914 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
915 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
916 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
917 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
918 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
919 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
920 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
921 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
922 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
923 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
926 #[cfg_attr(rustfmt, rustfmt_skip)]
927 const PATTERN_METHODS: [(&'static str, usize); 17] = [
935 ("split_terminator", 1),
936 ("rsplit_terminator", 1),
941 ("match_indices", 1),
942 ("rmatch_indices", 1),
943 ("trim_left_matches", 1),
944 ("trim_right_matches", 1),
948 #[derive(Clone, Copy)]
957 fn matches(&self, slf: &ExplicitSelf_, allow_value_for_ref: bool) -> bool {
959 (&SelfKind::Value, &SelfValue(_)) |
960 (&SelfKind::Ref, &SelfRegion(_, Mutability::MutImmutable, _)) |
961 (&SelfKind::RefMut, &SelfRegion(_, Mutability::MutMutable, _)) |
962 (&SelfKind::No, &SelfStatic) => true,
963 (&SelfKind::Ref, &SelfValue(_)) |
964 (&SelfKind::RefMut, &SelfValue(_)) => allow_value_for_ref,
965 (_, &SelfExplicit(ref ty, _)) => self.matches_explicit_type(ty, allow_value_for_ref),
970 fn matches_explicit_type(&self, ty: &Ty, allow_value_for_ref: bool) -> bool {
971 match (self, &ty.node) {
972 (&SelfKind::Value, &TyPath(..)) |
973 (&SelfKind::Ref, &TyRptr(_, MutTy { mutbl: Mutability::MutImmutable, .. })) |
974 (&SelfKind::RefMut, &TyRptr(_, MutTy { mutbl: Mutability::MutMutable, .. })) => true,
975 (&SelfKind::Ref, &TyPath(..)) |
976 (&SelfKind::RefMut, &TyPath(..)) => allow_value_for_ref,
981 fn description(&self) -> &'static str {
983 SelfKind::Value => "self by value",
984 SelfKind::Ref => "self by reference",
985 SelfKind::RefMut => "self by mutable reference",
986 SelfKind::No => "no self",
992 fn check(&self, other: &str) -> bool {
994 Convention::Eq(this) => this == other,
995 Convention::StartsWith(this) => other.starts_with(this),
1000 impl fmt::Display for Convention {
1001 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1003 Convention::Eq(this) => this.fmt(f),
1004 Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1009 #[derive(Clone, Copy)]
1018 fn matches(&self, ty: &FunctionRetTy) -> bool {
1020 (&OutType::Unit, &DefaultReturn(_)) => true,
1021 (&OutType::Unit, &Return(ref ty)) if ty.node == TyTup(vec![].into()) => true,
1022 (&OutType::Bool, &Return(ref ty)) if is_bool(ty) => true,
1023 (&OutType::Any, &Return(ref ty)) if ty.node != TyTup(vec![].into()) => true,
1024 (&OutType::Ref, &Return(ref ty)) => {
1025 if let TyRptr(_, _) = ty.node {
1036 fn is_bool(ty: &Ty) -> bool {
1037 if let TyPath(None, ref p) = ty.node {
1038 if match_path(p, &["bool"]) {
1045 fn is_copy<'a, 'ctx>(cx: &LateContext<'a, 'ctx>, ty: ty::Ty<'ctx>, item: &Item) -> bool {
1046 let env = ty::ParameterEnvironment::for_item(cx.tcx, item.id);
1047 !ty.subst(cx.tcx, env.free_substs).moves_by_default(cx.tcx.global_tcx(), &env, item.span)