]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods.rs
Use `utils::sugg` in methods lints
[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::{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, match_path, match_trait_method,
14             match_type, method_chain_args, return_ty, same_tys, snippet, span_lint,
15             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 `.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 ///
27 /// **Known problems:** None
28 ///
29 /// **Example:** `x.unwrap()`
30 declare_lint! {
31     pub OPTION_UNWRAP_USED, Allow,
32     "using `Option.unwrap()`, which should at least get a better message using `expect()`"
33 }
34
35 /// **What it does:** This lint checks for `.unwrap()` calls on `Result`s.
36 ///
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!`.
38 ///
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.
40 ///
41 /// **Known problems:** None
42 ///
43 /// **Example:** `x.unwrap()`
44 declare_lint! {
45     pub RESULT_UNWRAP_USED, Allow,
46     "using `Result.unwrap()`, which might be better handled"
47 }
48
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.
50 ///
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.
52 ///
53 /// **Known problems:** None
54 ///
55 /// **Example:**
56 /// ```
57 /// struct X;
58 /// impl X {
59 ///    fn add(&self, other: &X) -> X { .. }
60 /// }
61 /// ```
62 declare_lint! {
63     pub SHOULD_IMPLEMENT_TRAIT, Warn,
64     "defining a method that should be implementing a std trait"
65 }
66
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:
68 ///
69 /// |Prefix |`self` taken        |
70 /// |-------|--------------------|
71 /// |`as_`  |`&self` or &mut self|
72 /// |`from_`| none               |
73 /// |`into_`|`self`              |
74 /// |`is_`  |`&self` or none     |
75 /// |`to_`  |`&self`             |
76 ///
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.
78 ///
79 /// **Known problems:** None
80 ///
81 /// **Example**
82 ///
83 /// ```
84 /// impl X {
85 ///     fn as_str(self) -> &str { .. }
86 /// }
87 /// ```
88 declare_lint! {
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"
92 }
93
94 /// **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but for public items.
95 ///
96 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
97 ///
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.
99 ///
100 /// **Example:**
101 /// ```
102 /// impl X {
103 ///     pub fn as_str(self) -> &str { .. }
104 /// }
105 /// ```
106 declare_lint! {
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"
110 }
111
112 /// **What it does:** This lint checks for usage of `ok().expect(..)`.
113 ///
114 /// **Why is this bad?** Because you usually call `expect()` on the `Result` directly to get a good error message.
115 ///
116 /// **Known problems:** None.
117 ///
118 /// **Example:** `x.ok().expect("why did I do this again?")`
119 declare_lint! {
120     pub OK_EXPECT, Warn,
121     "using `ok().expect()`, which gives worse error messages than \
122      calling `expect` directly on the Result"
123 }
124
125 /// **What it does:** This lint checks for usage of `_.map(_).unwrap_or(_)`.
126 ///
127 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or(_, _)`.
128 ///
129 /// **Known problems:** None.
130 ///
131 /// **Example:** `x.map(|a| a + 1).unwrap_or(0)`
132 declare_lint! {
133     pub OPTION_MAP_UNWRAP_OR, Warn,
134     "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
135      `map_or(a, f)`"
136 }
137
138 /// **What it does:** This lint `Warn`s on `_.map(_).unwrap_or_else(_)`.
139 ///
140 /// **Why is this bad?** Readability, this can be written more concisely as `_.map_or_else(_, _)`.
141 ///
142 /// **Known problems:** None.
143 ///
144 /// **Example:** `x.map(|a| a + 1).unwrap_or_else(some_function)`
145 declare_lint! {
146     pub OPTION_MAP_UNWRAP_OR_ELSE, Warn,
147     "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
148      `map_or_else(g, f)`"
149 }
150
151 /// **What it does:** This lint `Warn`s on `_.filter(_).next()`.
152 ///
153 /// **Why is this bad?** Readability, this can be written more concisely as `_.find(_)`.
154 ///
155 /// **Known problems:** None.
156 ///
157 /// **Example:** `iter.filter(|x| x == 0).next()`
158 declare_lint! {
159     pub FILTER_NEXT, Warn,
160     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
161 }
162
163 /// **What it does:** This lint `Warn`s on `_.filter(_).map(_)`, `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
164 ///
165 /// **Why is this bad?** Readability, this can be written more concisely as a single method call
166 ///
167 /// **Known problems:** Often requires a condition + Option/Iterator creation inside the closure
168 ///
169 /// **Example:** `iter.filter(|x| x == 0).map(|x| x * 2)`
170 declare_lint! {
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"
173 }
174
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()`.
177 ///
178 /// **Why is this bad?** Readability, this can be written more concisely as `_.any(_)`.
179 ///
180 /// **Known problems:** None.
181 ///
182 /// **Example:** `iter.find(|x| x == 0).is_some()`
183 declare_lint! {
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()`"
187 }
188
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.
191 ///
192 /// **Why is this bad?** Readability, this can be written more concisely as `_.starts_with(_)`.
193 ///
194 /// **Known problems:** None.
195 ///
196 /// **Example:** `name.chars().next() == Some('_')`
197 declare_lint! {
198     pub CHARS_NEXT_CMP, Warn,
199     "using `.chars().next()` to check if a string starts with a char"
200 }
201
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.
204 ///
205 /// **Why is this bad?** The function will always be called and potentially allocate an object
206 /// in expressions such as:
207 /// ```rust
208 /// foo.unwrap_or(String::new())
209 /// ```
210 /// this can instead be written:
211 /// ```rust
212 /// foo.unwrap_or_else(String::new)
213 /// ```
214 /// or
215 /// ```rust
216 /// foo.unwrap_or_default()
217 /// ```
218 ///
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.
221 declare_lint! {
222     pub OR_FUN_CALL, Warn,
223     "using any `*or` method when the `*or_else` would do"
224 }
225
226 /// **What it does:** This lint checks for usage of `.extend(s)` on a `Vec` to extend the vector by a slice.
227 ///
228 /// **Why is this bad?** Since Rust 1.6, the `extend_from_slice(_)` method is stable and at least for now faster.
229 ///
230 /// **Known problems:** None.
231 ///
232 /// **Example:** `my_vec.extend(&xs)`
233 declare_lint! {
234     pub EXTEND_FROM_SLICE, Warn,
235     "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
236 }
237
238 /// **What it does:** This lint warns on using `.clone()` on a `Copy` type.
239 ///
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.
242 ///
243 /// **Known problems:** None.
244 ///
245 /// **Example:** `42u64.clone()`
246 declare_lint! {
247     pub CLONE_ON_COPY, Warn, "using `clone` on a `Copy` type"
248 }
249
250 /// **What it does:** This lint warns on using `.clone()` on an `&&T`
251 ///
252 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of cloning the underlying
253 /// `T`
254 ///
255 /// **Known problems:** None.
256 ///
257 /// **Example:**
258 /// ```rust
259 /// fn main() {
260 ///    let x = vec![1];
261 ///    let y = &&x;
262 ///    let z = y.clone();
263 ///    println!("{:p} {:p}",*y, z); // prints out the same pointer
264 /// }
265 /// ```
266 declare_lint! {
267     pub CLONE_DOUBLE_REF, Warn, "using `clone` on `&&T`"
268 }
269
270 /// **What it does:** This lint warns about `new` not returning `Self`.
271 ///
272 /// **Why is this bad?** As a convention, `new` methods are used to make a new instance of a type.
273 ///
274 /// **Known problems:** None.
275 ///
276 /// **Example:**
277 /// ```rust
278 /// impl Foo {
279 ///     fn new(..) -> NotAFoo {
280 ///     }
281 /// }
282 /// ```
283 declare_lint! {
284     pub NEW_RET_NO_SELF, Warn, "not returning `Self` in a `new` method"
285 }
286
287 /// **What it does:** This lint checks for string methods that receive a single-character `str` as an argument, e.g. `_.split("x")`.
288 ///
289 /// **Why is this bad?** Performing these methods using a `char` is faster than using a `str`.
290 ///
291 /// **Known problems:** Does not catch multi-byte unicode characters.
292 ///
293 /// **Example:** `_.split("x")` could be `_.split('x')`
294 declare_lint! {
295     pub SINGLE_CHAR_PATTERN,
296     Warn,
297     "using a single-character str where a char could be used, e.g. \
298      `_.split(\"x\")`"
299 }
300
301 /// **What it does:** This lint checks for getting the inner pointer of a temporary `CString`.
302 ///
303 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long as the `CString` is
304 /// alive.
305 ///
306 /// **Known problems:** None.
307 ///
308 /// **Example:**
309 /// ```rust,ignore
310 /// let c_str = CString::new("foo").unwrap().as_ptr();
311 /// unsafe {
312 /// call_some_ffi_func(c_str);
313 /// }
314 /// ```
315 /// Here `c_str` point to a freed address. The correct use would be:
316 /// ```rust,ignore
317 /// let c_str = CString::new("foo").unwrap();
318 /// unsafe {
319 /// call_some_ffi_func(c_str.as_ptr());
320 /// }
321 /// ```
322 declare_lint! {
323     pub TEMPORARY_CSTRING_AS_PTR,
324     Warn,
325     "getting the inner pointer of a temporary `CString`"
326 }
327
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.
330 ///
331 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more readable.
332 ///
333 /// **Known problems:** None.
334 ///
335 /// **Example:**
336 /// ```rust
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);
340 /// ```
341 /// The correct use would be:
342 /// ```rust
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);
346 /// ```
347 declare_lint! {
348     pub ITER_NTH,
349     Warn,
350     "using `.iter().nth()` on a standard library type with O(1) element access"
351 }
352
353 impl LintPass for Pass {
354     fn get_lints(&self) -> LintArray {
355         lint_array!(EXTEND_FROM_SLICE,
356                     OPTION_UNWRAP_USED,
357                     RESULT_UNWRAP_USED,
358                     SHOULD_IMPLEMENT_TRAIT,
359                     WRONG_SELF_CONVENTION,
360                     WRONG_PUB_SELF_CONVENTION,
361                     OK_EXPECT,
362                     OPTION_MAP_UNWRAP_OR,
363                     OPTION_MAP_UNWRAP_OR_ELSE,
364                     OR_FUN_CALL,
365                     CHARS_NEXT_CMP,
366                     CLONE_ON_COPY,
367                     CLONE_DOUBLE_REF,
368                     NEW_RET_NO_SELF,
369                     SINGLE_CHAR_PATTERN,
370                     SEARCH_IS_SOME,
371                     TEMPORARY_CSTRING_AS_PTR,
372                     FILTER_MAP,
373                     ITER_NTH)
374     }
375 }
376
377 impl LateLintPass for Pass {
378     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
379         if in_macro(cx, expr.span) {
380             return;
381         }
382
383         match expr.node {
384             hir::ExprMethodCall(name, _, ref args) => {
385                 // Chain calls
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);
418                 }
419
420                 lint_or_fun_call(cx, expr, &name.node.as_str(), args);
421
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);
426                 }
427
428                 match self_ty.sty {
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]);
433                             }
434                         }
435                     }
436                     _ => (),
437                 }
438             }
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);
442                 }
443             }
444             _ => (),
445         }
446     }
447
448     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
449         if in_external_macro(cx, item.span) {
450             return;
451         }
452
453         if let hir::ItemImpl(_, _, _, None, _, ref items) = item.node {
454             for implitem in items {
455                 let name = implitem.name;
456                 if_let_chain! {[
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),
459                 ], {
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));
469                         }
470                     }
471
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);
475                     for &(ref conv, self_kinds) in &CONVENTIONS {
476                         if_let_chain! {[
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)),
480                         ], {
481                             let lint = if item.vis == hir::Visibility::Public {
482                                 WRONG_PUB_SELF_CONVENTION
483                             } else {
484                                 WRONG_SELF_CONVENTION
485                             };
486                             span_lint(cx,
487                                       lint,
488                                       explicit_self.span,
489                                       &format!("methods called `{}` usually take {}; consider choosing a less \
490                                                 ambiguous name",
491                                                conv,
492                                                &self_kinds.iter()
493                                                           .map(|k| k.description())
494                                                           .collect::<Vec<_>>()
495                                                           .join(" or ")));
496                         }}
497                     }
498
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))) {
502                         span_lint(cx,
503                                   NEW_RET_NO_SELF,
504                                   explicit_self.span,
505                                   "methods called `new` usually return `Self`");
506                     }
507                 }}
508             }
509         }
510     }
511 }
512
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)
518                                -> bool {
519         if or_has_args {
520             return false;
521         }
522
523         if name == "unwrap_or" {
524             if let hir::ExprPath(_, ref path) = fun.node {
525                 let path: &str = &path.segments
526                                       .last()
527                                       .expect("A path must have at least one segment")
528                                       .name
529                                       .as_str();
530
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) {
534                         default_trait_id
535                     } else {
536                         return false;
537                     };
538
539                     if implements_trait(cx, arg_ty, default_trait_id, Vec::new()) {
540                         span_lint_and_then(cx,
541                                   OR_FUN_CALL,
542                                   span,
543                                   &format!("use of `{}` followed by a call to `{}`", name, path),
544                                   |db| {
545                                       db.span_suggestion(span, "try this",
546                                                           format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")));
547                                   });
548                         return true;
549                     }
550                 }
551             }
552         }
553
554         false
555     }
556
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,
559                           span: Span) {
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) {
564                 return;
565             }
566         }
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"),
570                                                   (&paths::OPTION,
571                                                    false,
572                                                    &["map_or", "ok_or", "or", "unwrap_or"],
573                                                    "else"),
574                                                   (&paths::RESULT, true, &["or", "unwrap_or"], "else")];
575
576         let self_ty = cx.tcx.expr_ty(self_expr);
577
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)
581         } else {
582             return;
583         };
584
585         if !poss.contains(&name) {
586             return;
587         }
588
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, ".."),
593         };
594
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,
597                                "try this",
598                                format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg));
599         });
600     }
601
602     if args.len() == 2 {
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);
607             }
608         }
609     }
610 }
611
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);
617
618     if !ty.moves_by_default(cx.tcx.global_tcx(), &parameter_environment, expr.span) {
619         span_lint(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type");
620     }
621 }
622
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,
628                                CLONE_DOUBLE_REF,
629                                expr.span,
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()));
634                                });
635         }
636     }
637 }
638
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) {
642         return;
643     }
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,
648                                "try this",
649                                format!("{}.extend_from_slice({})",
650                                        snippet(cx, args[0].span, "_"),
651                                        slice));
652         });
653     }
654 }
655
656 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
657     if_let_chain!{[
658         let hir::ExprCall(ref fun, ref args) = new.node,
659         args.len() == 1,
660         let hir::ExprPath(None, ref path) = fun.node,
661         match_path(path, &paths::CSTRING_NEW),
662     ], {
663         span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
664                            "you are getting the inner pointer of a temporary `CString`",
665                            |db| {
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");
668                            });
669     }}
670 }
671
672 #[allow(ptr_arg)]
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])) {
677         "slice"
678     }
679     else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC) {
680         "Vec"
681     }
682     else if match_type(cx, cx.tcx.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
683         "VecDeque"
684     }
685     else {
686         return; // caller is not a type that we want to lint
687     };
688
689     span_lint(
690         cx,
691         ITER_NTH,
692         expr.span,
693         &format!("called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
694                  mut_str, caller_type)
695     );
696 }
697
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 {
700         match ty.sty {
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),
706             _ => false,
707         }
708     }
709
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| {
713                 sugg.addr()
714             })
715         } else {
716             None
717         }
718     } else {
719         match ty.sty {
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)
725                 } else {
726                     None
727                 }
728             }
729             _ => None,
730         }
731     }
732 }
733
734 #[allow(ptr_arg)]
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]));
739
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"))
744     } else {
745         None
746     };
747
748     if let Some((lint, kind, none_value)) = mess {
749         span_lint(cx,
750                   lint,
751                   expr.span,
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
754                             message",
755                            kind,
756                            none_value));
757     }
758 }
759
760 #[allow(ptr_arg)]
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) {
769                 span_lint(cx,
770                           OK_EXPECT,
771                           expr.span,
772                           "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`");
773             }
774         }
775     }
776 }
777
778 #[allow(ptr_arg)]
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) {
784         // lint message
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,
797                                expr.span,
798                                msg,
799                                expr.span,
800                                &format!("replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
801                                         map_snippet,
802                                         unwrap_snippet));
803         } else if same_span && multiline {
804             span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
805         };
806     }
807 }
808
809 #[allow(ptr_arg)]
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) {
815         // lint message
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,
828                                expr.span,
829                                msg,
830                                expr.span,
831                                &format!("replace `map({0}).unwrap_or_else({1})` with `with map_or_else({1}, {0})`",
832                                         map_snippet,
833                                         unwrap_snippet));
834         } else if same_span && multiline {
835             span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
836         };
837     }
838 }
839
840 #[allow(ptr_arg)]
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)` \
847                    instead.";
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,
852                                FILTER_NEXT,
853                                expr.span,
854                                msg,
855                                expr.span,
856                                &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet));
857         } else {
858             span_lint(cx, FILTER_NEXT, expr.span, msg);
859         }
860     }
861 }
862
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);
871     }
872 }
873
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);
882     }
883 }
884
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);
894     }
895 }
896
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);
906     }
907 }
908
909 #[allow(ptr_arg)]
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()`.",
918                           search_method);
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,
923                                SEARCH_IS_SOME,
924                                expr.span,
925                                &msg,
926                                expr.span,
927                                &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet));
928         } else {
929             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
930         }
931     }
932 }
933
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 {
936     if_let_chain! {[
937         let Some(args) = method_chain_args(chain, &["chars", "next"]),
938         let hir::ExprCall(ref fun, ref arg_char) = other.node,
939         arg_char.len() == 1,
940         let hir::ExprPath(None, ref path) = fun.node,
941         path.segments.len() == 1 && path.segments[0].name.as_str() == "Some"
942     ], {
943         let self_ty = walk_ptrs_ty(cx.tcx.expr_ty_adjusted(&args[0][0]));
944
945         if self_ty.sty != ty::TyStr {
946             return false;
947         }
948
949         span_lint_and_then(cx,
950                            CHARS_NEXT_CMP,
951                            expr.span,
952                            "you should use the `starts_with` method",
953                            |db| {
954                                let sugg = format!("{}{}.starts_with({})",
955                                                   if eq { "" } else { "!" },
956                                                   snippet(cx, args[0][0].span, "_"),
957                                                   snippet(cx, arg_char[0].span, "_")
958                                                   );
959
960                                db.span_suggestion(expr.span, "like this", sugg);
961                            });
962
963         return true;
964     }}
965
966     false
967 }
968
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) {
972         if r.len() == 1 {
973             let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
974             span_lint_and_then(cx,
975                                SINGLE_CHAR_PATTERN,
976                                arg.span,
977                                "single-character string constant used as pattern",
978                                |db| {
979                                    db.span_suggestion(expr.span, "try using a char instead:", hint);
980                                });
981         }
982     }
983 }
984
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) {
988         return None;
989     }
990     if let ty::TyEnum(_, substs) = ty.sty {
991         if let Some(err_ty) = substs.types.opt_get(TypeSpace, 1) {
992             return Some(err_ty);
993         }
994     }
995     None
996 }
997
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()),
1002         None => false,
1003     }
1004 }
1005
1006 enum Convention {
1007     Eq(&'static str),
1008     StartsWith(&'static str),
1009 }
1010
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]),
1019 ];
1020
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"),
1053 ];
1054
1055 #[cfg_attr(rustfmt, rustfmt_skip)]
1056 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1057     ("contains", 1),
1058     ("starts_with", 1),
1059     ("ends_with", 1),
1060     ("find", 1),
1061     ("rfind", 1),
1062     ("split", 1),
1063     ("rsplit", 1),
1064     ("split_terminator", 1),
1065     ("rsplit_terminator", 1),
1066     ("splitn", 2),
1067     ("rsplitn", 2),
1068     ("matches", 1),
1069     ("rmatches", 1),
1070     ("match_indices", 1),
1071     ("rmatch_indices", 1),
1072     ("trim_left_matches", 1),
1073     ("trim_right_matches", 1),
1074 ];
1075
1076
1077 #[derive(Clone, Copy)]
1078 enum SelfKind {
1079     Value,
1080     Ref,
1081     RefMut,
1082     No,
1083 }
1084
1085 impl SelfKind {
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),
1094
1095             _ => false,
1096         }
1097     }
1098
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,
1106             _ => false,
1107         }
1108     }
1109
1110     fn description(&self) -> &'static str {
1111         match *self {
1112             SelfKind::Value => "self by value",
1113             SelfKind::Ref => "self by reference",
1114             SelfKind::RefMut => "self by mutable reference",
1115             SelfKind::No => "no self",
1116         }
1117     }
1118 }
1119
1120 impl Convention {
1121     fn check(&self, other: &str) -> bool {
1122         match *self {
1123             Convention::Eq(this) => this == other,
1124             Convention::StartsWith(this) => other.starts_with(this),
1125         }
1126     }
1127 }
1128
1129 impl fmt::Display for Convention {
1130     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1131         match *self {
1132             Convention::Eq(this) => this.fmt(f),
1133             Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1134         }
1135     }
1136 }
1137
1138 #[derive(Clone, Copy)]
1139 enum OutType {
1140     Unit,
1141     Bool,
1142     Any,
1143     Ref,
1144 }
1145
1146 impl OutType {
1147     fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1148         match (self, ty) {
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(_, _)),
1154             _ => false,
1155         }
1156     }
1157 }
1158
1159 fn is_bool(ty: &hir::Ty) -> bool {
1160     if let hir::TyPath(None, ref p) = ty.node {
1161         match_path(p, &["bool"])
1162     } else {
1163         false
1164     }
1165 }
1166
1167 fn is_copy<'a, 'ctx>(cx: &LateContext<'a, 'ctx>, ty: ty::Ty<'ctx>, item: &hir::Item) -> bool {
1168     let env = ty::ParameterEnvironment::for_item(cx.tcx, item.id);
1169     !ty.subst(cx.tcx, env.free_substs).moves_by_default(cx.tcx.global_tcx(), &env, item.span)
1170 }