]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods.rs
d1192e3f26bc67cac3f6b9a173b926c37e3d7b1d
[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;
6 use rustc_const_eval::EvalHint::ExprTypeChecked;
7 use rustc_const_eval::eval_const_expr_partial;
8 use std::borrow::Cow;
9 use std::fmt;
10 use syntax::codemap::Span;
11 use syntax::ptr::P;
12 use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, match_path,
13             match_trait_method, match_type, method_chain_args, return_ty, same_tys, snippet,
14             span_lint, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
15 use utils::MethodArgs;
16 use utils::paths;
17 use utils::sugg;
18
19 #[derive(Clone)]
20 pub struct Pass;
21
22 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
23 ///
24 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
25 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
26 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
27 /// `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,
37     Allow,
38     "using `Option.unwrap()`, which should at least get a better message using `expect()`"
39 }
40
41 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
42 ///
43 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
44 /// values. Normally, you want to implement more sophisticated error handling,
45 /// and propagate errors upwards with `try!`.
46 ///
47 /// Even if you want to panic on errors, not all `Error`s implement good
48 /// messages on display.  Therefore it may be beneficial to look at the places
49 /// where they may get displayed. Activate this lint to do just that.
50 ///
51 /// **Known problems:** None.
52 ///
53 /// **Example:**
54 /// ```rust
55 /// x.unwrap()
56 /// ```
57 declare_lint! {
58     pub RESULT_UNWRAP_USED,
59     Allow,
60     "using `Result.unwrap()`, which might be better handled"
61 }
62
63 /// **What it does:** Checks for methods that should live in a trait
64 /// implementation of a `std` trait (see [llogiq's blog
65 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
66 /// information) instead of an inherent implementation.
67 ///
68 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
69 /// the code, often with very little cost. Also people seeing a `mul(...)` method
70 /// may expect `*` to work equally, so you should have good reason to disappoint
71 /// them.
72 ///
73 /// **Known problems:** None.
74 ///
75 /// **Example:**
76 /// ```rust
77 /// struct X;
78 /// impl X {
79 ///    fn add(&self, other: &X) -> X { .. }
80 /// }
81 /// ```
82 declare_lint! {
83     pub SHOULD_IMPLEMENT_TRAIT,
84     Warn,
85     "defining a method that should be implementing a std trait"
86 }
87
88 /// **What it does:** Checks for methods with certain name prefixes and which
89 /// doesn't match how self is taken. The actual rules are:
90 ///
91 /// |Prefix |`self` taken          |
92 /// |-------|----------------------|
93 /// |`as_`  |`&self` or `&mut self`|
94 /// |`from_`| none                 |
95 /// |`into_`|`self`                |
96 /// |`is_`  |`&self` or none       |
97 /// |`to_`  |`&self`               |
98 ///
99 /// **Why is this bad?** Consistency breeds readability. If you follow the
100 /// conventions, your users won't be surprised that they, e.g., need to supply a
101 /// mutable reference to a `as_..` function.
102 ///
103 /// **Known problems:** None.
104 ///
105 /// **Example:**
106 /// ```rust
107 /// impl X {
108 ///     fn as_str(self) -> &str { .. }
109 /// }
110 /// ```
111 declare_lint! {
112     pub WRONG_SELF_CONVENTION,
113     Warn,
114     "defining a method named with an established prefix (like \"into_\") that takes \
115      `self` with the wrong convention"
116 }
117
118 /// **What it does:** This is the same as
119 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
120 ///
121 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
122 ///
123 /// **Known problems:** Actually *renaming* the function may break clients if
124 /// the function is part of the public interface. In that case, be mindful of
125 /// the stability guarantees you've given your users.
126 ///
127 /// **Example:**
128 /// ```rust
129 /// impl X {
130 ///     pub fn as_str(self) -> &str { .. }
131 /// }
132 /// ```
133 declare_lint! {
134     pub WRONG_PUB_SELF_CONVENTION,
135     Allow,
136     "defining a public method named with an established prefix (like \"into_\") that takes \
137      `self` with the wrong convention"
138 }
139
140 /// **What it does:** Checks for usage of `ok().expect(..)`.
141 ///
142 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
143 /// directly to get a better error message.
144 ///
145 /// **Known problems:** None.
146 ///
147 /// **Example:**
148 /// ```rust
149 /// x.ok().expect("why did I do this again?")
150 /// ```
151 declare_lint! {
152     pub OK_EXPECT,
153     Warn,
154     "using `ok().expect()`, which gives worse error messages than \
155      calling `expect` directly on the Result"
156 }
157
158 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
159 ///
160 /// **Why is this bad?** Readability, this can be written more concisely as
161 /// `_.map_or(_, _)`.
162 ///
163 /// **Known problems:** None.
164 ///
165 /// **Example:**
166 /// ```rust
167 /// x.map(|a| a + 1).unwrap_or(0)
168 /// ```
169 declare_lint! {
170     pub OPTION_MAP_UNWRAP_OR,
171     Allow,
172     "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as \
173      `map_or(a, f)`"
174 }
175
176 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
177 ///
178 /// **Why is this bad?** Readability, this can be written more concisely as
179 /// `_.map_or_else(_, _)`.
180 ///
181 /// **Known problems:** None.
182 ///
183 /// **Example:**
184 /// ```rust
185 /// x.map(|a| a + 1).unwrap_or_else(some_function)
186 /// ```
187 declare_lint! {
188     pub OPTION_MAP_UNWRAP_OR_ELSE,
189     Allow,
190     "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as \
191      `map_or_else(g, f)`"
192 }
193
194 /// **What it does:** Checks for usage of `_.filter(_).next()`.
195 ///
196 /// **Why is this bad?** Readability, this can be written more concisely as
197 /// `_.find(_)`.
198 ///
199 /// **Known problems:** None.
200 ///
201 /// **Example:**
202 /// ```rust
203 /// iter.filter(|x| x == 0).next()
204 /// ```
205 declare_lint! {
206     pub FILTER_NEXT,
207     Warn,
208     "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
209 }
210
211 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
212 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
213 ///
214 /// **Why is this bad?** Readability, this can be written more concisely as a
215 /// single method call.
216 ///
217 /// **Known problems:** Often requires a condition + Option/Iterator creation
218 /// inside the closure.
219 ///
220 /// **Example:**
221 /// ```rust
222 /// iter.filter(|x| x == 0).map(|x| x * 2)
223 /// ```
224 declare_lint! {
225     pub FILTER_MAP,
226     Allow,
227     "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can \
228      usually be written as a single method call"
229 }
230
231 /// **What it does:** Checks for an iterator search (such as `find()`,
232 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
233 ///
234 /// **Why is this bad?** Readability, this can be written more concisely as
235 /// `_.any(_)`.
236 ///
237 /// **Known problems:** None.
238 ///
239 /// **Example:**
240 /// ```rust
241 /// iter.find(|x| x == 0).is_some()
242 /// ```
243 declare_lint! {
244     pub SEARCH_IS_SOME,
245     Warn,
246     "using an iterator search followed by `is_some()`, which is more succinctly \
247      expressed as a call to `any()`"
248 }
249
250 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
251 /// if it starts with a given char.
252 ///
253 /// **Why is this bad?** Readability, this can be written more concisely as
254 /// `_.starts_with(_)`.
255 ///
256 /// **Known problems:** None.
257 ///
258 /// **Example:**
259 /// ```rust
260 /// name.chars().next() == Some('_')
261 /// ```
262 declare_lint! {
263     pub CHARS_NEXT_CMP,
264     Warn,
265     "using `.chars().next()` to check if a string starts with a char"
266 }
267
268 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
269 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
270 /// `unwrap_or_default` instead.
271 ///
272 /// **Why is this bad?** The function will always be called and potentially
273 /// allocate an object acting as the default.
274 ///
275 /// **Known problems:** If the function has side-effects, not calling it will
276 /// change the semantic of the program, but you shouldn't rely on that anyway.
277 ///
278 /// **Example:**
279 /// ```rust
280 /// foo.unwrap_or(String::new())
281 /// ```
282 /// this can instead be written:
283 /// ```rust
284 /// foo.unwrap_or_else(String::new)
285 /// ```
286 /// or
287 /// ```rust
288 /// foo.unwrap_or_default()
289 /// ```
290 declare_lint! {
291     pub OR_FUN_CALL,
292     Warn,
293     "using any `*or` method with a function call, which suggests `*or_else`"
294 }
295
296 /// **What it does:** Checks for usage of `.extend(s)` on a `Vec` to extend the
297 /// vector by a slice.
298 ///
299 /// **Why is this bad?** Since Rust 1.6, the `extend_from_slice(_)` method is
300 /// stable and at least for now faster.
301 ///
302 /// **Known problems:** None.
303 ///
304 /// **Example:**
305 /// ```rust
306 /// my_vec.extend(&xs)
307 /// ```
308 declare_lint! {
309     pub EXTEND_FROM_SLICE,
310     Warn,
311     "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
312 }
313
314 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
315 ///
316 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
317 /// generics, not for using the `clone` method on a concrete type.
318 ///
319 /// **Known problems:** None.
320 ///
321 /// **Example:**
322 /// ```rust
323 /// 42u64.clone()
324 /// ```
325 declare_lint! {
326     pub CLONE_ON_COPY,
327     Warn,
328     "using `clone` on a `Copy` type"
329 }
330
331 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
332 ///
333 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
334 /// cloning the underlying `T`.
335 ///
336 /// **Known problems:** None.
337 ///
338 /// **Example:**
339 /// ```rust
340 /// fn main() {
341 ///    let x = vec![1];
342 ///    let y = &&x;
343 ///    let z = y.clone();
344 ///    println!("{:p} {:p}",*y, z); // prints out the same pointer
345 /// }
346 /// ```
347 declare_lint! {
348     pub CLONE_DOUBLE_REF,
349     Warn,
350     "using `clone` on `&&T`"
351 }
352
353 /// **What it does:** Checks for `new` not returning `Self`.
354 ///
355 /// **Why is this bad?** As a convention, `new` methods are used to make a new
356 /// instance of a type.
357 ///
358 /// **Known problems:** None.
359 ///
360 /// **Example:**
361 /// ```rust
362 /// impl Foo {
363 ///     fn new(..) -> NotAFoo {
364 ///     }
365 /// }
366 /// ```
367 declare_lint! {
368     pub NEW_RET_NO_SELF,
369     Warn,
370     "not returning `Self` in a `new` method"
371 }
372
373 /// **What it does:** Checks for string methods that receive a single-character
374 /// `str` as an argument, e.g. `_.split("x")`.
375 ///
376 /// **Why is this bad?** Performing these methods using a `char` is faster than
377 /// using a `str`.
378 ///
379 /// **Known problems:** Does not catch multi-byte unicode characters.
380 ///
381 /// **Example:**
382 /// `_.split("x")` could be `_.split('x')
383 declare_lint! {
384     pub SINGLE_CHAR_PATTERN,
385     Warn,
386     "using a single-character str where a char could be used, e.g. \
387      `_.split(\"x\")`"
388 }
389
390 /// **What it does:** Checks for getting the inner pointer of a temporary `CString`.
391 ///
392 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
393 /// as the `CString` is alive.
394 ///
395 /// **Known problems:** None.
396 ///
397 /// **Example:**
398 /// ```rust,ignore
399 /// let c_str = CString::new("foo").unwrap().as_ptr();
400 /// unsafe {
401 /// call_some_ffi_func(c_str);
402 /// }
403 /// ```
404 /// Here `c_str` point to a freed address. The correct use would be:
405 /// ```rust,ignore
406 /// let c_str = CString::new("foo").unwrap();
407 /// unsafe {
408 ///     call_some_ffi_func(c_str.as_ptr());
409 /// }
410 /// ```
411 declare_lint! {
412     pub TEMPORARY_CSTRING_AS_PTR,
413     Warn,
414     "getting the inner pointer of a temporary `CString`"
415 }
416
417 /// **What it does:** Checks for use of `.iter().nth()` (and the related
418 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
419 ///
420 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
421 /// readable.
422 ///
423 /// **Known problems:** None.
424 ///
425 /// **Example:**
426 /// ```rust
427 /// let some_vec = vec![0, 1, 2, 3];
428 /// let bad_vec = some_vec.iter().nth(3);
429 /// let bad_slice = &some_vec[..].iter().nth(3);
430 /// ```
431 /// The correct use would be:
432 /// ```rust
433 /// let some_vec = vec![0, 1, 2, 3];
434 /// let bad_vec = some_vec.get(3);
435 /// let bad_slice = &some_vec[..].get(3);
436 /// ```
437 declare_lint! {
438     pub ITER_NTH,
439     Warn,
440     "using `.iter().nth()` on a standard library type with O(1) element access"
441 }
442
443 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
444 ///
445 /// **Why is this bad?** `.nth(x)` is cleaner
446 ///
447 /// **Known problems:** None.
448 ///
449 /// **Example:**
450 /// ```rust
451 /// let some_vec = vec![0, 1, 2, 3];
452 /// let bad_vec = some_vec.iter().skip(3).next();
453 /// let bad_slice = &some_vec[..].iter().skip(3).next();
454 /// ```
455 /// The correct use would be:
456 /// ```rust
457 /// let some_vec = vec![0, 1, 2, 3];
458 /// let bad_vec = some_vec.iter().nth(3);
459 /// let bad_slice = &some_vec[..].iter().nth(3);
460 /// ```
461 declare_lint! {
462     pub ITER_SKIP_NEXT,
463     Warn,
464     "using `.skip(x).next()` on an iterator"
465 }
466
467 /// **What it does:** Checks for use of `.get().unwrap()` (or
468 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
469 ///
470 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
471 /// concise.
472 ///
473 /// **Known problems:** None.
474 ///
475 /// **Example:**
476 /// ```rust
477 /// let some_vec = vec![0, 1, 2, 3];
478 /// let last = some_vec.get(3).unwrap();
479 /// *some_vec.get_mut(0).unwrap() = 1;
480 /// ```
481 /// The correct use would be:
482 /// ```rust
483 /// let some_vec = vec![0, 1, 2, 3];
484 /// let last = some_vec[3];
485 /// some_vec[0] = 1;
486 /// ```
487 declare_lint! {
488     pub GET_UNWRAP,
489     Warn,
490     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
491 }
492
493 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
494 /// `&str` or `String`.
495 ///
496 /// **Why is this bad?** `.push_str(s)` is clearer and faster
497 ///
498 /// **Known problems:** None.
499 ///
500 /// **Example:**
501 /// ```rust
502 /// let abc = "abc";
503 /// let def = String::from("def");
504 /// let mut s = String::new();
505 /// s.extend(abc.chars());
506 /// s.extend(def.chars());
507 /// ```
508 /// The correct use would be:
509 /// ```rust
510 /// let abc = "abc";
511 /// let def = String::from("def");
512 /// let mut s = String::new();
513 /// s.push_str(abc);
514 /// s.push_str(&def));
515 /// ```
516
517 declare_lint! {
518     pub STRING_EXTEND_CHARS,
519     Warn,
520     "using `x.extend(s.chars())` where s is a `&str` or `String`"
521 }
522
523
524 impl LintPass for Pass {
525     fn get_lints(&self) -> LintArray {
526         lint_array!(EXTEND_FROM_SLICE,
527                     OPTION_UNWRAP_USED,
528                     RESULT_UNWRAP_USED,
529                     SHOULD_IMPLEMENT_TRAIT,
530                     WRONG_SELF_CONVENTION,
531                     WRONG_PUB_SELF_CONVENTION,
532                     OK_EXPECT,
533                     OPTION_MAP_UNWRAP_OR,
534                     OPTION_MAP_UNWRAP_OR_ELSE,
535                     OR_FUN_CALL,
536                     CHARS_NEXT_CMP,
537                     CLONE_ON_COPY,
538                     CLONE_DOUBLE_REF,
539                     NEW_RET_NO_SELF,
540                     SINGLE_CHAR_PATTERN,
541                     SEARCH_IS_SOME,
542                     TEMPORARY_CSTRING_AS_PTR,
543                     FILTER_NEXT,
544                     FILTER_MAP,
545                     ITER_NTH,
546                     ITER_SKIP_NEXT,
547                     GET_UNWRAP,
548                     STRING_EXTEND_CHARS)
549     }
550 }
551
552 impl LateLintPass for Pass {
553     #[allow(unused_attributes)]
554     // ^ required because `cyclomatic_complexity` attribute shows up as unused
555     #[cyclomatic_complexity = "30"]
556     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
557         if in_macro(cx, expr.span) {
558             return;
559         }
560
561         match expr.node {
562             hir::ExprMethodCall(name, _, ref args) => {
563                 // Chain calls
564                 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
565                 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
566                     lint_get_unwrap(cx, expr, arglists[0], false);
567                 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
568                     lint_get_unwrap(cx, expr, arglists[0], true);
569                 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
570                     lint_unwrap(cx, expr, arglists[0]);
571                 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
572                     lint_ok_expect(cx, expr, arglists[0]);
573                 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
574                     lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
575                 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
576                     lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
577                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
578                     lint_filter_next(cx, expr, arglists[0]);
579                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
580                     lint_filter_map(cx, expr, arglists[0], arglists[1]);
581                 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
582                     lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
583                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
584                     lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
585                 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
586                     lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
587                 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
588                     lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
589                 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
590                     lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
591                 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
592                     lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
593                 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
594                     lint_extend(cx, expr, arglists[0]);
595                 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
596                     lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
597                 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
598                     lint_iter_nth(cx, expr, arglists[0], false);
599                 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
600                     lint_iter_nth(cx, expr, arglists[0], true);
601                 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
602                     lint_iter_skip_next(cx, expr);
603                 }
604
605                 lint_or_fun_call(cx, expr, &name.node.as_str(), args);
606
607                 let self_ty = cx.tcx.tables().expr_ty_adjusted(&args[0]);
608                 if args.len() == 1 && name.node.as_str() == "clone" {
609                     lint_clone_on_copy(cx, expr, &args[0], self_ty);
610                 }
611
612                 match self_ty.sty {
613                     ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
614                         for &(method, pos) in &PATTERN_METHODS {
615                             if name.node.as_str() == method && args.len() > pos {
616                                 lint_single_char_pattern(cx, expr, &args[pos]);
617                             }
618                         }
619                     }
620                     _ => (),
621                 }
622             }
623             hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
624                 if !lint_chars_next(cx, expr, lhs, rhs, op.node == hir::BiEq) {
625                     lint_chars_next(cx, expr, rhs, lhs, op.node == hir::BiEq);
626                 }
627             }
628             _ => (),
629         }
630     }
631
632     fn check_impl_item(&mut self, cx: &LateContext, implitem: &hir::ImplItem) {
633         if in_external_macro(cx, implitem.span) {
634             return;
635         }
636         let name = implitem.name;
637         let parent = cx.tcx.map.get_parent(implitem.id);
638         let item = cx.tcx.map.expect_item(parent);
639         if_let_chain! {[
640             let hir::ImplItemKind::Method(ref sig, _) = implitem.node,
641             let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
642             let hir::ItemImpl(_, _, _, None, _, _) = item.node,
643         ], {
644             // check missing trait implementations
645             for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
646                 if name.as_str() == method_name &&
647                    sig.decl.inputs.len() == n_args &&
648                    out_type.matches(&sig.decl.output) &&
649                    self_kind.matches(&explicit_self, false) {
650                     span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
651                         "defining a method called `{}` on this type; consider implementing \
652                          the `{}` trait or choosing a less ambiguous name", name, trait_name));
653                 }
654             }
655
656             // check conventions w.r.t. conversion method names and predicates
657             let ty = cx.tcx.item_type(cx.tcx.map.local_def_id(item.id));
658             let is_copy = is_copy(cx, ty, item.id);
659             for &(ref conv, self_kinds) in &CONVENTIONS {
660                 if_let_chain! {[
661                     conv.check(&name.as_str()),
662                     let Some(explicit_self) = sig.decl.inputs.get(0).and_then(hir::Arg::to_self),
663                     !self_kinds.iter().any(|k| k.matches(&explicit_self, is_copy)),
664                 ], {
665                     let lint = if item.vis == hir::Visibility::Public {
666                         WRONG_PUB_SELF_CONVENTION
667                     } else {
668                         WRONG_SELF_CONVENTION
669                     };
670                     span_lint(cx,
671                               lint,
672                               explicit_self.span,
673                               &format!("methods called `{}` usually take {}; consider choosing a less \
674                                         ambiguous name",
675                                        conv,
676                                        &self_kinds.iter()
677                                                   .map(|k| k.description())
678                                                   .collect::<Vec<_>>()
679                                                   .join(" or ")));
680                 }}
681             }
682
683             let ret_ty = return_ty(cx, implitem.id);
684             if &name.as_str() == &"new" &&
685                !ret_ty.walk().any(|t| same_tys(cx, t, ty, implitem.id)) {
686                 span_lint(cx,
687                           NEW_RET_NO_SELF,
688                           explicit_self.span,
689                           "methods called `new` usually return `Self`");
690             }
691         }}
692     }
693 }
694
695 /// Checks for the `OR_FUN_CALL` lint.
696 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[P<hir::Expr>]) {
697     /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
698     fn check_unwrap_or_default(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr,
699                                or_has_args: bool, span: Span)
700                                -> bool {
701         if or_has_args {
702             return false;
703         }
704
705         if name == "unwrap_or" {
706             if let hir::ExprPath(_, ref path) = fun.node {
707                 let path: &str = &path.segments
708                                       .last()
709                                       .expect("A path must have at least one segment")
710                                       .name
711                                       .as_str();
712
713                 if ["default", "new"].contains(&path) {
714                     let arg_ty = cx.tcx.tables().expr_ty(arg);
715                     let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
716                         default_trait_id
717                     } else {
718                         return false;
719                     };
720
721                     if implements_trait(cx, arg_ty, default_trait_id, Vec::new()) {
722                         span_lint_and_then(cx,
723                                   OR_FUN_CALL,
724                                   span,
725                                   &format!("use of `{}` followed by a call to `{}`", name, path),
726                                   |db| {
727                                       db.span_suggestion(span, "try this",
728                                                           format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")));
729                                   });
730                         return true;
731                     }
732                 }
733             }
734         }
735
736         false
737     }
738
739     /// Check for `*or(foo())`.
740     fn check_general_case(cx: &LateContext, name: &str, fun: &hir::Expr, self_expr: &hir::Expr, arg: &hir::Expr, or_has_args: bool,
741                           span: Span) {
742         // don't lint for constant values
743         // FIXME: can we `expect` here instead of match?
744         if let Some(qualif) = cx.tcx.const_qualif_map.borrow().get(&arg.id) {
745             if !qualif.contains(ConstQualif::NOT_CONST) {
746                 return;
747             }
748         }
749         // (path, fn_has_argument, methods, suffix)
750         let know_types: &[(&[_], _, &[_], _)] = &[(&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
751                                                   (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
752                                                   (&paths::OPTION,
753                                                    false,
754                                                    &["map_or", "ok_or", "or", "unwrap_or"],
755                                                    "else"),
756                                                   (&paths::RESULT, true, &["or", "unwrap_or"], "else")];
757
758         let self_ty = cx.tcx.tables().expr_ty(self_expr);
759
760         let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
761                                                       know_types.iter().find(|&&i| match_type(cx, self_ty, i.0)) {
762             (fn_has_arguments, poss, suffix)
763         } else {
764             return;
765         };
766
767         if !poss.contains(&name) {
768             return;
769         }
770
771         let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
772             (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
773             (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
774             (false, true) => snippet(cx, fun.span, ".."),
775         };
776
777         span_lint_and_then(cx, OR_FUN_CALL, span, &format!("use of `{}` followed by a function call", name), |db| {
778             db.span_suggestion(span,
779                                "try this",
780                                format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg));
781         });
782     }
783
784     if args.len() == 2 {
785         if let hir::ExprCall(ref fun, ref or_args) = args[1].node {
786             let or_has_args = !or_args.is_empty();
787             if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
788                 check_general_case(cx, name, fun, &args[0], &args[1], or_has_args, expr.span);
789             }
790         }
791     }
792 }
793
794 /// Checks for the `CLONE_ON_COPY` lint.
795 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: ty::Ty) {
796     let ty = cx.tcx.tables().expr_ty(expr);
797     let parent = cx.tcx.map.get_parent(expr.id);
798     let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, parent);
799     if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
800         if let ty::TyRef(..) = inner.sty {
801             span_lint_and_then(cx,
802                                CLONE_DOUBLE_REF,
803                                expr.span,
804                                "using `clone` on a double-reference; \
805                                 this will copy the reference instead of cloning the inner type",
806                                |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
807                                    db.span_suggestion(expr.span, "try dereferencing it", format!("({}).clone()", snip.deref()));
808                                });
809             return; // don't report clone_on_copy
810         }
811     }
812
813     if !ty.moves_by_default(cx.tcx.global_tcx(), &parameter_environment, expr.span) {
814         span_lint_and_then(cx,
815                            CLONE_ON_COPY,
816                            expr.span,
817                            "using `clone` on a `Copy` type",
818                            |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
819                                if let ty::TyRef(..) = cx.tcx.tables().expr_ty(arg).sty {
820                                    db.span_suggestion(expr.span, "try dereferencing it", format!("{}", snip.deref()));
821                                } else {
822                                    db.span_suggestion(expr.span, "try removing the `clone` call", format!("{}", snip));
823                                }
824                            });
825     }
826 }
827
828 fn lint_vec_extend(cx: &LateContext, expr: &hir::Expr, args: &MethodArgs) {
829     let arg_ty = cx.tcx.tables().expr_ty(&args[1]);
830     if let Some(slice) = derefs_to_slice(cx, &args[1], arg_ty) {
831         span_lint_and_then(cx, EXTEND_FROM_SLICE, expr.span, "use of `extend` to extend a Vec by a slice", |db| {
832             db.span_suggestion(expr.span,
833                                "try this",
834                                format!("{}.extend_from_slice({})",
835                                        snippet(cx, args[0].span, "_"),
836                                        slice));
837         });
838     }
839 }
840
841 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &MethodArgs) {
842     let arg = &args[1];
843     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
844         let target = &arglists[0][0];
845         let (self_ty, _) = walk_ptrs_ty_depth(cx.tcx.tables().expr_ty(target));
846         let ref_str = if self_ty.sty == ty::TyStr {
847             ""
848         } else if match_type(cx, self_ty, &paths::STRING) {
849             "&"
850         } else {
851             return;
852         };
853
854         span_lint_and_then(
855             cx,
856             STRING_EXTEND_CHARS,
857             expr.span,
858             "calling `.extend(_.chars())`",
859             |db| {
860                 db.span_suggestion(expr.span, "try this",
861                         format!("{}.push_str({}{})",
862                                 snippet(cx, args[0].span, "_"),
863                                 ref_str,
864                                 snippet(cx, target.span, "_")));
865             });
866     }
867 }
868
869 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &MethodArgs) {
870     let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.tables().expr_ty(&args[0]));
871     if match_type(cx, obj_ty, &paths::VEC) {
872         lint_vec_extend(cx, expr, args);
873     } else if match_type(cx, obj_ty, &paths::STRING) {
874         lint_string_extend(cx, expr, args);
875     }
876 }
877
878 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
879     if_let_chain!{[
880         let hir::ExprCall(ref fun, ref args) = new.node,
881         args.len() == 1,
882         let hir::ExprPath(None, ref path) = fun.node,
883         match_path(path, &paths::CSTRING_NEW),
884     ], {
885         span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
886                            "you are getting the inner pointer of a temporary `CString`",
887                            |db| {
888                                db.note("that pointer will be invalid outside this expression");
889                                db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
890                            });
891     }}
892 }
893
894 #[allow(ptr_arg)]
895 // Type of MethodArgs is potentially a Vec
896 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &MethodArgs, is_mut: bool){
897     let mut_str = if is_mut { "_mut" } else {""};
898     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tcx.tables().expr_ty(&iter_args[0])).is_some() {
899         "slice"
900     }
901     else if match_type(cx, cx.tcx.tables().expr_ty(&iter_args[0]), &paths::VEC) {
902         "Vec"
903     }
904     else if match_type(cx, cx.tcx.tables().expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
905         "VecDeque"
906     }
907     else {
908         return; // caller is not a type that we want to lint
909     };
910
911     span_lint(
912         cx,
913         ITER_NTH,
914         expr.span,
915         &format!("called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
916                  mut_str, caller_type)
917     );
918 }
919
920 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &MethodArgs, is_mut: bool) {
921     // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
922     // because they do not implement `IndexMut`
923     let expr_ty = cx.tcx.tables().expr_ty(&get_args[0]);
924     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
925         "slice"
926     } else if match_type(cx, expr_ty, &paths::VEC) {
927         "Vec"
928     } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
929         "VecDeque"
930     } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
931         "HashMap"
932     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
933         "BTreeMap"
934     } else {
935         return; // caller is not a type that we want to lint
936     };
937
938     let mut_str = if is_mut { "_mut" } else { "" };
939     let borrow_str = if is_mut { "&mut " } else { "&" };
940     span_lint_and_then(
941         cx,
942         GET_UNWRAP,
943         expr.span,
944         &format!("called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
945                  mut_str, caller_type),
946         |db| {
947             db.span_suggestion(
948                 expr.span,
949                 "try this",
950                 format!("{}{}[{}]", borrow_str, snippet(cx, get_args[0].span, "_"),
951                         snippet(cx, get_args[1].span, "_"))
952             );
953         }
954     );
955 }
956
957 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr){
958     // lint if caller of skip is an Iterator
959     if match_trait_method(cx, expr, &paths::ITERATOR) {
960          span_lint(
961             cx,
962             ITER_SKIP_NEXT,
963             expr.span,
964             "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`"
965         );
966     }
967 }
968
969 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: ty::Ty) -> Option<sugg::Sugg<'static>> {
970     fn may_slice(cx: &LateContext, ty: ty::Ty) -> bool {
971         match ty.sty {
972             ty::TySlice(_) => true,
973             ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
974             ty::TyArray(_, size) => size < 32,
975             ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) |
976             ty::TyBox(inner) => may_slice(cx, inner),
977             _ => false,
978         }
979     }
980
981     if let hir::ExprMethodCall(name, _, ref args) = expr.node {
982         if &name.node.as_str() == &"iter" && may_slice(cx, cx.tcx.tables().expr_ty(&args[0])) {
983             sugg::Sugg::hir_opt(cx, &*args[0]).map(|sugg| {
984                 sugg.addr()
985             })
986         } else {
987             None
988         }
989     } else {
990         match ty.sty {
991             ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
992             ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) |
993             ty::TyBox(inner) => {
994                 if may_slice(cx, inner) {
995                     sugg::Sugg::hir_opt(cx, expr)
996                 } else {
997                     None
998                 }
999             }
1000             _ => None,
1001         }
1002     }
1003 }
1004
1005 #[allow(ptr_arg)]
1006 // Type of MethodArgs is potentially a Vec
1007 /// lint use of `unwrap()` for `Option`s and `Result`s
1008 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &MethodArgs) {
1009     let (obj_ty, _) = walk_ptrs_ty_depth(cx.tcx.tables().expr_ty(&unwrap_args[0]));
1010
1011     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1012         Some((OPTION_UNWRAP_USED, "an Option", "None"))
1013     } else if match_type(cx, obj_ty, &paths::RESULT) {
1014         Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1015     } else {
1016         None
1017     };
1018
1019     if let Some((lint, kind, none_value)) = mess {
1020         span_lint(cx,
1021                   lint,
1022                   expr.span,
1023                   &format!("used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1024                             using expect() to provide a better panic
1025                             message",
1026                            kind,
1027                            none_value));
1028     }
1029 }
1030
1031 #[allow(ptr_arg)]
1032 // Type of MethodArgs is potentially a Vec
1033 /// lint use of `ok().expect()` for `Result`s
1034 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &MethodArgs) {
1035     // lint if the caller of `ok()` is a `Result`
1036     if match_type(cx, cx.tcx.tables().expr_ty(&ok_args[0]), &paths::RESULT) {
1037         let result_type = cx.tcx.tables().expr_ty(&ok_args[0]);
1038         if let Some(error_type) = get_error_type(cx, result_type) {
1039             if has_debug_impl(error_type, cx) {
1040                 span_lint(cx,
1041                           OK_EXPECT,
1042                           expr.span,
1043                           "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`");
1044             }
1045         }
1046     }
1047 }
1048
1049 #[allow(ptr_arg)]
1050 // Type of MethodArgs is potentially a Vec
1051 /// lint use of `map().unwrap_or()` for `Option`s
1052 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
1053     // lint if the caller of `map()` is an `Option`
1054     if match_type(cx, cx.tcx.tables().expr_ty(&map_args[0]), &paths::OPTION) {
1055         // lint message
1056         let msg = "called `map(f).unwrap_or(a)` on an Option value. This can be done more directly by calling \
1057                    `map_or(a, f)` instead";
1058         // get snippets for args to map() and unwrap_or()
1059         let map_snippet = snippet(cx, map_args[1].span, "..");
1060         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1061         // lint, with note if neither arg is > 1 line and both map() and
1062         // unwrap_or() have the same span
1063         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1064         let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
1065         if same_span && !multiline {
1066             span_note_and_lint(cx,
1067                                OPTION_MAP_UNWRAP_OR,
1068                                expr.span,
1069                                msg,
1070                                expr.span,
1071                                &format!("replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
1072                                         map_snippet,
1073                                         unwrap_snippet));
1074         } else if same_span && multiline {
1075             span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1076         };
1077     }
1078 }
1079
1080 #[allow(ptr_arg)]
1081 // Type of MethodArgs is potentially a Vec
1082 /// lint use of `map().unwrap_or_else()` for `Option`s
1083 fn lint_map_unwrap_or_else(cx: &LateContext, expr: &hir::Expr, map_args: &MethodArgs, unwrap_args: &MethodArgs) {
1084     // lint if the caller of `map()` is an `Option`
1085     if match_type(cx, cx.tcx.tables().expr_ty(&map_args[0]), &paths::OPTION) {
1086         // lint message
1087         let msg = "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1088                    `map_or_else(g, f)` instead";
1089         // get snippets for args to map() and unwrap_or_else()
1090         let map_snippet = snippet(cx, map_args[1].span, "..");
1091         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1092         // lint, with note if neither arg is > 1 line and both map() and
1093         // unwrap_or_else() have the same span
1094         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1095         let same_span = map_args[1].span.expn_id == unwrap_args[1].span.expn_id;
1096         if same_span && !multiline {
1097             span_note_and_lint(cx,
1098                                OPTION_MAP_UNWRAP_OR_ELSE,
1099                                expr.span,
1100                                msg,
1101                                expr.span,
1102                                &format!("replace `map({0}).unwrap_or_else({1})` with `with map_or_else({1}, {0})`",
1103                                         map_snippet,
1104                                         unwrap_snippet));
1105         } else if same_span && multiline {
1106             span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
1107         };
1108     }
1109 }
1110
1111 #[allow(ptr_arg)]
1112 // Type of MethodArgs is potentially a Vec
1113 /// lint use of `filter().next()` for `Iterators`
1114 fn lint_filter_next(cx: &LateContext, expr: &hir::Expr, filter_args: &MethodArgs) {
1115     // lint if caller of `.filter().next()` is an Iterator
1116     if match_trait_method(cx, expr, &paths::ITERATOR) {
1117         let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling `.find(p)` \
1118                    instead.";
1119         let filter_snippet = snippet(cx, filter_args[1].span, "..");
1120         if filter_snippet.lines().count() <= 1 {
1121             // add note if not multi-line
1122             span_note_and_lint(cx,
1123                                FILTER_NEXT,
1124                                expr.span,
1125                                msg,
1126                                expr.span,
1127                                &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet));
1128         } else {
1129             span_lint(cx, FILTER_NEXT, expr.span, msg);
1130         }
1131     }
1132 }
1133
1134 // Type of MethodArgs is potentially a Vec
1135 /// lint use of `filter().map()` for `Iterators`
1136 fn lint_filter_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1137     // lint if caller of `.filter().map()` is an Iterator
1138     if match_trait_method(cx, expr, &paths::ITERATOR) {
1139         let msg = "called `filter(p).map(q)` on an `Iterator`. \
1140                    This is more succinctly expressed by calling `.filter_map(..)` instead.";
1141         span_lint(cx, FILTER_MAP, expr.span, msg);
1142     }
1143 }
1144
1145 // Type of MethodArgs is potentially a Vec
1146 /// lint use of `filter().map()` for `Iterators`
1147 fn lint_filter_map_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1148     // lint if caller of `.filter().map()` is an Iterator
1149     if match_trait_method(cx, expr, &paths::ITERATOR) {
1150         let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1151                    This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1152         span_lint(cx, FILTER_MAP, expr.span, msg);
1153     }
1154 }
1155
1156 // Type of MethodArgs is potentially a Vec
1157 /// lint use of `filter().flat_map()` for `Iterators`
1158 fn lint_filter_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1159     // lint if caller of `.filter().flat_map()` is an Iterator
1160     if match_trait_method(cx, expr, &paths::ITERATOR) {
1161         let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1162                    This is more succinctly expressed by calling `.flat_map(..)` \
1163                    and filtering by returning an empty Iterator.";
1164         span_lint(cx, FILTER_MAP, expr.span, msg);
1165     }
1166 }
1167
1168 // Type of MethodArgs is potentially a Vec
1169 /// lint use of `filter_map().flat_map()` for `Iterators`
1170 fn lint_filter_map_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &MethodArgs, _map_args: &MethodArgs) {
1171     // lint if caller of `.filter_map().flat_map()` is an Iterator
1172     if match_trait_method(cx, expr, &paths::ITERATOR) {
1173         let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1174                    This is more succinctly expressed by calling `.flat_map(..)` \
1175                    and filtering by returning an empty Iterator.";
1176         span_lint(cx, FILTER_MAP, expr.span, msg);
1177     }
1178 }
1179
1180 #[allow(ptr_arg)]
1181 // Type of MethodArgs is potentially a Vec
1182 /// lint searching an Iterator followed by `is_some()`
1183 fn lint_search_is_some(cx: &LateContext, expr: &hir::Expr, search_method: &str, search_args: &MethodArgs,
1184                        is_some_args: &MethodArgs) {
1185     // lint if caller of search is an Iterator
1186     if match_trait_method(cx, &*is_some_args[0], &paths::ITERATOR) {
1187         let msg = format!("called `is_some()` after searching an `Iterator` with {}. This is more succinctly expressed \
1188                            by calling `any()`.",
1189                           search_method);
1190         let search_snippet = snippet(cx, search_args[1].span, "..");
1191         if search_snippet.lines().count() <= 1 {
1192             // add note if not multi-line
1193             span_note_and_lint(cx,
1194                                SEARCH_IS_SOME,
1195                                expr.span,
1196                                &msg,
1197                                expr.span,
1198                                &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet));
1199         } else {
1200             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1201         }
1202     }
1203 }
1204
1205 /// Checks for the `CHARS_NEXT_CMP` lint.
1206 fn lint_chars_next(cx: &LateContext, expr: &hir::Expr, chain: &hir::Expr, other: &hir::Expr, eq: bool) -> bool {
1207     if_let_chain! {[
1208         let Some(args) = method_chain_args(chain, &["chars", "next"]),
1209         let hir::ExprCall(ref fun, ref arg_char) = other.node,
1210         arg_char.len() == 1,
1211         let hir::ExprPath(None, ref path) = fun.node,
1212         path.segments.len() == 1 && path.segments[0].name.as_str() == "Some"
1213     ], {
1214         let self_ty = walk_ptrs_ty(cx.tcx.tables().expr_ty_adjusted(&args[0][0]));
1215
1216         if self_ty.sty != ty::TyStr {
1217             return false;
1218         }
1219
1220         span_lint_and_then(cx,
1221                            CHARS_NEXT_CMP,
1222                            expr.span,
1223                            "you should use the `starts_with` method",
1224                            |db| {
1225                                let sugg = format!("{}{}.starts_with({})",
1226                                                   if eq { "" } else { "!" },
1227                                                   snippet(cx, args[0][0].span, "_"),
1228                                                   snippet(cx, arg_char[0].span, "_")
1229                                                   );
1230
1231                                db.span_suggestion(expr.span, "like this", sugg);
1232                            });
1233
1234         return true;
1235     }}
1236
1237     false
1238 }
1239
1240 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1241 fn lint_single_char_pattern(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1242     if let Ok(ConstVal::Str(r)) = eval_const_expr_partial(cx.tcx, arg, ExprTypeChecked, None) {
1243         if r.len() == 1 {
1244             let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1245             span_lint_and_then(cx,
1246                                SINGLE_CHAR_PATTERN,
1247                                arg.span,
1248                                "single-character string constant used as pattern",
1249                                |db| {
1250                                    db.span_suggestion(expr.span, "try using a char instead:", hint);
1251                                });
1252         }
1253     }
1254 }
1255
1256 /// Given a `Result<T, E>` type, return its error type (`E`).
1257 fn get_error_type<'a>(cx: &LateContext, ty: ty::Ty<'a>) -> Option<ty::Ty<'a>> {
1258     if let ty::TyAdt(_, substs) = ty.sty {
1259         if match_type(cx, ty, &paths::RESULT) {
1260             substs.types().nth(1)
1261         } else {
1262             None
1263         }
1264     } else {
1265         None
1266     }
1267 }
1268
1269 /// This checks whether a given type is known to implement Debug.
1270 fn has_debug_impl<'a, 'b>(ty: ty::Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1271     match cx.tcx.lang_items.debug_trait() {
1272         Some(debug) => implements_trait(cx, ty, debug, Vec::new()),
1273         None => false,
1274     }
1275 }
1276
1277 enum Convention {
1278     Eq(&'static str),
1279     StartsWith(&'static str),
1280 }
1281
1282 #[cfg_attr(rustfmt, rustfmt_skip)]
1283 const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
1284     (Convention::Eq("new"), &[SelfKind::No]),
1285     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1286     (Convention::StartsWith("from_"), &[SelfKind::No]),
1287     (Convention::StartsWith("into_"), &[SelfKind::Value]),
1288     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1289     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1290 ];
1291
1292 #[cfg_attr(rustfmt, rustfmt_skip)]
1293 const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
1294     ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1295     ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1296     ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1297     ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1298     ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1299     ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1300     ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1301     ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1302     ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1303     ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1304     ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1305     ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1306     ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1307     ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1308     ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1309     ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1310     ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1311     ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1312     ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1313     ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1314     ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1315     ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1316     ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1317     ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1318     ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1319     ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1320     ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1321     ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1322     ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1323     ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1324 ];
1325
1326 #[cfg_attr(rustfmt, rustfmt_skip)]
1327 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1328     ("contains", 1),
1329     ("starts_with", 1),
1330     ("ends_with", 1),
1331     ("find", 1),
1332     ("rfind", 1),
1333     ("split", 1),
1334     ("rsplit", 1),
1335     ("split_terminator", 1),
1336     ("rsplit_terminator", 1),
1337     ("splitn", 2),
1338     ("rsplitn", 2),
1339     ("matches", 1),
1340     ("rmatches", 1),
1341     ("match_indices", 1),
1342     ("rmatch_indices", 1),
1343     ("trim_left_matches", 1),
1344     ("trim_right_matches", 1),
1345 ];
1346
1347
1348 #[derive(Clone, Copy)]
1349 enum SelfKind {
1350     Value,
1351     Ref,
1352     RefMut,
1353     No,
1354 }
1355
1356 impl SelfKind {
1357     fn matches(self, slf: &hir::ExplicitSelf, allow_value_for_ref: bool) -> bool {
1358         match (self, &slf.node) {
1359             (SelfKind::Value, &hir::SelfKind::Value(_)) |
1360             (SelfKind::Ref, &hir::SelfKind::Region(_, hir::Mutability::MutImmutable)) |
1361             (SelfKind::RefMut, &hir::SelfKind::Region(_, hir::Mutability::MutMutable)) => true,
1362             (SelfKind::Ref, &hir::SelfKind::Value(_)) |
1363             (SelfKind::RefMut, &hir::SelfKind::Value(_)) => allow_value_for_ref,
1364             (_, &hir::SelfKind::Explicit(ref ty, _)) => self.matches_explicit_type(ty, allow_value_for_ref),
1365
1366             _ => false,
1367         }
1368     }
1369
1370     fn matches_explicit_type(self, ty: &hir::Ty, allow_value_for_ref: bool) -> bool {
1371         match (self, &ty.node) {
1372             (SelfKind::Value, &hir::TyPath(..)) |
1373             (SelfKind::Ref, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutImmutable, .. })) |
1374             (SelfKind::RefMut, &hir::TyRptr(_, hir::MutTy { mutbl: hir::Mutability::MutMutable, .. })) => true,
1375             (SelfKind::Ref, &hir::TyPath(..)) |
1376             (SelfKind::RefMut, &hir::TyPath(..)) => allow_value_for_ref,
1377             _ => false,
1378         }
1379     }
1380
1381     fn description(&self) -> &'static str {
1382         match *self {
1383             SelfKind::Value => "self by value",
1384             SelfKind::Ref => "self by reference",
1385             SelfKind::RefMut => "self by mutable reference",
1386             SelfKind::No => "no self",
1387         }
1388     }
1389 }
1390
1391 impl Convention {
1392     fn check(&self, other: &str) -> bool {
1393         match *self {
1394             Convention::Eq(this) => this == other,
1395             Convention::StartsWith(this) => other.starts_with(this) && this != other,
1396         }
1397     }
1398 }
1399
1400 impl fmt::Display for Convention {
1401     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1402         match *self {
1403             Convention::Eq(this) => this.fmt(f),
1404             Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1405         }
1406     }
1407 }
1408
1409 #[derive(Clone, Copy)]
1410 enum OutType {
1411     Unit,
1412     Bool,
1413     Any,
1414     Ref,
1415 }
1416
1417 impl OutType {
1418     fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1419         match (self, ty) {
1420             (&OutType::Unit, &hir::DefaultReturn(_)) => true,
1421             (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
1422             (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
1423             (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
1424             (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
1425             _ => false,
1426         }
1427     }
1428 }
1429
1430 fn is_bool(ty: &hir::Ty) -> bool {
1431     if let hir::TyPath(None, ref p) = ty.node {
1432         match_path(p, &["bool"])
1433     } else {
1434         false
1435     }
1436 }