]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods.rs
Improve docs
[rust.git] / clippy_lints / src / methods.rs
1 use rustc::hir;
2 use rustc::lint::*;
3 use rustc::middle::const_val::ConstVal;
4 use rustc::middle::const_qualif::ConstQualif;
5 use rustc::ty::subst::TypeSpace;
6 use rustc::ty;
7 use rustc_const_eval::EvalHint::ExprTypeChecked;
8 use rustc_const_eval::eval_const_expr_partial;
9 use std::borrow::Cow;
10 use std::fmt;
11 use syntax::codemap::Span;
12 use syntax::ptr::P;
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;
17 use utils::paths;
18 use utils::sugg;
19
20 #[derive(Clone)]
21 pub struct Pass;
22
23 /// **What it does:** This lint checks for `.unwrap()` calls on `Option`s.
24 ///
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.
28 ///
29 /// **Known problems:** None
30 ///
31 /// **Example:**
32 /// ```rust
33 /// x.unwrap()
34 /// ```
35 declare_lint! {
36     pub OPTION_UNWRAP_USED, Allow,
37     "using `Option.unwrap()`, which should at least get a better message using `expect()`"
38 }
39
40 /// **What it does:** This lint checks for `.unwrap()` calls on `Result`s.
41 ///
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!`.
44 ///
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.
48 ///
49 /// **Known problems:** None
50 ///
51 /// **Example:**
52 /// ```rust
53 /// x.unwrap()
54 /// ```
55 declare_lint! {
56     pub RESULT_UNWRAP_USED, Allow,
57     "using `Result.unwrap()`, which might be better handled"
58 }
59
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.
63 ///
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.
67 ///
68 /// **Known problems:** None
69 ///
70 /// **Example:**
71 /// ```rust
72 /// struct X;
73 /// impl X {
74 ///    fn add(&self, other: &X) -> X { .. }
75 /// }
76 /// ```
77 declare_lint! {
78     pub SHOULD_IMPLEMENT_TRAIT, Warn,
79     "defining a method that should be implementing a std trait"
80 }
81
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:
84 ///
85 /// |Prefix |`self` taken          |
86 /// |-------|----------------------|
87 /// |`as_`  |`&self` or `&mut self`|
88 /// |`from_`| none                 |
89 /// |`into_`|`self`                |
90 /// |`is_`  |`&self` or none       |
91 /// |`to_`  |`&self`               |
92 ///
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.
95 ///
96 /// **Known problems:** None
97 ///
98 /// **Example**
99 ///
100 /// ```rust
101 /// impl X {
102 ///     fn as_str(self) -> &str { .. }
103 /// }
104 /// ```
105 declare_lint! {
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"
109 }
110
111 /// **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but
112 /// for public items.
113 ///
114 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
115 ///
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
118 /// users.
119 ///
120 /// **Example:**
121 /// ```rust
122 /// impl X {
123 ///     pub fn as_str(self) -> &str { .. }
124 /// }
125 /// ```
126 declare_lint! {
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"
130 }
131
132 /// **What it does:** This lint checks for usage of `ok().expect(..)`.
133 ///
134 /// **Why is this bad?** Because you usually call `expect()` on the `Result` directly to get a good
135 /// error message.
136 ///
137 /// **Known problems:** None.
138 ///
139 /// **Example:**
140 /// ```rust
141 /// x.ok().expect("why did I do this again?")
142 /// ```
143 declare_lint! {
144     pub OK_EXPECT, Warn,
145     "using `ok().expect()`, which gives worse error messages than \
146      calling `expect` directly on the Result"
147 }
148
149 /// **What it does:** This lint checks for usage of `_.map(_).unwrap_or(_)`.
150 ///
151 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or(_, _)`.
152 ///
153 /// **Known problems:** None.
154 ///
155 /// **Example:**
156 /// ```rust
157 /// x.map(|a| a + 1).unwrap_or(0)
158 /// ```
159 declare_lint! {
160     pub OPTION_MAP_UNWRAP_OR, Warn,
161     "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
162      `map_or(a, f)`"
163 }
164
165 /// **What it does:** This lint `Warn`s on `_.map(_).unwrap_or_else(_)`.
166 ///
167 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or_else(_, _)`.
168 ///
169 /// **Known problems:** None.
170 ///
171 /// **Example:**
172 /// ```rust
173 /// x.map(|a| a + 1).unwrap_or_else(some_function)
174 /// ```
175 declare_lint! {
176     pub OPTION_MAP_UNWRAP_OR_ELSE, Warn,
177     "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
178      `map_or_else(g, f)`"
179 }
180
181 /// **What it does:** This lint `Warn`s on `_.filter(_).next()`.
182 ///
183 /// **Why is this bad?** Readability, this can be written more concisely as `_.find(_)`.
184 ///
185 /// **Known problems:** None.
186 ///
187 /// **Example:**
188 /// ```rust
189 /// iter.filter(|x| x == 0).next()
190 /// ```
191 declare_lint! {
192     pub FILTER_NEXT, Warn,
193     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
194 }
195
196 /// **What it does:** This lint `Warn`s on `_.filter(_).map(_)`, `_.filter(_).flat_map(_)`,
197 /// `_.filter_map(_).flat_map(_)` and similar.
198 ///
199 /// **Why is this bad?** Readability, this can be written more concisely as a single method call
200 ///
201 /// **Known problems:** Often requires a condition + Option/Iterator creation inside the closure
202 ///
203 /// **Example:**
204 /// ```rust
205 /// iter.filter(|x| x == 0).map(|x| x * 2)
206 /// ```
207 declare_lint! {
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"
210 }
211
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()`.
214 ///
215 /// **Why is this bad?** Readability, this can be written more concisely as `_.any(_)`.
216 ///
217 /// **Known problems:** None.
218 ///
219 /// **Example:**
220 /// ```rust
221 /// iter.find(|x| x == 0).is_some()
222 /// ```
223 declare_lint! {
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()`"
227 }
228
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.
231 ///
232 /// **Why is this bad?** Readability, this can be written more concisely as `_.starts_with(_)`.
233 ///
234 /// **Known problems:** None.
235 ///
236 /// **Example:**
237 /// ```rust
238 /// name.chars().next() == Some('_')
239 /// ```
240 declare_lint! {
241     pub CHARS_NEXT_CMP, Warn,
242     "using `.chars().next()` to check if a string starts with a char"
243 }
244
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.
247 ///
248 /// **Why is this bad?** The function will always be called and potentially allocate an object
249 /// in expressions such as:
250 /// ```rust
251 /// foo.unwrap_or(String::new())
252 /// ```
253 /// this can instead be written:
254 /// ```rust
255 /// foo.unwrap_or_else(String::new)
256 /// ```
257 /// or
258 /// ```rust
259 /// foo.unwrap_or_default()
260 /// ```
261 ///
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.
264 declare_lint! {
265     pub OR_FUN_CALL, Warn,
266     "using any `*or` method when the `*or_else` would do"
267 }
268
269 /// **What it does:** This lint checks for usage of `.extend(s)` on a `Vec` to extend the vector by a slice.
270 ///
271 /// **Why is this bad?** Since Rust 1.6, the `extend_from_slice(_)` method is stable and at least for now faster.
272 ///
273 /// **Known problems:** None.
274 ///
275 /// **Example:**
276 /// ```rust
277 /// my_vec.extend(&xs)
278 /// ```
279 declare_lint! {
280     pub EXTEND_FROM_SLICE, Warn,
281     "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
282 }
283
284 /// **What it does:** This lint warns on using `.clone()` on a `Copy` type.
285 ///
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.
288 ///
289 /// **Known problems:** None.
290 ///
291 /// **Example:**
292 /// ```rust
293 /// 42u64.clone()
294 /// ```
295 declare_lint! {
296     pub CLONE_ON_COPY, Warn, "using `clone` on a `Copy` type"
297 }
298
299 /// **What it does:** This lint warns on using `.clone()` on an `&&T`
300 ///
301 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of cloning the underlying
302 /// `T`
303 ///
304 /// **Known problems:** None.
305 ///
306 /// **Example:**
307 /// ```rust
308 /// fn main() {
309 ///    let x = vec![1];
310 ///    let y = &&x;
311 ///    let z = y.clone();
312 ///    println!("{:p} {:p}",*y, z); // prints out the same pointer
313 /// }
314 /// ```
315 declare_lint! {
316     pub CLONE_DOUBLE_REF, Warn, "using `clone` on `&&T`"
317 }
318
319 /// **What it does:** This lint warns about `new` not returning `Self`.
320 ///
321 /// **Why is this bad?** As a convention, `new` methods are used to make a new instance of a type.
322 ///
323 /// **Known problems:** None.
324 ///
325 /// **Example:**
326 /// ```rust
327 /// impl Foo {
328 ///     fn new(..) -> NotAFoo {
329 ///     }
330 /// }
331 /// ```
332 declare_lint! {
333     pub NEW_RET_NO_SELF, Warn, "not returning `Self` in a `new` method"
334 }
335
336 /// **What it does:** This lint checks for string methods that receive a single-character `str` as an argument, e.g. `_.split("x")`.
337 ///
338 /// **Why is this bad?** Performing these methods using a `char` is faster than using a `str`.
339 ///
340 /// **Known problems:** Does not catch multi-byte unicode characters.
341 ///
342 /// **Example:**
343 /// ```rust
344 /// _.split("x")` could be `_.split('x')
345 /// ```
346 declare_lint! {
347     pub SINGLE_CHAR_PATTERN,
348     Warn,
349     "using a single-character str where a char could be used, e.g. \
350      `_.split(\"x\")`"
351 }
352
353 /// **What it does:** This lint checks for getting the inner pointer of a temporary `CString`.
354 ///
355 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long as the `CString` is
356 /// alive.
357 ///
358 /// **Known problems:** None.
359 ///
360 /// **Example:**
361 /// ```rust,ignore
362 /// let c_str = CString::new("foo").unwrap().as_ptr();
363 /// unsafe {
364 /// call_some_ffi_func(c_str);
365 /// }
366 /// ```
367 /// Here `c_str` point to a freed address. The correct use would be:
368 /// ```rust,ignore
369 /// let c_str = CString::new("foo").unwrap();
370 /// unsafe {
371 ///     call_some_ffi_func(c_str.as_ptr());
372 /// }
373 /// ```
374 declare_lint! {
375     pub TEMPORARY_CSTRING_AS_PTR,
376     Warn,
377     "getting the inner pointer of a temporary `CString`"
378 }
379
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.
382 ///
383 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more readable.
384 ///
385 /// **Known problems:** None.
386 ///
387 /// **Example:**
388 /// ```rust
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);
392 /// ```
393 /// The correct use would be:
394 /// ```rust
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);
398 /// ```
399 declare_lint! {
400     pub ITER_NTH,
401     Warn,
402     "using `.iter().nth()` on a standard library type with O(1) element access"
403 }
404
405 impl LintPass for Pass {
406     fn get_lints(&self) -> LintArray {
407         lint_array!(EXTEND_FROM_SLICE,
408                     OPTION_UNWRAP_USED,
409                     RESULT_UNWRAP_USED,
410                     SHOULD_IMPLEMENT_TRAIT,
411                     WRONG_SELF_CONVENTION,
412                     WRONG_PUB_SELF_CONVENTION,
413                     OK_EXPECT,
414                     OPTION_MAP_UNWRAP_OR,
415                     OPTION_MAP_UNWRAP_OR_ELSE,
416                     OR_FUN_CALL,
417                     CHARS_NEXT_CMP,
418                     CLONE_ON_COPY,
419                     CLONE_DOUBLE_REF,
420                     NEW_RET_NO_SELF,
421                     SINGLE_CHAR_PATTERN,
422                     SEARCH_IS_SOME,
423                     TEMPORARY_CSTRING_AS_PTR,
424                     FILTER_MAP,
425                     ITER_NTH)
426     }
427 }
428
429 impl LateLintPass for Pass {
430     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
431         if in_macro(cx, expr.span) {
432             return;
433         }
434
435         match expr.node {
436             hir::ExprMethodCall(name, _, ref args) => {
437                 // Chain calls
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);
470                 }
471
472                 lint_or_fun_call(cx, expr, &name.node.as_str(), args);
473
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);
478                 }
479
480                 match self_ty.sty {
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]);
485                             }
486                         }
487                     }
488                     _ => (),
489                 }
490             }
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);
494                 }
495             }
496             _ => (),
497         }
498     }
499
500     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
501         if in_external_macro(cx, item.span) {
502             return;
503         }
504
505         if let hir::ItemImpl(_, _, _, None, _, ref items) = item.node {
506             for implitem in items {
507                 let name = implitem.name;
508                 if_let_chain! {[
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),
511                 ], {
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));
521                         }
522                     }
523
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 {
528                         if_let_chain! {[
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)),
532                         ], {
533                             let lint = if item.vis == hir::Visibility::Public {
534                                 WRONG_PUB_SELF_CONVENTION
535                             } else {
536                                 WRONG_SELF_CONVENTION
537                             };
538                             span_lint(cx,
539                                       lint,
540                                       explicit_self.span,
541                                       &format!("methods called `{}` usually take {}; consider choosing a less \
542                                                 ambiguous name",
543                                                conv,
544                                                &self_kinds.iter()
545                                                           .map(|k| k.description())
546                                                           .collect::<Vec<_>>()
547                                                           .join(" or ")));
548                         }}
549                     }
550
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))) {
554                         span_lint(cx,
555                                   NEW_RET_NO_SELF,
556                                   explicit_self.span,
557                                   "methods called `new` usually return `Self`");
558                     }
559                 }}
560             }
561         }
562     }
563 }
564
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)
570                                -> bool {
571         if or_has_args {
572             return false;
573         }
574
575         if name == "unwrap_or" {
576             if let hir::ExprPath(_, ref path) = fun.node {
577                 let path: &str = &path.segments
578                                       .last()
579                                       .expect("A path must have at least one segment")
580                                       .name
581                                       .as_str();
582
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) {
586                         default_trait_id
587                     } else {
588                         return false;
589                     };
590
591                     if implements_trait(cx, arg_ty, default_trait_id, Vec::new()) {
592                         span_lint_and_then(cx,
593                                   OR_FUN_CALL,
594                                   span,
595                                   &format!("use of `{}` followed by a call to `{}`", name, path),
596                                   |db| {
597                                       db.span_suggestion(span, "try this",
598                                                           format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")));
599                                   });
600                         return true;
601                     }
602                 }
603             }
604         }
605
606         false
607     }
608
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,
611                           span: Span) {
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) {
616                 return;
617             }
618         }
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"),
622                                                   (&paths::OPTION,
623                                                    false,
624                                                    &["map_or", "ok_or", "or", "unwrap_or"],
625                                                    "else"),
626                                                   (&paths::RESULT, true, &["or", "unwrap_or"], "else")];
627
628         let self_ty = cx.tcx.expr_ty(self_expr);
629
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)
633         } else {
634             return;
635         };
636
637         if !poss.contains(&name) {
638             return;
639         }
640
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, ".."),
645         };
646
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,
649                                "try this",
650                                format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg));
651         });
652     }
653
654     if args.len() == 2 {
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);
659             }
660         }
661     }
662 }
663
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);
669
670     if !ty.moves_by_default(cx.tcx.global_tcx(), &parameter_environment, expr.span) {
671         span_lint(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type");
672     }
673 }
674
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,
680                                CLONE_DOUBLE_REF,
681                                expr.span,
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()));
686                                });
687         }
688     }
689 }
690
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) {
694         return;
695     }
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,
700                                "try this",
701                                format!("{}.extend_from_slice({})",
702                                        snippet(cx, args[0].span, "_"),
703                                        slice));
704         });
705     }
706 }
707
708 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
709     if_let_chain!{[
710         let hir::ExprCall(ref fun, ref args) = new.node,
711         args.len() == 1,
712         let hir::ExprPath(None, ref path) = fun.node,
713         match_path(path, &paths::CSTRING_NEW),
714     ], {
715         span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
716                            "you are getting the inner pointer of a temporary `CString`",
717                            |db| {
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");
720                            });
721     }}
722 }
723
724 #[allow(ptr_arg)]
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])) {
729         "slice"
730     }
731     else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC) {
732         "Vec"
733     }
734     else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
735         "VecDeque"
736     }
737     else {
738         return; // caller is not a type that we want to lint
739     };
740
741     span_lint(
742         cx,
743         ITER_NTH,
744         expr.span,
745         &format!("called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
746                  mut_str, caller_type)
747     );
748 }
749
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 {
752         match ty.sty {
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),
758             _ => false,
759         }
760     }
761
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| {
765                 sugg.addr()
766             })
767         } else {
768             None
769         }
770     } else {
771         match ty.sty {
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)
777                 } else {
778                     None
779                 }
780             }
781             _ => None,
782         }
783     }
784 }
785
786 #[allow(ptr_arg)]
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]));
791
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"))
796     } else {
797         None
798     };
799
800     if let Some((lint, kind, none_value)) = mess {
801         span_lint(cx,
802                   lint,
803                   expr.span,
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
806                             message",
807                            kind,
808                            none_value));
809     }
810 }
811
812 #[allow(ptr_arg)]
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) {
821                 span_lint(cx,
822                           OK_EXPECT,
823                           expr.span,
824                           "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`");
825             }
826         }
827     }
828 }
829
830 #[allow(ptr_arg)]
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) {
836         // lint message
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,
849                                expr.span,
850                                msg,
851                                expr.span,
852                                &format!("replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
853                                         map_snippet,
854                                         unwrap_snippet));
855         } else if same_span && multiline {
856             span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
857         };
858     }
859 }
860
861 #[allow(ptr_arg)]
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) {
867         // lint message
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,
880                                expr.span,
881                                msg,
882                                expr.span,
883                                &format!("replace `map({0}).unwrap_or_else({1})` with `with map_or_else({1}, {0})`",
884                                         map_snippet,
885                                         unwrap_snippet));
886         } else if same_span && multiline {
887             span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
888         };
889     }
890 }
891
892 #[allow(ptr_arg)]
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)` \
899                    instead.";
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,
904                                FILTER_NEXT,
905                                expr.span,
906                                msg,
907                                expr.span,
908                                &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet));
909         } else {
910             span_lint(cx, FILTER_NEXT, expr.span, msg);
911         }
912     }
913 }
914
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);
923     }
924 }
925
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);
934     }
935 }
936
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);
946     }
947 }
948
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);
958     }
959 }
960
961 #[allow(ptr_arg)]
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()`.",
970                           search_method);
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,
975                                SEARCH_IS_SOME,
976                                expr.span,
977                                &msg,
978                                expr.span,
979                                &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet));
980         } else {
981             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
982         }
983     }
984 }
985
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 {
988     if_let_chain! {[
989         let Some(args) = method_chain_args(chain, &["chars", "next"]),
990         let hir::ExprCall(ref fun, ref arg_char) = other.node,
991         arg_char.len() == 1,
992         let hir::ExprPath(None, ref path) = fun.node,
993         path.segments.len() == 1 && path.segments[0].name.as_str() == "Some"
994     ], {
995         let self_ty = walk_ptrs_ty(cx.tcx.expr_ty_adjusted(&args[0][0]));
996
997         if self_ty.sty != ty::TyStr {
998             return false;
999         }
1000
1001         span_lint_and_then(cx,
1002                            CHARS_NEXT_CMP,
1003                            expr.span,
1004                            "you should use the `starts_with` method",
1005                            |db| {
1006                                let sugg = format!("{}{}.starts_with({})",
1007                                                   if eq { "" } else { "!" },
1008                                                   snippet(cx, args[0][0].span, "_"),
1009                                                   snippet(cx, arg_char[0].span, "_")
1010                                                   );
1011
1012                                db.span_suggestion(expr.span, "like this", sugg);
1013                            });
1014
1015         return true;
1016     }}
1017
1018     false
1019 }
1020
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) {
1024         if r.len() == 1 {
1025             let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1026             span_lint_and_then(cx,
1027                                SINGLE_CHAR_PATTERN,
1028                                arg.span,
1029                                "single-character string constant used as pattern",
1030                                |db| {
1031                                    db.span_suggestion(expr.span, "try using a char instead:", hint);
1032                                });
1033         }
1034     }
1035 }
1036
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) {
1040         return None;
1041     }
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);
1045         }
1046     }
1047     None
1048 }
1049
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()),
1054         None => false,
1055     }
1056 }
1057
1058 enum Convention {
1059     Eq(&'static str),
1060     StartsWith(&'static str),
1061 }
1062
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]),
1071 ];
1072
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"),
1105 ];
1106
1107 #[cfg_attr(rustfmt, rustfmt_skip)]
1108 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1109     ("contains", 1),
1110     ("starts_with", 1),
1111     ("ends_with", 1),
1112     ("find", 1),
1113     ("rfind", 1),
1114     ("split", 1),
1115     ("rsplit", 1),
1116     ("split_terminator", 1),
1117     ("rsplit_terminator", 1),
1118     ("splitn", 2),
1119     ("rsplitn", 2),
1120     ("matches", 1),
1121     ("rmatches", 1),
1122     ("match_indices", 1),
1123     ("rmatch_indices", 1),
1124     ("trim_left_matches", 1),
1125     ("trim_right_matches", 1),
1126 ];
1127
1128
1129 #[derive(Clone, Copy)]
1130 enum SelfKind {
1131     Value,
1132     Ref,
1133     RefMut,
1134     No,
1135 }
1136
1137 impl SelfKind {
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),
1146
1147             _ => false,
1148         }
1149     }
1150
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,
1158             _ => false,
1159         }
1160     }
1161
1162     fn description(&self) -> &'static str {
1163         match *self {
1164             SelfKind::Value => "self by value",
1165             SelfKind::Ref => "self by reference",
1166             SelfKind::RefMut => "self by mutable reference",
1167             SelfKind::No => "no self",
1168         }
1169     }
1170 }
1171
1172 impl Convention {
1173     fn check(&self, other: &str) -> bool {
1174         match *self {
1175             Convention::Eq(this) => this == other,
1176             Convention::StartsWith(this) => other.starts_with(this),
1177         }
1178     }
1179 }
1180
1181 impl fmt::Display for Convention {
1182     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1183         match *self {
1184             Convention::Eq(this) => this.fmt(f),
1185             Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1186         }
1187     }
1188 }
1189
1190 #[derive(Clone, Copy)]
1191 enum OutType {
1192     Unit,
1193     Bool,
1194     Any,
1195     Ref,
1196 }
1197
1198 impl OutType {
1199     fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1200         match (self, ty) {
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(_, _)),
1206             _ => false,
1207         }
1208     }
1209 }
1210
1211 fn is_bool(ty: &hir::Ty) -> bool {
1212     if let hir::TyPath(None, ref p) = ty.node {
1213         match_path(p, &["bool"])
1214     } else {
1215         false
1216     }
1217 }