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