]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods.rs
a50d77f5521fedf473265e9bff749d96b7ebe215
[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::{self, Ty};
5 use rustc::hir::def::Def;
6 use rustc::ty::subst::Substs;
7 use rustc_const_eval::ConstContext;
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_lint_and_sugg, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, last_path_segment,
14             single_segment_path, match_def_path, is_self, is_self_ty, iter_input_pats, match_path_old};
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(...)`
69 /// 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 `.clone()` on a `Copy` type.
297 ///
298 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
299 /// generics, not for using the `clone` method on a concrete type.
300 ///
301 /// **Known problems:** None.
302 ///
303 /// **Example:**
304 /// ```rust
305 /// 42u64.clone()
306 /// ```
307 declare_lint! {
308     pub CLONE_ON_COPY,
309     Warn,
310     "using `clone` on a `Copy` type"
311 }
312
313 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
314 ///
315 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
316 /// cloning the underlying `T`.
317 ///
318 /// **Known problems:** None.
319 ///
320 /// **Example:**
321 /// ```rust
322 /// fn main() {
323 ///    let x = vec![1];
324 ///    let y = &&x;
325 ///    let z = y.clone();
326 ///    println!("{:p} {:p}",*y, z); // prints out the same pointer
327 /// }
328 /// ```
329 declare_lint! {
330     pub CLONE_DOUBLE_REF,
331     Warn,
332     "using `clone` on `&&T`"
333 }
334
335 /// **What it does:** Checks for `new` not returning `Self`.
336 ///
337 /// **Why is this bad?** As a convention, `new` methods are used to make a new
338 /// instance of a type.
339 ///
340 /// **Known problems:** None.
341 ///
342 /// **Example:**
343 /// ```rust
344 /// impl Foo {
345 ///     fn new(..) -> NotAFoo {
346 ///     }
347 /// }
348 /// ```
349 declare_lint! {
350     pub NEW_RET_NO_SELF,
351     Warn,
352     "not returning `Self` in a `new` method"
353 }
354
355 /// **What it does:** Checks for string methods that receive a single-character
356 /// `str` as an argument, e.g. `_.split("x")`.
357 ///
358 /// **Why is this bad?** Performing these methods using a `char` is faster than
359 /// using a `str`.
360 ///
361 /// **Known problems:** Does not catch multi-byte unicode characters.
362 ///
363 /// **Example:**
364 /// `_.split("x")` could be `_.split('x')
365 declare_lint! {
366     pub SINGLE_CHAR_PATTERN,
367     Warn,
368     "using a single-character str where a char could be used, e.g. \
369      `_.split(\"x\")`"
370 }
371
372 /// **What it does:** Checks for getting the inner pointer of a temporary
373 /// `CString`.
374 ///
375 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
376 /// as the `CString` is alive.
377 ///
378 /// **Known problems:** None.
379 ///
380 /// **Example:**
381 /// ```rust,ignore
382 /// let c_str = CString::new("foo").unwrap().as_ptr();
383 /// unsafe {
384 /// call_some_ffi_func(c_str);
385 /// }
386 /// ```
387 /// Here `c_str` point to a freed address. The correct use would be:
388 /// ```rust,ignore
389 /// let c_str = CString::new("foo").unwrap();
390 /// unsafe {
391 ///     call_some_ffi_func(c_str.as_ptr());
392 /// }
393 /// ```
394 declare_lint! {
395     pub TEMPORARY_CSTRING_AS_PTR,
396     Warn,
397     "getting the inner pointer of a temporary `CString`"
398 }
399
400 /// **What it does:** Checks for use of `.iter().nth()` (and the related
401 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
402 ///
403 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
404 /// readable.
405 ///
406 /// **Known problems:** None.
407 ///
408 /// **Example:**
409 /// ```rust
410 /// let some_vec = vec![0, 1, 2, 3];
411 /// let bad_vec = some_vec.iter().nth(3);
412 /// let bad_slice = &some_vec[..].iter().nth(3);
413 /// ```
414 /// The correct use would be:
415 /// ```rust
416 /// let some_vec = vec![0, 1, 2, 3];
417 /// let bad_vec = some_vec.get(3);
418 /// let bad_slice = &some_vec[..].get(3);
419 /// ```
420 declare_lint! {
421     pub ITER_NTH,
422     Warn,
423     "using `.iter().nth()` on a standard library type with O(1) element access"
424 }
425
426 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
427 ///
428 /// **Why is this bad?** `.nth(x)` is cleaner
429 ///
430 /// **Known problems:** None.
431 ///
432 /// **Example:**
433 /// ```rust
434 /// let some_vec = vec![0, 1, 2, 3];
435 /// let bad_vec = some_vec.iter().skip(3).next();
436 /// let bad_slice = &some_vec[..].iter().skip(3).next();
437 /// ```
438 /// The correct use would be:
439 /// ```rust
440 /// let some_vec = vec![0, 1, 2, 3];
441 /// let bad_vec = some_vec.iter().nth(3);
442 /// let bad_slice = &some_vec[..].iter().nth(3);
443 /// ```
444 declare_lint! {
445     pub ITER_SKIP_NEXT,
446     Warn,
447     "using `.skip(x).next()` on an iterator"
448 }
449
450 /// **What it does:** Checks for use of `.get().unwrap()` (or
451 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
452 ///
453 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
454 /// concise.
455 ///
456 /// **Known problems:** None.
457 ///
458 /// **Example:**
459 /// ```rust
460 /// let some_vec = vec![0, 1, 2, 3];
461 /// let last = some_vec.get(3).unwrap();
462 /// *some_vec.get_mut(0).unwrap() = 1;
463 /// ```
464 /// The correct use would be:
465 /// ```rust
466 /// let some_vec = vec![0, 1, 2, 3];
467 /// let last = some_vec[3];
468 /// some_vec[0] = 1;
469 /// ```
470 declare_lint! {
471     pub GET_UNWRAP,
472     Warn,
473     "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
474 }
475
476 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
477 /// `&str` or `String`.
478 ///
479 /// **Why is this bad?** `.push_str(s)` is clearer
480 ///
481 /// **Known problems:** None.
482 ///
483 /// **Example:**
484 /// ```rust
485 /// let abc = "abc";
486 /// let def = String::from("def");
487 /// let mut s = String::new();
488 /// s.extend(abc.chars());
489 /// s.extend(def.chars());
490 /// ```
491 /// The correct use would be:
492 /// ```rust
493 /// let abc = "abc";
494 /// let def = String::from("def");
495 /// let mut s = String::new();
496 /// s.push_str(abc);
497 /// s.push_str(&def));
498 /// ```
499 declare_lint! {
500     pub STRING_EXTEND_CHARS,
501     Warn,
502     "using `x.extend(s.chars())` where s is a `&str` or `String`"
503 }
504
505 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
506 /// create a `Vec`.
507 ///
508 /// **Why is this bad?** `.to_vec()` is clearer
509 ///
510 /// **Known problems:** None.
511 ///
512 /// **Example:**
513 /// ```rust
514 /// let s = [1,2,3,4,5];
515 /// let s2 : Vec<isize> = s[..].iter().cloned().collect();
516 /// ```
517 /// The better use would be:
518 /// ```rust
519 /// let s = [1,2,3,4,5];
520 /// let s2 : Vec<isize> = s.to_vec();
521 /// ```
522 declare_lint! {
523     pub ITER_CLONED_COLLECT,
524     Warn,
525     "using `.cloned().collect()` on slice to create a `Vec`"
526 }
527
528 impl LintPass for Pass {
529     fn get_lints(&self) -> LintArray {
530         lint_array!(
531             OPTION_UNWRAP_USED,
532             RESULT_UNWRAP_USED,
533             SHOULD_IMPLEMENT_TRAIT,
534             WRONG_SELF_CONVENTION,
535             WRONG_PUB_SELF_CONVENTION,
536             OK_EXPECT,
537             OPTION_MAP_UNWRAP_OR,
538             OPTION_MAP_UNWRAP_OR_ELSE,
539             OR_FUN_CALL,
540             CHARS_NEXT_CMP,
541             CLONE_ON_COPY,
542             CLONE_DOUBLE_REF,
543             NEW_RET_NO_SELF,
544             SINGLE_CHAR_PATTERN,
545             SEARCH_IS_SOME,
546             TEMPORARY_CSTRING_AS_PTR,
547             FILTER_NEXT,
548             FILTER_MAP,
549             ITER_NTH,
550             ITER_SKIP_NEXT,
551             GET_UNWRAP,
552             STRING_EXTEND_CHARS,
553             ITER_CLONED_COLLECT
554         )
555     }
556 }
557
558 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
559     #[allow(unused_attributes)]
560     // ^ required because `cyclomatic_complexity` attribute shows up as unused
561     #[cyclomatic_complexity = "30"]
562     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
563         if in_macro(expr.span) {
564             return;
565         }
566
567         match expr.node {
568             hir::ExprMethodCall(ref method_call, _, ref args) => {
569                 // Chain calls
570                 // GET_UNWRAP needs to be checked before general `UNWRAP` lints
571                 if let Some(arglists) = method_chain_args(expr, &["get", "unwrap"]) {
572                     lint_get_unwrap(cx, expr, arglists[0], false);
573                 } else if let Some(arglists) = method_chain_args(expr, &["get_mut", "unwrap"]) {
574                     lint_get_unwrap(cx, expr, arglists[0], true);
575                 } else if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
576                     lint_unwrap(cx, expr, arglists[0]);
577                 } else if let Some(arglists) = method_chain_args(expr, &["ok", "expect"]) {
578                     lint_ok_expect(cx, expr, arglists[0]);
579                 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or"]) {
580                     lint_map_unwrap_or(cx, expr, arglists[0], arglists[1]);
581                 } else if let Some(arglists) = method_chain_args(expr, &["map", "unwrap_or_else"]) {
582                     lint_map_unwrap_or_else(cx, expr, arglists[0], arglists[1]);
583                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "next"]) {
584                     lint_filter_next(cx, expr, arglists[0]);
585                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "map"]) {
586                     lint_filter_map(cx, expr, arglists[0], arglists[1]);
587                 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "map"]) {
588                     lint_filter_map_map(cx, expr, arglists[0], arglists[1]);
589                 } else if let Some(arglists) = method_chain_args(expr, &["filter", "flat_map"]) {
590                     lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
591                 } else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
592                     lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
593                 } else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
594                     lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
595                 } else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
596                     lint_search_is_some(cx, expr, "position", arglists[0], arglists[1]);
597                 } else if let Some(arglists) = method_chain_args(expr, &["rposition", "is_some"]) {
598                     lint_search_is_some(cx, expr, "rposition", arglists[0], arglists[1]);
599                 } else if let Some(arglists) = method_chain_args(expr, &["extend"]) {
600                     lint_extend(cx, expr, arglists[0]);
601                 } else if let Some(arglists) = method_chain_args(expr, &["unwrap", "as_ptr"]) {
602                     lint_cstring_as_ptr(cx, expr, &arglists[0][0], &arglists[1][0]);
603                 } else if let Some(arglists) = method_chain_args(expr, &["iter", "nth"]) {
604                     lint_iter_nth(cx, expr, arglists[0], false);
605                 } else if let Some(arglists) = method_chain_args(expr, &["iter_mut", "nth"]) {
606                     lint_iter_nth(cx, expr, arglists[0], true);
607                 } else if method_chain_args(expr, &["skip", "next"]).is_some() {
608                     lint_iter_skip_next(cx, expr);
609                 } else if let Some(arglists) = method_chain_args(expr, &["cloned", "collect"]) {
610                     lint_iter_cloned_collect(cx, expr, arglists[0]);
611                 }
612
613                 lint_or_fun_call(cx, expr, &method_call.name.as_str(), args);
614
615                 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
616                 if args.len() == 1 && method_call.name == "clone" {
617                     lint_clone_on_copy(cx, expr, &args[0], self_ty);
618                 }
619
620                 match self_ty.sty {
621                     ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
622                         for &(method, pos) in &PATTERN_METHODS {
623                             if method_call.name == method && args.len() > pos {
624                                 lint_single_char_pattern(cx, expr, &args[pos]);
625                             }
626                         }
627                     },
628                     _ => (),
629                 }
630             },
631             hir::ExprBinary(op, ref lhs, ref rhs) if op.node == hir::BiEq || op.node == hir::BiNe => {
632                 if !lint_chars_next(cx, expr, lhs, rhs, op.node == hir::BiEq) {
633                     lint_chars_next(cx, expr, rhs, lhs, op.node == hir::BiEq);
634                 }
635             },
636             _ => (),
637         }
638     }
639
640     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
641         if in_external_macro(cx, implitem.span) {
642             return;
643         }
644         let name = implitem.name;
645         let parent = cx.tcx.hir.get_parent(implitem.id);
646         let item = cx.tcx.hir.expect_item(parent);
647         if_let_chain! {[
648             let hir::ImplItemKind::Method(ref sig, id) = implitem.node,
649             let Some(first_arg_ty) = sig.decl.inputs.get(0),
650             let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next(),
651             let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node,
652         ], {
653             // check missing trait implementations
654             for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
655                 if name == method_name &&
656                    sig.decl.inputs.len() == n_args &&
657                    out_type.matches(&sig.decl.output) &&
658                    self_kind.matches(first_arg_ty, first_arg, self_ty, false, &sig.generics) {
659                     span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
660                         "defining a method called `{}` on this type; consider implementing \
661                          the `{}` trait or choosing a less ambiguous name", name, trait_name));
662                 }
663             }
664
665             // check conventions w.r.t. conversion method names and predicates
666             let def_id = cx.tcx.hir.local_def_id(item.id);
667             let ty = cx.tcx.type_of(def_id);
668             let is_copy = is_copy(cx, ty);
669             for &(ref conv, self_kinds) in &CONVENTIONS {
670                 if_let_chain! {[
671                     conv.check(&name.as_str()),
672                     !self_kinds.iter().any(|k| k.matches(first_arg_ty, first_arg, self_ty, is_copy, &sig.generics)),
673                 ], {
674                     let lint = if item.vis == hir::Visibility::Public {
675                         WRONG_PUB_SELF_CONVENTION
676                     } else {
677                         WRONG_SELF_CONVENTION
678                     };
679                     span_lint(cx,
680                               lint,
681                               first_arg.pat.span,
682                               &format!("methods called `{}` usually take {}; consider choosing a less \
683                                         ambiguous name",
684                                        conv,
685                                        &self_kinds.iter()
686                                                   .map(|k| k.description())
687                                                   .collect::<Vec<_>>()
688                                                   .join(" or ")));
689                 }}
690             }
691
692             let ret_ty = return_ty(cx, implitem.id);
693             if name == "new" &&
694                !ret_ty.walk().any(|t| same_tys(cx, t, ty)) {
695                 span_lint(cx,
696                           NEW_RET_NO_SELF,
697                           implitem.span,
698                           "methods called `new` usually return `Self`");
699             }
700         }}
701     }
702 }
703
704 /// Checks for the `OR_FUN_CALL` lint.
705 fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[hir::Expr]) {
706     /// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
707     fn check_unwrap_or_default(
708         cx: &LateContext,
709         name: &str,
710         fun: &hir::Expr,
711         self_expr: &hir::Expr,
712         arg: &hir::Expr,
713         or_has_args: bool,
714         span: Span,
715     ) -> bool {
716         if or_has_args {
717             return false;
718         }
719
720         if name == "unwrap_or" {
721             if let hir::ExprPath(ref qpath) = fun.node {
722                 let path = &*last_path_segment(qpath).name.as_str();
723
724                 if ["default", "new"].contains(&path) {
725                     let arg_ty = cx.tables.expr_ty(arg);
726                     let default_trait_id =
727                         if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
728                             default_trait_id
729                         } else {
730                             return false;
731                         };
732
733                     if implements_trait(cx, arg_ty, default_trait_id, &[]) {
734                         span_lint_and_sugg(
735                             cx,
736                             OR_FUN_CALL,
737                             span,
738                             &format!("use of `{}` followed by a call to `{}`", name, path),
739                             "try this",
740                             format!("{}.unwrap_or_default()", snippet(cx, self_expr.span, "_")),
741                         );
742                         return true;
743                     }
744                 }
745             }
746         }
747
748         false
749     }
750
751     /// Check for `*or(foo())`.
752     fn check_general_case(
753         cx: &LateContext,
754         name: &str,
755         fun_span: Span,
756         self_expr: &hir::Expr,
757         arg: &hir::Expr,
758         or_has_args: bool,
759         span: Span,
760     ) {
761         // don't lint for constant values
762         // FIXME: can we `expect` here instead of match?
763         let promotable = cx.tcx
764             .rvalue_promotable_to_static
765             .borrow()
766             .get(&arg.id)
767             .cloned()
768             .unwrap_or(true);
769         if promotable {
770             return;
771         }
772
773         // (path, fn_has_argument, methods, suffix)
774         let know_types: &[(&[_], _, &[_], _)] =
775             &[
776                 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
777                 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
778                 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
779                 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
780             ];
781
782         let self_ty = cx.tables.expr_ty(self_expr);
783
784         let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
785             know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
786         {
787             (fn_has_arguments, poss, suffix)
788         } else {
789             return;
790         };
791
792         if !poss.contains(&name) {
793             return;
794         }
795
796         let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
797             (true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
798             (false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
799             (false, true) => snippet(cx, fun_span, ".."),
800         };
801
802         span_lint_and_sugg(
803             cx,
804             OR_FUN_CALL,
805             span,
806             &format!("use of `{}` followed by a function call", name),
807             "try this",
808             format!("{}.{}_{}({})", snippet(cx, self_expr.span, "_"), name, suffix, sugg),
809         );
810     }
811
812     if args.len() == 2 {
813         match args[1].node {
814             hir::ExprCall(ref fun, ref or_args) => {
815                 let or_has_args = !or_args.is_empty();
816                 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
817                     check_general_case(cx, name, fun.span, &args[0], &args[1], or_has_args, expr.span);
818                 }
819             },
820             hir::ExprMethodCall(_, span, ref or_args) => {
821                 check_general_case(cx, name, span, &args[0], &args[1], !or_args.is_empty(), expr.span)
822             },
823             _ => {},
824         }
825     }
826 }
827
828 /// Checks for the `CLONE_ON_COPY` lint.
829 fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
830     let ty = cx.tables.expr_ty(expr);
831     if let ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) = arg_ty.sty {
832         if let ty::TyRef(..) = inner.sty {
833             span_lint_and_then(
834                 cx,
835                 CLONE_DOUBLE_REF,
836                 expr.span,
837                 "using `clone` on a double-reference; \
838                                 this will copy the reference instead of cloning the inner type",
839                 |db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
840                     db.span_suggestion(expr.span, "try dereferencing it", format!("({}).clone()", snip.deref()));
841                 },
842             );
843             return; // don't report clone_on_copy
844         }
845     }
846
847     if is_copy(cx, ty) {
848         span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
849             if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
850                 if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
851                     db.span_suggestion(expr.span, "try dereferencing it", format!("{}", snip.deref()));
852                 } else {
853                     db.span_suggestion(expr.span, "try removing the `clone` call", format!("{}", snip));
854                 }
855             }
856         });
857     }
858 }
859
860 fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
861     let arg = &args[1];
862     if let Some(arglists) = method_chain_args(arg, &["chars"]) {
863         let target = &arglists[0][0];
864         let (self_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(target));
865         let ref_str = if self_ty.sty == ty::TyStr {
866             ""
867         } else if match_type(cx, self_ty, &paths::STRING) {
868             "&"
869         } else {
870             return;
871         };
872
873         span_lint_and_sugg(
874             cx,
875             STRING_EXTEND_CHARS,
876             expr.span,
877             "calling `.extend(_.chars())`",
878             "try this",
879             format!(
880                 "{}.push_str({}{})",
881                 snippet(cx, args[0].span, "_"),
882                 ref_str,
883                 snippet(cx, target.span, "_")
884             ),
885         );
886     }
887 }
888
889 fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
890     let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&args[0]));
891     if match_type(cx, obj_ty, &paths::STRING) {
892         lint_string_extend(cx, expr, args);
893     }
894 }
895
896 fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
897     if_let_chain!{[
898         let hir::ExprCall(ref fun, ref args) = new.node,
899         args.len() == 1,
900         let hir::ExprPath(ref path) = fun.node,
901         let Def::Method(did) = cx.tables.qpath_def(path, fun.hir_id),
902         match_def_path(cx.tcx, did, &paths::CSTRING_NEW)
903     ], {
904         span_lint_and_then(cx, TEMPORARY_CSTRING_AS_PTR, expr.span,
905                            "you are getting the inner pointer of a temporary `CString`",
906                            |db| {
907                                db.note("that pointer will be invalid outside this expression");
908                                db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
909                            });
910     }}
911 }
912
913 fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
914     if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC) &&
915         derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
916     {
917         span_lint(
918             cx,
919             ITER_CLONED_COLLECT,
920             expr.span,
921             "called `cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
922                    more readable",
923         );
924     }
925 }
926
927 fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
928     let mut_str = if is_mut { "_mut" } else { "" };
929     let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
930         "slice"
931     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
932         "Vec"
933     } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
934         "VecDeque"
935     } else {
936         return; // caller is not a type that we want to lint
937     };
938
939     span_lint(
940         cx,
941         ITER_NTH,
942         expr.span,
943         &format!(
944             "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
945             mut_str,
946             caller_type
947         ),
948     );
949 }
950
951 fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
952     // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
953     // because they do not implement `IndexMut`
954     let expr_ty = cx.tables.expr_ty(&get_args[0]);
955     let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
956         "slice"
957     } else if match_type(cx, expr_ty, &paths::VEC) {
958         "Vec"
959     } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
960         "VecDeque"
961     } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
962         "HashMap"
963     } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
964         "BTreeMap"
965     } else {
966         return; // caller is not a type that we want to lint
967     };
968
969     let mut_str = if is_mut { "_mut" } else { "" };
970     let borrow_str = if is_mut { "&mut " } else { "&" };
971     span_lint_and_sugg(
972         cx,
973         GET_UNWRAP,
974         expr.span,
975         &format!(
976             "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
977             mut_str,
978             caller_type
979         ),
980         "try this",
981         format!(
982             "{}{}[{}]",
983             borrow_str,
984             snippet(cx, get_args[0].span, "_"),
985             snippet(cx, get_args[1].span, "_")
986         ),
987     );
988 }
989
990 fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
991     // lint if caller of skip is an Iterator
992     if match_trait_method(cx, expr, &paths::ITERATOR) {
993         span_lint(
994             cx,
995             ITER_SKIP_NEXT,
996             expr.span,
997             "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
998         );
999     }
1000 }
1001
1002 fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
1003     fn may_slice(cx: &LateContext, ty: Ty) -> bool {
1004         match ty.sty {
1005             ty::TySlice(_) => true,
1006             ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1007             ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
1008             ty::TyArray(_, size) => size < 32,
1009             ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => may_slice(cx, inner),
1010             _ => false,
1011         }
1012     }
1013
1014     if let hir::ExprMethodCall(ref path, _, ref args) = expr.node {
1015         if path.name == "iter" && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1016             sugg::Sugg::hir_opt(cx, &args[0]).map(|sugg| sugg.addr())
1017         } else {
1018             None
1019         }
1020     } else {
1021         match ty.sty {
1022             ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
1023             ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
1024             ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => {
1025                 if may_slice(cx, inner) {
1026                     sugg::Sugg::hir_opt(cx, expr)
1027                 } else {
1028                     None
1029                 }
1030             },
1031             _ => None,
1032         }
1033     }
1034 }
1035
1036 /// lint use of `unwrap()` for `Option`s and `Result`s
1037 fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1038     let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(&unwrap_args[0]));
1039
1040     let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1041         Some((OPTION_UNWRAP_USED, "an Option", "None"))
1042     } else if match_type(cx, obj_ty, &paths::RESULT) {
1043         Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1044     } else {
1045         None
1046     };
1047
1048     if let Some((lint, kind, none_value)) = mess {
1049         span_lint(
1050             cx,
1051             lint,
1052             expr.span,
1053             &format!(
1054                 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1055                             using expect() to provide a better panic \
1056                             message",
1057                 kind,
1058                 none_value
1059             ),
1060         );
1061     }
1062 }
1063
1064 /// lint use of `ok().expect()` for `Result`s
1065 fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1066     // lint if the caller of `ok()` is a `Result`
1067     if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1068         let result_type = cx.tables.expr_ty(&ok_args[0]);
1069         if let Some(error_type) = get_error_type(cx, result_type) {
1070             if has_debug_impl(error_type, cx) {
1071                 span_lint(
1072                     cx,
1073                     OK_EXPECT,
1074                     expr.span,
1075                     "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1076                 );
1077             }
1078         }
1079     }
1080 }
1081
1082 /// lint use of `map().unwrap_or()` for `Option`s
1083 fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1084     // lint if the caller of `map()` is an `Option`
1085     if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1086         // lint message
1087         let msg = "called `map(f).unwrap_or(a)` on an Option value. This can be done more directly by calling \
1088                    `map_or(a, f)` instead";
1089         // get snippets for args to map() and unwrap_or()
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() 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.ctxt == unwrap_args[1].span.ctxt;
1096         if same_span && !multiline {
1097             span_note_and_lint(
1098                 cx,
1099                 OPTION_MAP_UNWRAP_OR,
1100                 expr.span,
1101                 msg,
1102                 expr.span,
1103                 &format!(
1104                     "replace `map({0}).unwrap_or({1})` with `map_or({1}, {0})`",
1105                     map_snippet,
1106                     unwrap_snippet
1107                 ),
1108             );
1109         } else if same_span && multiline {
1110             span_lint(cx, OPTION_MAP_UNWRAP_OR, expr.span, msg);
1111         };
1112     }
1113 }
1114
1115 /// lint use of `map().unwrap_or_else()` for `Option`s
1116 fn lint_map_unwrap_or_else(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
1117     // lint if the caller of `map()` is an `Option`
1118     if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
1119         // lint message
1120         let msg = "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1121                    `map_or_else(g, f)` instead";
1122         // get snippets for args to map() and unwrap_or_else()
1123         let map_snippet = snippet(cx, map_args[1].span, "..");
1124         let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1125         // lint, with note if neither arg is > 1 line and both map() and
1126         // unwrap_or_else() have the same span
1127         let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1128         let same_span = map_args[1].span.ctxt == unwrap_args[1].span.ctxt;
1129         if same_span && !multiline {
1130             span_note_and_lint(
1131                 cx,
1132                 OPTION_MAP_UNWRAP_OR_ELSE,
1133                 expr.span,
1134                 msg,
1135                 expr.span,
1136                 &format!(
1137                     "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
1138                     map_snippet,
1139                     unwrap_snippet
1140                 ),
1141             );
1142         } else if same_span && multiline {
1143             span_lint(cx, OPTION_MAP_UNWRAP_OR_ELSE, expr.span, msg);
1144         };
1145     }
1146 }
1147
1148 /// lint use of `filter().next()` for `Iterators`
1149 fn lint_filter_next(cx: &LateContext, expr: &hir::Expr, filter_args: &[hir::Expr]) {
1150     // lint if caller of `.filter().next()` is an Iterator
1151     if match_trait_method(cx, expr, &paths::ITERATOR) {
1152         let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
1153                    `.find(p)` instead.";
1154         let filter_snippet = snippet(cx, filter_args[1].span, "..");
1155         if filter_snippet.lines().count() <= 1 {
1156             // add note if not multi-line
1157             span_note_and_lint(
1158                 cx,
1159                 FILTER_NEXT,
1160                 expr.span,
1161                 msg,
1162                 expr.span,
1163                 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
1164             );
1165         } else {
1166             span_lint(cx, FILTER_NEXT, expr.span, msg);
1167         }
1168     }
1169 }
1170
1171 /// lint use of `filter().map()` for `Iterators`
1172 fn lint_filter_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1173     // lint if caller of `.filter().map()` is an Iterator
1174     if match_trait_method(cx, expr, &paths::ITERATOR) {
1175         let msg = "called `filter(p).map(q)` on an `Iterator`. \
1176                    This is more succinctly expressed by calling `.filter_map(..)` instead.";
1177         span_lint(cx, FILTER_MAP, expr.span, msg);
1178     }
1179 }
1180
1181 /// lint use of `filter().map()` for `Iterators`
1182 fn lint_filter_map_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1183     // lint if caller of `.filter().map()` is an Iterator
1184     if match_trait_method(cx, expr, &paths::ITERATOR) {
1185         let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
1186                    This is more succinctly expressed by only calling `.filter_map(..)` instead.";
1187         span_lint(cx, FILTER_MAP, expr.span, msg);
1188     }
1189 }
1190
1191 /// lint use of `filter().flat_map()` for `Iterators`
1192 fn lint_filter_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1193     // lint if caller of `.filter().flat_map()` is an Iterator
1194     if match_trait_method(cx, expr, &paths::ITERATOR) {
1195         let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
1196                    This is more succinctly expressed by calling `.flat_map(..)` \
1197                    and filtering by returning an empty Iterator.";
1198         span_lint(cx, FILTER_MAP, expr.span, msg);
1199     }
1200 }
1201
1202 /// lint use of `filter_map().flat_map()` for `Iterators`
1203 fn lint_filter_map_flat_map(cx: &LateContext, expr: &hir::Expr, _filter_args: &[hir::Expr], _map_args: &[hir::Expr]) {
1204     // lint if caller of `.filter_map().flat_map()` is an Iterator
1205     if match_trait_method(cx, expr, &paths::ITERATOR) {
1206         let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
1207                    This is more succinctly expressed by calling `.flat_map(..)` \
1208                    and filtering by returning an empty Iterator.";
1209         span_lint(cx, FILTER_MAP, expr.span, msg);
1210     }
1211 }
1212
1213 /// lint searching an Iterator followed by `is_some()`
1214 fn lint_search_is_some(
1215     cx: &LateContext,
1216     expr: &hir::Expr,
1217     search_method: &str,
1218     search_args: &[hir::Expr],
1219     is_some_args: &[hir::Expr],
1220 ) {
1221     // lint if caller of search is an Iterator
1222     if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
1223         let msg = format!(
1224             "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
1225                            expressed by calling `any()`.",
1226             search_method
1227         );
1228         let search_snippet = snippet(cx, search_args[1].span, "..");
1229         if search_snippet.lines().count() <= 1 {
1230             // add note if not multi-line
1231             span_note_and_lint(
1232                 cx,
1233                 SEARCH_IS_SOME,
1234                 expr.span,
1235                 &msg,
1236                 expr.span,
1237                 &format!("replace `{0}({1}).is_some()` with `any({1})`", search_method, search_snippet),
1238             );
1239         } else {
1240             span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
1241         }
1242     }
1243 }
1244
1245 /// Checks for the `CHARS_NEXT_CMP` lint.
1246 fn lint_chars_next(cx: &LateContext, expr: &hir::Expr, chain: &hir::Expr, other: &hir::Expr, eq: bool) -> bool {
1247     if_let_chain! {[
1248         let Some(args) = method_chain_args(chain, &["chars", "next"]),
1249         let hir::ExprCall(ref fun, ref arg_char) = other.node,
1250         arg_char.len() == 1,
1251         let hir::ExprPath(ref qpath) = fun.node,
1252         let Some(segment) = single_segment_path(qpath),
1253         segment.name == "Some"
1254     ], {
1255         let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
1256
1257         if self_ty.sty != ty::TyStr {
1258             return false;
1259         }
1260
1261         span_lint_and_sugg(cx,
1262                            CHARS_NEXT_CMP,
1263                            expr.span,
1264                            "you should use the `starts_with` method",
1265                            "like this",
1266                            format!("{}{}.starts_with({})",
1267                                    if eq { "" } else { "!" },
1268                                    snippet(cx, args[0][0].span, "_"),
1269                                    snippet(cx, arg_char[0].span, "_")));
1270
1271         return true;
1272     }}
1273
1274     false
1275 }
1276
1277 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
1278 fn lint_single_char_pattern(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
1279     let parent_item = cx.tcx.hir.get_parent(arg.id);
1280     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1281     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1282     if let Ok(ConstVal::Str(r)) = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(arg) {
1283         if r.len() == 1 {
1284             let hint = snippet(cx, expr.span, "..").replace(&format!("\"{}\"", r), &format!("'{}'", r));
1285             span_lint_and_then(
1286                 cx,
1287                 SINGLE_CHAR_PATTERN,
1288                 arg.span,
1289                 "single-character string constant used as pattern",
1290                 |db| { db.span_suggestion(expr.span, "try using a char instead", hint); },
1291             );
1292         }
1293     }
1294 }
1295
1296 /// Given a `Result<T, E>` type, return its error type (`E`).
1297 fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
1298     if let ty::TyAdt(_, substs) = ty.sty {
1299         if match_type(cx, ty, &paths::RESULT) {
1300             substs.types().nth(1)
1301         } else {
1302             None
1303         }
1304     } else {
1305         None
1306     }
1307 }
1308
1309 /// This checks whether a given type is known to implement Debug.
1310 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
1311     match cx.tcx.lang_items.debug_trait() {
1312         Some(debug) => implements_trait(cx, ty, debug, &[]),
1313         None => false,
1314     }
1315 }
1316
1317 enum Convention {
1318     Eq(&'static str),
1319     StartsWith(&'static str),
1320 }
1321
1322 #[cfg_attr(rustfmt, rustfmt_skip)]
1323 const CONVENTIONS: [(Convention, &'static [SelfKind]); 6] = [
1324     (Convention::Eq("new"), &[SelfKind::No]),
1325     (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
1326     (Convention::StartsWith("from_"), &[SelfKind::No]),
1327     (Convention::StartsWith("into_"), &[SelfKind::Value]),
1328     (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
1329     (Convention::StartsWith("to_"), &[SelfKind::Ref]),
1330 ];
1331
1332 #[cfg_attr(rustfmt, rustfmt_skip)]
1333 const TRAIT_METHODS: [(&'static str, usize, SelfKind, OutType, &'static str); 30] = [
1334     ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
1335     ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
1336     ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
1337     ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
1338     ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
1339     ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
1340     ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
1341     ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
1342     ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
1343     ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
1344     ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
1345     ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
1346     ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
1347     ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
1348     ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
1349     ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
1350     ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
1351     ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
1352     ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
1353     ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
1354     ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
1355     ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
1356     ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
1357     ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
1358     ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
1359     ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
1360     ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
1361     ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
1362     ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
1363     ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
1364 ];
1365
1366 #[cfg_attr(rustfmt, rustfmt_skip)]
1367 const PATTERN_METHODS: [(&'static str, usize); 17] = [
1368     ("contains", 1),
1369     ("starts_with", 1),
1370     ("ends_with", 1),
1371     ("find", 1),
1372     ("rfind", 1),
1373     ("split", 1),
1374     ("rsplit", 1),
1375     ("split_terminator", 1),
1376     ("rsplit_terminator", 1),
1377     ("splitn", 2),
1378     ("rsplitn", 2),
1379     ("matches", 1),
1380     ("rmatches", 1),
1381     ("match_indices", 1),
1382     ("rmatch_indices", 1),
1383     ("trim_left_matches", 1),
1384     ("trim_right_matches", 1),
1385 ];
1386
1387
1388 #[derive(Clone, Copy, PartialEq, Debug)]
1389 enum SelfKind {
1390     Value,
1391     Ref,
1392     RefMut,
1393     No,
1394 }
1395
1396 impl SelfKind {
1397     fn matches(
1398         self,
1399         ty: &hir::Ty,
1400         arg: &hir::Arg,
1401         self_ty: &hir::Ty,
1402         allow_value_for_ref: bool,
1403         generics: &hir::Generics,
1404     ) -> bool {
1405         // Self types in the HIR are desugared to explicit self types. So it will
1406         // always be `self:
1407         // SomeType`,
1408         // where SomeType can be `Self` or an explicit impl self type (e.g. `Foo` if
1409         // the impl is on `Foo`)
1410         // Thus, we only need to test equality against the impl self type or if it is
1411         // an explicit
1412         // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
1413         // `Self`, `&mut Self`,
1414         // and `Box<Self>`, including the equivalent types with `Foo`.
1415
1416         let is_actually_self = |ty| is_self_ty(ty) || ty == self_ty;
1417         if is_self(arg) {
1418             match self {
1419                 SelfKind::Value => is_actually_self(ty),
1420                 SelfKind::Ref | SelfKind::RefMut => {
1421                     if allow_value_for_ref && is_actually_self(ty) {
1422                         return true;
1423                     }
1424                     match ty.node {
1425                         hir::TyRptr(_, ref mt_ty) => {
1426                             let mutability_match = if self == SelfKind::Ref {
1427                                 mt_ty.mutbl == hir::MutImmutable
1428                             } else {
1429                                 mt_ty.mutbl == hir::MutMutable
1430                             };
1431                             is_actually_self(&mt_ty.ty) && mutability_match
1432                         },
1433                         _ => false,
1434                     }
1435                 },
1436                 _ => false,
1437             }
1438         } else {
1439             match self {
1440                 SelfKind::Value => false,
1441                 SelfKind::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
1442                 SelfKind::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
1443                 SelfKind::No => true,
1444             }
1445         }
1446     }
1447
1448     fn description(&self) -> &'static str {
1449         match *self {
1450             SelfKind::Value => "self by value",
1451             SelfKind::Ref => "self by reference",
1452             SelfKind::RefMut => "self by mutable reference",
1453             SelfKind::No => "no self",
1454         }
1455     }
1456 }
1457
1458 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
1459     single_segment_ty(ty).map_or(false, |seg| {
1460         generics.ty_params.iter().any(|param| {
1461             param.name == seg.name &&
1462                 param.bounds.iter().any(|bound| {
1463                     if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
1464                         let path = &ptr.trait_ref.path;
1465                         match_path_old(path, name) &&
1466                             path.segments.last().map_or(false, |s| {
1467                                 if let hir::PathParameters::AngleBracketedParameters(ref data) = s.parameters {
1468                                     data.types.len() == 1 &&
1469                                         (is_self_ty(&data.types[0]) || is_ty(&*data.types[0], self_ty))
1470                                 } else {
1471                                     false
1472                                 }
1473                             })
1474                     } else {
1475                         false
1476                     }
1477                 })
1478         })
1479     })
1480 }
1481
1482 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
1483     match (&ty.node, &self_ty.node) {
1484         (&hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
1485          &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path))) => {
1486             ty_path.segments.iter().map(|seg| seg.name).eq(
1487                 self_ty_path.segments.iter().map(|seg| seg.name),
1488             )
1489         },
1490         _ => false,
1491     }
1492 }
1493
1494 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
1495     if let hir::TyPath(ref path) = ty.node {
1496         single_segment_path(path)
1497     } else {
1498         None
1499     }
1500 }
1501
1502 impl Convention {
1503     fn check(&self, other: &str) -> bool {
1504         match *self {
1505             Convention::Eq(this) => this == other,
1506             Convention::StartsWith(this) => other.starts_with(this) && this != other,
1507         }
1508     }
1509 }
1510
1511 impl fmt::Display for Convention {
1512     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1513         match *self {
1514             Convention::Eq(this) => this.fmt(f),
1515             Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
1516         }
1517     }
1518 }
1519
1520 #[derive(Clone, Copy)]
1521 enum OutType {
1522     Unit,
1523     Bool,
1524     Any,
1525     Ref,
1526 }
1527
1528 impl OutType {
1529     fn matches(&self, ty: &hir::FunctionRetTy) -> bool {
1530         match (self, ty) {
1531             (&OutType::Unit, &hir::DefaultReturn(_)) => true,
1532             (&OutType::Unit, &hir::Return(ref ty)) if ty.node == hir::TyTup(vec![].into()) => true,
1533             (&OutType::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
1534             (&OutType::Any, &hir::Return(ref ty)) if ty.node != hir::TyTup(vec![].into()) => true,
1535             (&OutType::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyRptr(_, _)),
1536             _ => false,
1537         }
1538     }
1539 }
1540
1541 fn is_bool(ty: &hir::Ty) -> bool {
1542     if let hir::TyPath(ref p) = ty.node {
1543         match_path(p, &["bool"])
1544     } else {
1545         false
1546     }
1547 }