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