]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types.rs
Fix ICE for issues 2767, 2499, 1782
[rust.git] / clippy_lints / src / types.rs
1 use reexport::*;
2 use rustc::hir;
3 use rustc::hir::*;
4 use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
5 use rustc::lint::*;
6 use rustc::ty::{self, Ty, TyCtxt, TypeckTables};
7 use rustc::ty::layout::LayoutOf;
8 use rustc_typeck::hir_ty_to_ty;
9 use std::cmp::Ordering;
10 use std::collections::BTreeMap;
11 use std::borrow::Cow;
12 use syntax::ast::{FloatTy, IntTy, UintTy};
13 use syntax::codemap::Span;
14 use syntax::errors::DiagnosticBuilder;
15 use utils::{comparisons, differing_macro_contexts, higher, in_constant, in_external_macro, in_macro, last_path_segment, match_def_path, match_path,
16             match_type, multispan_sugg, opt_def_id, same_tys, snippet, snippet_opt, span_help_and_lint, span_lint,
17             span_lint_and_sugg, span_lint_and_then, clip, unsext, sext, int_bits};
18 use utils::paths;
19 use consts::{constant, Constant};
20
21 /// Handles all the linting of funky types
22 #[allow(missing_copy_implementations)]
23 pub struct TypePass;
24
25 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
26 ///
27 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
28 /// the heap. So if you `Box` it, you just add another level of indirection
29 /// without any benefit whatsoever.
30 ///
31 /// **Known problems:** None.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// struct X {
36 ///     values: Box<Vec<Foo>>,
37 /// }
38 /// ```
39 ///
40 /// Better:
41 ///
42 /// ```rust
43 /// struct X {
44 ///     values: Vec<Foo>,
45 /// }
46 /// ```
47 declare_clippy_lint! {
48     pub BOX_VEC,
49     perf,
50     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
51 }
52
53 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
54 /// definitions
55 ///
56 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
57 /// represents an optional optional value which is logically the same thing as an optional
58 /// value but has an unneeded extra level of wrapping.
59 ///
60 /// **Known problems:** None.
61 ///
62 /// **Example**
63 /// ```rust
64 /// fn x() -> Option<Option<u32>> {
65 ///     None
66 /// }
67 declare_clippy_lint! {
68     pub OPTION_OPTION,
69     complexity,
70     "usage of `Option<Option<T>>`"
71 }
72
73 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
74 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
75 ///
76 /// **Why is this bad?** Gankro says:
77 ///
78 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
79 /// pointers and indirection.
80 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
81 /// `RingBuf`, while
82 /// > "only" amortized for push/pop, should be faster in the general case for
83 /// almost every possible
84 /// > workload, and isn't even amortized at all if you can predict the capacity
85 /// you need.
86 /// >
87 /// > `LinkedList`s are only really good if you're doing a lot of merging or
88 /// splitting of lists.
89 /// > This is because they can just mangle some pointers instead of actually
90 /// copying the data. Even
91 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
92 /// can still be better
93 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
94 ///
95 /// **Known problems:** False positives – the instances where using a
96 /// `LinkedList` makes sense are few and far between, but they can still happen.
97 ///
98 /// **Example:**
99 /// ```rust
100 /// let x = LinkedList::new();
101 /// ```
102 declare_clippy_lint! {
103     pub LINKEDLIST,
104     pedantic,
105     "usage of LinkedList, usually a vector is faster, or a more specialized data \
106      structure like a VecDeque"
107 }
108
109 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
110 ///
111 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
112 /// general.
113 ///
114 /// **Known problems:** None.
115 ///
116 /// **Example:**
117 /// ```rust
118 /// fn foo(bar: &Box<T>) { ... }
119 /// ```
120 ///
121 /// Better:
122 ///
123 /// ```rust
124 /// fn foo(bar: &T) { ... }
125 /// ```
126 declare_clippy_lint! {
127     pub BORROWED_BOX,
128     complexity,
129     "a borrow of a boxed type"
130 }
131
132 impl LintPass for TypePass {
133     fn get_lints(&self) -> LintArray {
134         lint_array!(BOX_VEC, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
135     }
136 }
137
138 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
139     fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Body, _: Span, id: NodeId) {
140         // skip trait implementations, see #605
141         if let Some(map::NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(id)) {
142             if let ItemImpl(_, _, _, _, Some(..), _, _) = item.node {
143                 return;
144             }
145         }
146
147         check_fn_decl(cx, decl);
148     }
149
150     fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
151         check_ty(cx, &field.ty, false);
152     }
153
154     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
155         match item.node {
156             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
157             TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
158             _ => (),
159         }
160     }
161
162     fn check_local(&mut self, cx: &LateContext, local: &Local) {
163         if let Some(ref ty) = local.ty {
164             check_ty(cx, ty, true);
165         }
166     }
167 }
168
169 fn check_fn_decl(cx: &LateContext, decl: &FnDecl) {
170     for input in &decl.inputs {
171         check_ty(cx, input, false);
172     }
173
174     if let FunctionRetTy::Return(ref ty) = decl.output {
175         check_ty(cx, ty, false);
176     }
177 }
178
179 /// Check if `qpath` has last segment with type parameter matching `path`
180 fn match_type_parameter(cx: &LateContext, qpath: &QPath, path: &[&str]) -> bool {
181     let last = last_path_segment(qpath);
182     if_chain! {
183         if let Some(ref params) = last.parameters;
184         if !params.parenthesized;
185         if let Some(ty) = params.types.get(0);
186         if let TyPath(ref qpath) = ty.node;
187         if let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir.node_to_hir_id(ty.id)));
188         if match_def_path(cx.tcx, did, path);
189         then {
190             return true;
191         }
192     }
193     false
194 }
195
196 /// Recursively check for `TypePass` lints in the given type. Stop at the first
197 /// lint found.
198 ///
199 /// The parameter `is_local` distinguishes the context of the type; types from
200 /// local bindings should only be checked for the `BORROWED_BOX` lint.
201 fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
202     if in_macro(ast_ty.span) {
203         return;
204     }
205     match ast_ty.node {
206         TyPath(ref qpath) if !is_local => {
207             let hir_id = cx.tcx.hir.node_to_hir_id(ast_ty.id);
208             let def = cx.tables.qpath_def(qpath, hir_id);
209             if let Some(def_id) = opt_def_id(def) {
210                 if Some(def_id) == cx.tcx.lang_items().owned_box() {
211                     if match_type_parameter(cx, qpath, &paths::VEC) {
212                         span_help_and_lint(
213                             cx,
214                             BOX_VEC,
215                             ast_ty.span,
216                             "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
217                             "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
218                         );
219                         return; // don't recurse into the type
220                     }
221                 } else if match_def_path(cx.tcx, def_id, &paths::OPTION) {
222                     if match_type_parameter(cx, qpath, &paths::OPTION) {
223                         span_lint(
224                             cx,
225                             OPTION_OPTION,
226                             ast_ty.span,
227                             "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
228                             enum if you need to distinguish all 3 cases",
229                         );
230                         return; // don't recurse into the type
231                     }
232                 } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
233                     span_help_and_lint(
234                         cx,
235                         LINKEDLIST,
236                         ast_ty.span,
237                         "I see you're using a LinkedList! Perhaps you meant some other data structure?",
238                         "a VecDeque might work",
239                     );
240                     return; // don't recurse into the type
241                 }
242             }
243             match *qpath {
244                 QPath::Resolved(Some(ref ty), ref p) => {
245                     check_ty(cx, ty, is_local);
246                     for ty in p.segments.iter().flat_map(|seg| {
247                         seg.parameters
248                             .as_ref()
249                             .map_or_else(|| [].iter(), |params| params.types.iter())
250                     }) {
251                         check_ty(cx, ty, is_local);
252                     }
253                 },
254                 QPath::Resolved(None, ref p) => for ty in p.segments.iter().flat_map(|seg| {
255                     seg.parameters
256                         .as_ref()
257                         .map_or_else(|| [].iter(), |params| params.types.iter())
258                 }) {
259                     check_ty(cx, ty, is_local);
260                 },
261                 QPath::TypeRelative(ref ty, ref seg) => {
262                     check_ty(cx, ty, is_local);
263                     if let Some(ref params) = seg.parameters {
264                         for ty in params.types.iter() {
265                             check_ty(cx, ty, is_local);
266                         }
267                     }
268                 },
269             }
270         },
271         TyRptr(ref lt, ref mut_ty) => check_ty_rptr(cx, ast_ty, is_local, lt, mut_ty),
272         // recurse
273         TySlice(ref ty) | TyArray(ref ty, _) | TyPtr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
274         TyTup(ref tys) => for ty in tys {
275             check_ty(cx, ty, is_local);
276         },
277         _ => {},
278     }
279 }
280
281 fn check_ty_rptr(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool, lt: &Lifetime, mut_ty: &MutTy) {
282     match mut_ty.ty.node {
283         TyPath(ref qpath) => {
284             let hir_id = cx.tcx.hir.node_to_hir_id(mut_ty.ty.id);
285             let def = cx.tables.qpath_def(qpath, hir_id);
286             if_chain! {
287                 if let Some(def_id) = opt_def_id(def);
288                 if Some(def_id) == cx.tcx.lang_items().owned_box();
289                 if let QPath::Resolved(None, ref path) = *qpath;
290                 if let [ref bx] = *path.segments;
291                 if let Some(ref params) = bx.parameters;
292                 if !params.parenthesized;
293                 if let [ref inner] = *params.types;
294                 then {
295                     if is_any_trait(inner) {
296                         // Ignore `Box<Any>` types, see #1884 for details.
297                         return;
298                     }
299
300                     let ltopt = if lt.is_elided() {
301                         "".to_owned()
302                     } else {
303                         format!("{} ", lt.name.name().as_str())
304                     };
305                     let mutopt = if mut_ty.mutbl == Mutability::MutMutable {
306                         "mut "
307                     } else {
308                         ""
309                     };
310                     span_lint_and_sugg(cx,
311                         BORROWED_BOX,
312                         ast_ty.span,
313                         "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
314                         "try",
315                         format!("&{}{}{}", ltopt, mutopt, &snippet(cx, inner.span, ".."))
316                     );
317                     return; // don't recurse into the type
318                 }
319             };
320             check_ty(cx, &mut_ty.ty, is_local);
321         },
322         _ => check_ty(cx, &mut_ty.ty, is_local),
323     }
324 }
325
326 // Returns true if given type is `Any` trait.
327 fn is_any_trait(t: &hir::Ty) -> bool {
328     if_chain! {
329         if let TyTraitObject(ref traits, _) = t.node;
330         if traits.len() >= 1;
331         // Only Send/Sync can be used as additional traits, so it is enough to
332         // check only the first trait.
333         if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
334         then {
335             return true;
336         }
337     }
338
339     false
340 }
341
342 #[allow(missing_copy_implementations)]
343 pub struct LetPass;
344
345 /// **What it does:** Checks for binding a unit value.
346 ///
347 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
348 /// binding one is kind of pointless.
349 ///
350 /// **Known problems:** None.
351 ///
352 /// **Example:**
353 /// ```rust
354 /// let x = { 1; };
355 /// ```
356 declare_clippy_lint! {
357     pub LET_UNIT_VALUE,
358     style,
359     "creating a let binding to a value of unit type, which usually can't be used afterwards"
360 }
361
362 fn check_let_unit(cx: &LateContext, decl: &Decl) {
363     if let DeclLocal(ref local) = decl.node {
364         if is_unit(cx.tables.pat_ty(&local.pat)) {
365             if in_external_macro(cx, decl.span) || in_macro(local.pat.span) {
366                 return;
367             }
368             if higher::is_from_for_desugar(decl) {
369                 return;
370             }
371             span_lint(
372                 cx,
373                 LET_UNIT_VALUE,
374                 decl.span,
375                 &format!(
376                     "this let-binding has unit value. Consider omitting `let {} =`",
377                     snippet(cx, local.pat.span, "..")
378                 ),
379             );
380         }
381     }
382 }
383
384 impl LintPass for LetPass {
385     fn get_lints(&self) -> LintArray {
386         lint_array!(LET_UNIT_VALUE)
387     }
388 }
389
390 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
391     fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
392         check_let_unit(cx, decl)
393     }
394 }
395
396 /// **What it does:** Checks for comparisons to unit.
397 ///
398 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
399 /// clumsily written constant. Mostly this happens when someone accidentally
400 /// adds semicolons at the end of the operands.
401 ///
402 /// **Known problems:** None.
403 ///
404 /// **Example:**
405 /// ```rust
406 /// if { foo(); } == { bar(); } { baz(); }
407 /// ```
408 /// is equal to
409 /// ```rust
410 /// { foo(); bar(); baz(); }
411 /// ```
412 declare_clippy_lint! {
413     pub UNIT_CMP,
414     correctness,
415     "comparing unit values"
416 }
417
418 #[allow(missing_copy_implementations)]
419 pub struct UnitCmp;
420
421 impl LintPass for UnitCmp {
422     fn get_lints(&self) -> LintArray {
423         lint_array!(UNIT_CMP)
424     }
425 }
426
427 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
428     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
429         if in_macro(expr.span) {
430             return;
431         }
432         if let ExprBinary(ref cmp, ref left, _) = expr.node {
433             let op = cmp.node;
434             if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
435                 let result = match op {
436                     BiEq | BiLe | BiGe => "true",
437                     _ => "false",
438                 };
439                 span_lint(
440                     cx,
441                     UNIT_CMP,
442                     expr.span,
443                     &format!(
444                         "{}-comparison of unit values detected. This will always be {}",
445                         op.as_str(),
446                         result
447                     ),
448                 );
449             }
450         }
451     }
452 }
453
454 /// **What it does:** Checks for passing a unit value as an argument to a function without using a unit literal (`()`).
455 ///
456 /// **Why is this bad?** This is likely the result of an accidental semicolon.
457 ///
458 /// **Known problems:** None.
459 ///
460 /// **Example:**
461 /// ```rust
462 /// foo({
463 ///   let a = bar();
464 ///   baz(a);
465 /// })
466 /// ```
467 declare_clippy_lint! {
468     pub UNIT_ARG,
469     complexity,
470     "passing unit to a function"
471 }
472
473 pub struct UnitArg;
474
475 impl LintPass for UnitArg {
476     fn get_lints(&self) -> LintArray {
477         lint_array!(UNIT_ARG)
478     }
479 }
480
481 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
482     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
483         if in_macro(expr.span) {
484             return;
485         }
486         match expr.node {
487             ExprCall(_, ref args) | ExprMethodCall(_, _, ref args) => {
488                 for arg in args {
489                     if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
490                         let map = &cx.tcx.hir;
491                         // apparently stuff in the desugaring of `?` can trigger this
492                         // so check for that here
493                         // only the calls to `Try::from_error` is marked as desugared,
494                         // so we need to check both the current Expr and its parent.
495                         if !is_questionmark_desugar_marked_call(expr) {
496                             if_chain!{
497                                 let opt_parent_node = map.find(map.get_parent_node(expr.id));
498                                 if let Some(hir::map::NodeExpr(parent_expr)) = opt_parent_node;
499                                 if is_questionmark_desugar_marked_call(parent_expr);
500                                 then {}
501                                 else {
502                                     // `expr` and `parent_expr` where _both_ not from
503                                     // desugaring `?`, so lint
504                                     span_lint_and_sugg(
505                                         cx,
506                                         UNIT_ARG,
507                                         arg.span,
508                                         "passing a unit value to a function",
509                                         "if you intended to pass a unit value, use a unit literal instead",
510                                         "()".to_string(),
511                                     );
512                                 }
513                             }
514                         }
515                     }
516                 }
517             },
518             _ => (),
519         }
520     }
521 }
522
523 fn is_questionmark_desugar_marked_call(expr: &Expr) -> bool {
524     use syntax_pos::hygiene::CompilerDesugaringKind;
525     if let ExprCall(ref callee, _) = expr.node {
526         callee.span.is_compiler_desugaring(CompilerDesugaringKind::QuestionMark)
527     } else {
528         false
529     }
530 }
531
532 fn is_unit(ty: Ty) -> bool {
533     match ty.sty {
534         ty::TyTuple(slice) if slice.is_empty() => true,
535         _ => false,
536     }
537 }
538
539 fn is_unit_literal(expr: &Expr) -> bool {
540     match expr.node {
541         ExprTup(ref slice) if slice.is_empty() => true,
542         _ => false,
543     }
544 }
545
546 pub struct CastPass;
547
548 /// **What it does:** Checks for casts from any numerical to a float type where
549 /// the receiving type cannot store all values from the original type without
550 /// rounding errors. This possible rounding is to be expected, so this lint is
551 /// `Allow` by default.
552 ///
553 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
554 /// or any 64-bit integer to `f64`.
555 ///
556 /// **Why is this bad?** It's not bad at all. But in some applications it can be
557 /// helpful to know where precision loss can take place. This lint can help find
558 /// those places in the code.
559 ///
560 /// **Known problems:** None.
561 ///
562 /// **Example:**
563 /// ```rust
564 /// let x = u64::MAX; x as f64
565 /// ```
566 declare_clippy_lint! {
567     pub CAST_PRECISION_LOSS,
568     pedantic,
569     "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
570 }
571
572 /// **What it does:** Checks for casts from a signed to an unsigned numerical
573 /// type. In this case, negative values wrap around to large positive values,
574 /// which can be quite surprising in practice. However, as the cast works as
575 /// defined, this lint is `Allow` by default.
576 ///
577 /// **Why is this bad?** Possibly surprising results. You can activate this lint
578 /// as a one-time check to see where numerical wrapping can arise.
579 ///
580 /// **Known problems:** None.
581 ///
582 /// **Example:**
583 /// ```rust
584 /// let y: i8 = -1;
585 /// y as u128  // will return 18446744073709551615
586 /// ```
587 declare_clippy_lint! {
588     pub CAST_SIGN_LOSS,
589     pedantic,
590     "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
591 }
592
593 /// **What it does:** Checks for on casts between numerical types that may
594 /// truncate large values. This is expected behavior, so the cast is `Allow` by
595 /// default.
596 ///
597 /// **Why is this bad?** In some problem domains, it is good practice to avoid
598 /// truncation. This lint can be activated to help assess where additional
599 /// checks could be beneficial.
600 ///
601 /// **Known problems:** None.
602 ///
603 /// **Example:**
604 /// ```rust
605 /// fn as_u8(x: u64) -> u8 { x as u8 }
606 /// ```
607 declare_clippy_lint! {
608     pub CAST_POSSIBLE_TRUNCATION,
609     pedantic,
610     "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, \
611      or `x as i32` where `x: f32`"
612 }
613
614 /// **What it does:** Checks for casts from an unsigned type to a signed type of
615 /// the same size. Performing such a cast is a 'no-op' for the compiler,
616 /// i.e. nothing is changed at the bit level, and the binary representation of
617 /// the value is reinterpreted. This can cause wrapping if the value is too big
618 /// for the target signed type. However, the cast works as defined, so this lint
619 /// is `Allow` by default.
620 ///
621 /// **Why is this bad?** While such a cast is not bad in itself, the results can
622 /// be surprising when this is not the intended behavior, as demonstrated by the
623 /// example below.
624 ///
625 /// **Known problems:** None.
626 ///
627 /// **Example:**
628 /// ```rust
629 /// u32::MAX as i32  // will yield a value of `-1`
630 /// ```
631 declare_clippy_lint! {
632     pub CAST_POSSIBLE_WRAP,
633     pedantic,
634     "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` \
635      and `x > i32::MAX`"
636 }
637
638 /// **What it does:** Checks for on casts between numerical types that may
639 /// be replaced by safe conversion functions.
640 ///
641 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
642 /// conversions, including silently lossy conversions. Conversion functions such
643 /// as `i32::from` will only perform lossless conversions. Using the conversion
644 /// functions prevents conversions from turning into silent lossy conversions if
645 /// the types of the input expressions ever change, and make it easier for
646 /// people reading the code to know that the conversion is lossless.
647 ///
648 /// **Known problems:** None.
649 ///
650 /// **Example:**
651 /// ```rust
652 /// fn as_u64(x: u8) -> u64 { x as u64 }
653 /// ```
654 ///
655 /// Using `::from` would look like this:
656 ///
657 /// ```rust
658 /// fn as_u64(x: u8) -> u64 { u64::from(x) }
659 /// ```
660 declare_clippy_lint! {
661     pub CAST_LOSSLESS,
662     complexity,
663     "casts using `as` that are known to be lossless, e.g. `x as u64` where `x: u8`"
664 }
665
666 /// **What it does:** Checks for casts to the same type.
667 ///
668 /// **Why is this bad?** It's just unnecessary.
669 ///
670 /// **Known problems:** None.
671 ///
672 /// **Example:**
673 /// ```rust
674 /// let _ = 2i32 as i32
675 /// ```
676 declare_clippy_lint! {
677     pub UNNECESSARY_CAST,
678     complexity,
679     "cast to the same type, e.g. `x as i32` where `x: i32`"
680 }
681
682 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
683 /// more-strictly-aligned pointer
684 ///
685 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
686 /// behavior.
687 ///
688 /// **Known problems:** None.
689 ///
690 /// **Example:**
691 /// ```rust
692 /// let _ = (&1u8 as *const u8) as *const u16;
693 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
694 /// ```
695 declare_clippy_lint! {
696     pub CAST_PTR_ALIGNMENT,
697     correctness,
698     "cast from a pointer to a more-strictly-aligned pointer"
699 }
700
701 /// Returns the size in bits of an integral type.
702 /// Will return 0 if the type is not an int or uint variant
703 fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
704     match typ.sty {
705         ty::TyInt(i) => match i {
706             IntTy::Isize => tcx.data_layout.pointer_size.bits(),
707             IntTy::I8 => 8,
708             IntTy::I16 => 16,
709             IntTy::I32 => 32,
710             IntTy::I64 => 64,
711             IntTy::I128 => 128,
712         },
713         ty::TyUint(i) => match i {
714             UintTy::Usize => tcx.data_layout.pointer_size.bits(),
715             UintTy::U8 => 8,
716             UintTy::U16 => 16,
717             UintTy::U32 => 32,
718             UintTy::U64 => 64,
719             UintTy::U128 => 128,
720         },
721         _ => 0,
722     }
723 }
724
725 fn is_isize_or_usize(typ: Ty) -> bool {
726     match typ.sty {
727         ty::TyInt(IntTy::Isize) | ty::TyUint(UintTy::Usize) => true,
728         _ => false,
729     }
730 }
731
732 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to_f64: bool) {
733     let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
734     let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
735     let arch_dependent_str = "on targets with 64-bit wide pointers ";
736     let from_nbits_str = if arch_dependent {
737         "64".to_owned()
738     } else if is_isize_or_usize(cast_from) {
739         "32 or 64".to_owned()
740     } else {
741         int_ty_to_nbits(cast_from, cx.tcx).to_string()
742     };
743     span_lint(
744         cx,
745         CAST_PRECISION_LOSS,
746         expr.span,
747         &format!(
748             "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
749              is only {4} bits wide)",
750             cast_from,
751             if cast_to_f64 { "f64" } else { "f32" },
752             if arch_dependent {
753                 arch_dependent_str
754             } else {
755                 ""
756             },
757             from_nbits_str,
758             mantissa_nbits
759         ),
760     );
761 }
762
763 fn should_strip_parens(op: &Expr, snip: &str) -> bool {
764     if let ExprBinary(_, _, _) = op.node {
765         if snip.starts_with('(') && snip.ends_with(')') {
766             return true;
767         }
768     }
769     false
770 }
771
772 fn span_lossless_lint(cx: &LateContext, expr: &Expr, op: &Expr, cast_from: Ty, cast_to: Ty) {
773     // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
774     if in_constant(cx, expr.id) { return }
775     // The suggestion is to use a function call, so if the original expression
776     // has parens on the outside, they are no longer needed.
777     let opt = snippet_opt(cx, op.span);
778     let sugg = if let Some(ref snip) = opt {
779         if should_strip_parens(op, snip) {
780             &snip[1..snip.len() - 1]
781         } else {
782             snip.as_str()
783         }
784     } else {
785         ".."
786     };
787
788     span_lint_and_sugg(
789         cx,
790         CAST_LOSSLESS,
791         expr.span,
792         &format!("casting {} to {} may become silently lossy if types change", cast_from, cast_to),
793         "try",
794         format!("{}::from({})", cast_to, sugg),
795     );
796 }
797
798 enum ArchSuffix {
799     _32,
800     _64,
801     None,
802 }
803
804 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to: Ty) {
805     let arch_64_suffix = " on targets with 64-bit wide pointers";
806     let arch_32_suffix = " on targets with 32-bit wide pointers";
807     let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
808     let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
809     let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
810     let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
811         match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
812             (true, true) | (false, false) => (
813                 to_nbits < from_nbits,
814                 ArchSuffix::None,
815                 to_nbits == from_nbits && cast_unsigned_to_signed,
816                 ArchSuffix::None,
817             ),
818             (true, false) => (
819                 to_nbits <= 32,
820                 if to_nbits == 32 {
821                     ArchSuffix::_64
822                 } else {
823                     ArchSuffix::None
824                 },
825                 to_nbits <= 32 && cast_unsigned_to_signed,
826                 ArchSuffix::_32,
827             ),
828             (false, true) => (
829                 from_nbits == 64,
830                 ArchSuffix::_32,
831                 cast_unsigned_to_signed,
832                 if from_nbits == 64 {
833                     ArchSuffix::_64
834                 } else {
835                     ArchSuffix::_32
836                 },
837             ),
838         };
839     if span_truncation {
840         span_lint(
841             cx,
842             CAST_POSSIBLE_TRUNCATION,
843             expr.span,
844             &format!(
845                 "casting {} to {} may truncate the value{}",
846                 cast_from,
847                 cast_to,
848                 match suffix_truncation {
849                     ArchSuffix::_32 => arch_32_suffix,
850                     ArchSuffix::_64 => arch_64_suffix,
851                     ArchSuffix::None => "",
852                 }
853             ),
854         );
855     }
856     if span_wrap {
857         span_lint(
858             cx,
859             CAST_POSSIBLE_WRAP,
860             expr.span,
861             &format!(
862                 "casting {} to {} may wrap around the value{}",
863                 cast_from,
864                 cast_to,
865                 match suffix_wrap {
866                     ArchSuffix::_32 => arch_32_suffix,
867                     ArchSuffix::_64 => arch_64_suffix,
868                     ArchSuffix::None => "",
869                 }
870             ),
871         );
872     }
873 }
874
875 fn check_lossless(cx: &LateContext, expr: &Expr, op: &Expr, cast_from: Ty, cast_to: Ty) {
876     let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
877     let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
878     let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
879     if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
880     {
881         span_lossless_lint(cx, expr, op, cast_from, cast_to);
882     }
883 }
884
885 impl LintPass for CastPass {
886     fn get_lints(&self) -> LintArray {
887         lint_array!(
888             CAST_PRECISION_LOSS,
889             CAST_SIGN_LOSS,
890             CAST_POSSIBLE_TRUNCATION,
891             CAST_POSSIBLE_WRAP,
892             CAST_LOSSLESS,
893             UNNECESSARY_CAST,
894             CAST_PTR_ALIGNMENT
895         )
896     }
897 }
898
899 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
900     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
901         if let ExprCast(ref ex, _) = expr.node {
902             let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
903             if let ExprLit(ref lit) = ex.node {
904                 use syntax::ast::{LitIntType, LitKind};
905                 match lit.node {
906                     LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
907                     _ => if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
908                         span_lint(
909                             cx,
910                             UNNECESSARY_CAST,
911                             expr.span,
912                             &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
913                         );
914                     },
915                 }
916             }
917             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
918                 match (cast_from.is_integral(), cast_to.is_integral()) {
919                     (true, false) => {
920                         let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
921                         let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
922                             32
923                         } else {
924                             64
925                         };
926                         if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
927                             span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
928                         }
929                         if from_nbits < to_nbits {
930                             span_lossless_lint(cx, expr, ex, cast_from, cast_to);
931                         }
932                     },
933                     (false, true) => {
934                         span_lint(
935                             cx,
936                             CAST_POSSIBLE_TRUNCATION,
937                             expr.span,
938                             &format!("casting {} to {} may truncate the value", cast_from, cast_to),
939                         );
940                         if !cast_to.is_signed() {
941                             span_lint(
942                                 cx,
943                                 CAST_SIGN_LOSS,
944                                 expr.span,
945                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
946                             );
947                         }
948                     },
949                     (true, true) => {
950                         if cast_from.is_signed() && !cast_to.is_signed() {
951                             span_lint(
952                                 cx,
953                                 CAST_SIGN_LOSS,
954                                 expr.span,
955                                 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
956                             );
957                         }
958                         check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
959                         check_lossless(cx, expr, ex, cast_from, cast_to);
960                     },
961                     (false, false) => {
962                         if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty)
963                         {
964                             span_lint(
965                                 cx,
966                                 CAST_POSSIBLE_TRUNCATION,
967                                 expr.span,
968                                 "casting f64 to f32 may truncate the value",
969                             );
970                         }
971                         if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty)
972                         {
973                             span_lossless_lint(cx, expr, ex, cast_from, cast_to);
974                         }
975                     },
976                 }
977             }
978             if_chain!{
979                 if let ty::TyRawPtr(from_ptr_ty) = &cast_from.sty;
980                 if let ty::TyRawPtr(to_ptr_ty) = &cast_to.sty;
981                 if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi());
982                 if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi());
983                 if from_align < to_align;
984                 // with c_void, we inherently need to trust the user
985                 if ! (
986                     match_type(cx, from_ptr_ty.ty, &paths::C_VOID)
987                     || match_type(cx, from_ptr_ty.ty, &paths::C_VOID_LIBC)
988                 );
989                 then {
990                     span_lint(
991                         cx,
992                         CAST_PTR_ALIGNMENT,
993                         expr.span,
994                         &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
995                     );
996                 }
997             }
998         }
999     }
1000 }
1001
1002 /// **What it does:** Checks for types used in structs, parameters and `let`
1003 /// declarations above a certain complexity threshold.
1004 ///
1005 /// **Why is this bad?** Too complex types make the code less readable. Consider
1006 /// using a `type` definition to simplify them.
1007 ///
1008 /// **Known problems:** None.
1009 ///
1010 /// **Example:**
1011 /// ```rust
1012 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
1013 /// ```
1014 declare_clippy_lint! {
1015     pub TYPE_COMPLEXITY,
1016     complexity,
1017     "usage of very complex types that might be better factored into `type` definitions"
1018 }
1019
1020 #[allow(missing_copy_implementations)]
1021 pub struct TypeComplexityPass {
1022     threshold: u64,
1023 }
1024
1025 impl TypeComplexityPass {
1026     pub fn new(threshold: u64) -> Self {
1027         Self {
1028             threshold,
1029         }
1030     }
1031 }
1032
1033 impl LintPass for TypeComplexityPass {
1034     fn get_lints(&self) -> LintArray {
1035         lint_array!(TYPE_COMPLEXITY)
1036     }
1037 }
1038
1039 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
1040     fn check_fn(
1041         &mut self,
1042         cx: &LateContext<'a, 'tcx>,
1043         _: FnKind<'tcx>,
1044         decl: &'tcx FnDecl,
1045         _: &'tcx Body,
1046         _: Span,
1047         _: NodeId,
1048     ) {
1049         self.check_fndecl(cx, decl);
1050     }
1051
1052     fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
1053         // enum variants are also struct fields now
1054         self.check_type(cx, &field.ty);
1055     }
1056
1057     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1058         match item.node {
1059             ItemStatic(ref ty, _, _) | ItemConst(ref ty, _) => self.check_type(cx, ty),
1060             // functions, enums, structs, impls and traits are covered
1061             _ => (),
1062         }
1063     }
1064
1065     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
1066         match item.node {
1067             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1068             TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1069             // methods with default impl are covered by check_fn
1070             _ => (),
1071         }
1072     }
1073
1074     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
1075         match item.node {
1076             ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
1077             // methods are covered by check_fn
1078             _ => (),
1079         }
1080     }
1081
1082     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
1083         if let Some(ref ty) = local.ty {
1084             self.check_type(cx, ty);
1085         }
1086     }
1087 }
1088
1089 impl<'a, 'tcx> TypeComplexityPass {
1090     fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
1091         for arg in &decl.inputs {
1092             self.check_type(cx, arg);
1093         }
1094         if let Return(ref ty) = decl.output {
1095             self.check_type(cx, ty);
1096         }
1097     }
1098
1099     fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
1100         if in_macro(ty.span) {
1101             return;
1102         }
1103         let score = {
1104             let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1105             visitor.visit_ty(ty);
1106             visitor.score
1107         };
1108
1109         if score > self.threshold {
1110             span_lint(
1111                 cx,
1112                 TYPE_COMPLEXITY,
1113                 ty.span,
1114                 "very complex type used. Consider factoring parts into `type` definitions",
1115             );
1116         }
1117     }
1118 }
1119
1120 /// Walks a type and assigns a complexity score to it.
1121 struct TypeComplexityVisitor {
1122     /// total complexity score of the type
1123     score: u64,
1124     /// current nesting level
1125     nest: u64,
1126 }
1127
1128 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1129     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1130         let (add_score, sub_nest) = match ty.node {
1131             // _, &x and *x have only small overhead; don't mess with nesting level
1132             TyInfer | TyPtr(..) | TyRptr(..) => (1, 0),
1133
1134             // the "normal" components of a type: named types, arrays/tuples
1135             TyPath(..) | TySlice(..) | TyTup(..) | TyArray(..) => (10 * self.nest, 1),
1136
1137             // function types bring a lot of overhead
1138             TyBareFn(..) => (50 * self.nest, 1),
1139
1140             TyTraitObject(ref param_bounds, _) => {
1141                 let has_lifetime_parameters = param_bounds
1142                     .iter()
1143                     .any(|bound| bound.bound_generic_params.iter().any(|gen| gen.is_lifetime_param()));
1144                 if has_lifetime_parameters {
1145                     // complex trait bounds like A<'a, 'b>
1146                     (50 * self.nest, 1)
1147                 } else {
1148                     // simple trait bounds like A + B
1149                     (20 * self.nest, 0)
1150                 }
1151             },
1152
1153             _ => (0, 0),
1154         };
1155         self.score += add_score;
1156         self.nest += sub_nest;
1157         walk_ty(self, ty);
1158         self.nest -= sub_nest;
1159     }
1160     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1161         NestedVisitorMap::None
1162     }
1163 }
1164
1165 /// **What it does:** Checks for expressions where a character literal is cast
1166 /// to `u8` and suggests using a byte literal instead.
1167 ///
1168 /// **Why is this bad?** In general, casting values to smaller types is
1169 /// error-prone and should be avoided where possible. In the particular case of
1170 /// converting a character literal to u8, it is easy to avoid by just using a
1171 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1172 /// than `'a' as u8`.
1173 ///
1174 /// **Known problems:** None.
1175 ///
1176 /// **Example:**
1177 /// ```rust
1178 /// 'x' as u8
1179 /// ```
1180 ///
1181 /// A better version, using the byte literal:
1182 ///
1183 /// ```rust
1184 /// b'x'
1185 /// ```
1186 declare_clippy_lint! {
1187     pub CHAR_LIT_AS_U8,
1188     complexity,
1189     "casting a character literal to u8"
1190 }
1191
1192 pub struct CharLitAsU8;
1193
1194 impl LintPass for CharLitAsU8 {
1195     fn get_lints(&self) -> LintArray {
1196         lint_array!(CHAR_LIT_AS_U8)
1197     }
1198 }
1199
1200 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1201     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1202         use syntax::ast::{LitKind, UintTy};
1203
1204         if let ExprCast(ref e, _) = expr.node {
1205             if let ExprLit(ref l) = e.node {
1206                 if let LitKind::Char(_) = l.node {
1207                     if ty::TyUint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
1208                         let msg = "casting character literal to u8. `char`s \
1209                                    are 4 bytes wide in rust, so casting to u8 \
1210                                    truncates them";
1211                         let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
1212                         span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
1213                     }
1214                 }
1215             }
1216         }
1217     }
1218 }
1219
1220 /// **What it does:** Checks for comparisons where one side of the relation is
1221 /// either the minimum or maximum value for its type and warns if it involves a
1222 /// case that is always true or always false. Only integer and boolean types are
1223 /// checked.
1224 ///
1225 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1226 /// that is is possible for `x` to be less than the minimum. Expressions like
1227 /// `max < x` are probably mistakes.
1228 ///
1229 /// **Known problems:** For `usize` the size of the current compile target will
1230 /// be assumed (e.g. 64 bits on 64 bit systems). This means code that uses such
1231 /// a comparison to detect target pointer width will trigger this lint. One can
1232 /// use `mem::sizeof` and compare its value or conditional compilation
1233 /// attributes
1234 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1235 ///
1236 /// **Example:**
1237 /// ```rust
1238 /// vec.len() <= 0
1239 /// 100 > std::i32::MAX
1240 /// ```
1241 declare_clippy_lint! {
1242     pub ABSURD_EXTREME_COMPARISONS,
1243     correctness,
1244     "a comparison with a maximum or minimum value that is always true or false"
1245 }
1246
1247 pub struct AbsurdExtremeComparisons;
1248
1249 impl LintPass for AbsurdExtremeComparisons {
1250     fn get_lints(&self) -> LintArray {
1251         lint_array!(ABSURD_EXTREME_COMPARISONS)
1252     }
1253 }
1254
1255 enum ExtremeType {
1256     Minimum,
1257     Maximum,
1258 }
1259
1260 struct ExtremeExpr<'a> {
1261     which: ExtremeType,
1262     expr: &'a Expr,
1263 }
1264
1265 enum AbsurdComparisonResult {
1266     AlwaysFalse,
1267     AlwaysTrue,
1268     InequalityImpossible,
1269 }
1270
1271
1272 fn is_cast_between_fixed_and_target<'a, 'tcx>(
1273     cx: &LateContext<'a, 'tcx>,
1274     expr: &'tcx Expr
1275 ) -> bool {
1276
1277     if let ExprCast(ref cast_exp, _) = expr.node {
1278         let precast_ty = cx.tables.expr_ty(cast_exp);
1279         let cast_ty = cx.tables.expr_ty(expr);
1280
1281         return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty)
1282     }
1283
1284     false
1285 }
1286
1287 fn detect_absurd_comparison<'a, 'tcx>(
1288     cx: &LateContext<'a, 'tcx>,
1289     op: BinOp_,
1290     lhs: &'tcx Expr,
1291     rhs: &'tcx Expr,
1292 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1293     use types::ExtremeType::*;
1294     use types::AbsurdComparisonResult::*;
1295     use utils::comparisons::*;
1296
1297     // absurd comparison only makes sense on primitive types
1298     // primitive types don't implement comparison operators with each other
1299     if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1300         return None;
1301     }
1302
1303     // comparisons between fix sized types and target sized types are considered unanalyzable
1304     if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1305         return None;
1306     }
1307
1308     let normalized = normalize_comparison(op, lhs, rhs);
1309     let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1310         val
1311     } else {
1312         return None;
1313     };
1314
1315     let lx = detect_extreme_expr(cx, normalized_lhs);
1316     let rx = detect_extreme_expr(cx, normalized_rhs);
1317
1318     Some(match rel {
1319         Rel::Lt => {
1320             match (lx, rx) {
1321                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1322                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1323                 _ => return None,
1324             }
1325         },
1326         Rel::Le => {
1327             match (lx, rx) {
1328                 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1329                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1330                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1331                 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1332                 _ => return None,
1333             }
1334         },
1335         Rel::Ne | Rel::Eq => return None,
1336     })
1337 }
1338
1339 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<ExtremeExpr<'tcx>> {
1340     use types::ExtremeType::*;
1341
1342     let ty = cx.tables.expr_ty(expr);
1343
1344     let cv = constant(cx, cx.tables, expr)?.0;
1345
1346     let which = match (&ty.sty, cv) {
1347         (&ty::TyBool, Constant::Bool(false)) |
1348         (&ty::TyUint(_), Constant::Int(0)) => Minimum,
1349         (&ty::TyInt(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Minimum,
1350
1351         (&ty::TyBool, Constant::Bool(true)) => Maximum,
1352         (&ty::TyInt(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Maximum,
1353         (&ty::TyUint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1354
1355         _ => return None,
1356     };
1357     Some(ExtremeExpr {
1358         which,
1359         expr,
1360     })
1361 }
1362
1363 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1364     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1365         use types::ExtremeType::*;
1366         use types::AbsurdComparisonResult::*;
1367
1368         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1369             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1370                 if !in_macro(expr.span) {
1371                     let msg = "this comparison involving the minimum or maximum element for this \
1372                                type contains a case that is always true or always false";
1373
1374                     let conclusion = match result {
1375                         AlwaysFalse => "this comparison is always false".to_owned(),
1376                         AlwaysTrue => "this comparison is always true".to_owned(),
1377                         InequalityImpossible => format!(
1378                             "the case where the two sides are not equal never occurs, consider using {} == {} \
1379                              instead",
1380                             snippet(cx, lhs.span, "lhs"),
1381                             snippet(cx, rhs.span, "rhs")
1382                         ),
1383                     };
1384
1385                     let help = format!(
1386                         "because {} is the {} value for this type, {}",
1387                         snippet(cx, culprit.expr.span, "x"),
1388                         match culprit.which {
1389                             Minimum => "minimum",
1390                             Maximum => "maximum",
1391                         },
1392                         conclusion
1393                     );
1394
1395                     span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1396                 }
1397             }
1398         }
1399     }
1400 }
1401
1402 /// **What it does:** Checks for comparisons where the relation is always either
1403 /// true or false, but where one side has been upcast so that the comparison is
1404 /// necessary. Only integer types are checked.
1405 ///
1406 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1407 /// will mistakenly imply that it is possible for `x` to be outside the range of
1408 /// `u8`.
1409 ///
1410 /// **Known problems:**
1411 /// https://github.com/rust-lang-nursery/rust-clippy/issues/886
1412 ///
1413 /// **Example:**
1414 /// ```rust
1415 /// let x : u8 = ...; (x as u32) > 300
1416 /// ```
1417 declare_clippy_lint! {
1418     pub INVALID_UPCAST_COMPARISONS,
1419     pedantic,
1420     "a comparison involving an upcast which is always true or false"
1421 }
1422
1423 pub struct InvalidUpcastComparisons;
1424
1425 impl LintPass for InvalidUpcastComparisons {
1426     fn get_lints(&self) -> LintArray {
1427         lint_array!(INVALID_UPCAST_COMPARISONS)
1428     }
1429 }
1430
1431 #[derive(Copy, Clone, Debug, Eq)]
1432 enum FullInt {
1433     S(i128),
1434     U(u128),
1435 }
1436
1437 impl FullInt {
1438     #[allow(cast_sign_loss)]
1439     fn cmp_s_u(s: i128, u: u128) -> Ordering {
1440         if s < 0 {
1441             Ordering::Less
1442         } else if u > (i128::max_value() as u128) {
1443             Ordering::Greater
1444         } else {
1445             (s as u128).cmp(&u)
1446         }
1447     }
1448 }
1449
1450 impl PartialEq for FullInt {
1451     fn eq(&self, other: &Self) -> bool {
1452         self.partial_cmp(other)
1453             .expect("partial_cmp only returns Some(_)") == Ordering::Equal
1454     }
1455 }
1456
1457 impl PartialOrd for FullInt {
1458     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1459         Some(match (self, other) {
1460             (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1461             (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1462             (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1463             (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1464         })
1465     }
1466 }
1467 impl Ord for FullInt {
1468     fn cmp(&self, other: &Self) -> Ordering {
1469         self.partial_cmp(other)
1470             .expect("partial_cmp for FullInt can never return None")
1471     }
1472 }
1473
1474
1475 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1476     use syntax::ast::{IntTy, UintTy};
1477     use std::*;
1478
1479     if let ExprCast(ref cast_exp, _) = expr.node {
1480         let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1481         let cast_ty = cx.tables.expr_ty(expr);
1482         // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1483         if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1484             return None;
1485         }
1486         match pre_cast_ty.sty {
1487             ty::TyInt(int_ty) => Some(match int_ty {
1488                 IntTy::I8 => (FullInt::S(i128::from(i8::min_value())), FullInt::S(i128::from(i8::max_value()))),
1489                 IntTy::I16 => (
1490                     FullInt::S(i128::from(i16::min_value())),
1491                     FullInt::S(i128::from(i16::max_value())),
1492                 ),
1493                 IntTy::I32 => (
1494                     FullInt::S(i128::from(i32::min_value())),
1495                     FullInt::S(i128::from(i32::max_value())),
1496                 ),
1497                 IntTy::I64 => (
1498                     FullInt::S(i128::from(i64::min_value())),
1499                     FullInt::S(i128::from(i64::max_value())),
1500                 ),
1501                 IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
1502                 IntTy::Isize => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
1503             }),
1504             ty::TyUint(uint_ty) => Some(match uint_ty {
1505                 UintTy::U8 => (FullInt::U(u128::from(u8::min_value())), FullInt::U(u128::from(u8::max_value()))),
1506                 UintTy::U16 => (
1507                     FullInt::U(u128::from(u16::min_value())),
1508                     FullInt::U(u128::from(u16::max_value())),
1509                 ),
1510                 UintTy::U32 => (
1511                     FullInt::U(u128::from(u32::min_value())),
1512                     FullInt::U(u128::from(u32::max_value())),
1513                 ),
1514                 UintTy::U64 => (
1515                     FullInt::U(u128::from(u64::min_value())),
1516                     FullInt::U(u128::from(u64::max_value())),
1517                 ),
1518                 UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
1519                 UintTy::Usize => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
1520             }),
1521             _ => None,
1522         }
1523     } else {
1524         None
1525     }
1526 }
1527
1528 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<FullInt> {
1529     let val = constant(cx, cx.tables, expr)?.0;
1530     if let Constant::Int(const_int) = val {
1531         match cx.tables.expr_ty(expr).sty {
1532             ty::TyInt(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1533             ty::TyUint(_) => Some(FullInt::U(const_int)),
1534             _ => None,
1535         }
1536     } else {
1537         None
1538     }
1539 }
1540
1541 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
1542     if let ExprCast(ref cast_val, _) = expr.node {
1543         span_lint(
1544             cx,
1545             INVALID_UPCAST_COMPARISONS,
1546             *span,
1547             &format!(
1548                 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1549                 snippet(cx, cast_val.span, "the expression"),
1550                 if always { "true" } else { "false" },
1551             ),
1552         );
1553     }
1554 }
1555
1556 fn upcast_comparison_bounds_err<'a, 'tcx>(
1557     cx: &LateContext<'a, 'tcx>,
1558     span: &Span,
1559     rel: comparisons::Rel,
1560     lhs_bounds: Option<(FullInt, FullInt)>,
1561     lhs: &'tcx Expr,
1562     rhs: &'tcx Expr,
1563     invert: bool,
1564 ) {
1565     use utils::comparisons::*;
1566
1567     if let Some((lb, ub)) = lhs_bounds {
1568         if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1569             if rel == Rel::Eq || rel == Rel::Ne {
1570                 if norm_rhs_val < lb || norm_rhs_val > ub {
1571                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1572                 }
1573             } else if match rel {
1574                 Rel::Lt => if invert {
1575                     norm_rhs_val < lb
1576                 } else {
1577                     ub < norm_rhs_val
1578                 },
1579                 Rel::Le => if invert {
1580                     norm_rhs_val <= lb
1581                 } else {
1582                     ub <= norm_rhs_val
1583                 },
1584                 Rel::Eq | Rel::Ne => unreachable!(),
1585             } {
1586                 err_upcast_comparison(cx, span, lhs, true)
1587             } else if match rel {
1588                 Rel::Lt => if invert {
1589                     norm_rhs_val >= ub
1590                 } else {
1591                     lb >= norm_rhs_val
1592                 },
1593                 Rel::Le => if invert {
1594                     norm_rhs_val > ub
1595                 } else {
1596                     lb > norm_rhs_val
1597                 },
1598                 Rel::Eq | Rel::Ne => unreachable!(),
1599             } {
1600                 err_upcast_comparison(cx, span, lhs, false)
1601             }
1602         }
1603     }
1604 }
1605
1606 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1607     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1608         if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
1609             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1610             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1611                 val
1612             } else {
1613                 return;
1614             };
1615
1616             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1617             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1618
1619             upcast_comparison_bounds_err(cx, &expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1620             upcast_comparison_bounds_err(cx, &expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1621         }
1622     }
1623 }
1624
1625 /// **What it does:** Checks for public `impl` or `fn` missing generalization
1626 /// over different hashers and implicitly defaulting to the default hashing
1627 /// algorithm (SipHash).
1628 ///
1629 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
1630 /// used with them.
1631 ///
1632 /// **Known problems:** Suggestions for replacing constructors can contain
1633 /// false-positives. Also applying suggestions can require modification of other
1634 /// pieces of code, possibly including external crates.
1635 ///
1636 /// **Example:**
1637 /// ```rust
1638 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { ... }
1639 ///
1640 /// pub foo(map: &mut HashMap<i32, i32>) { .. }
1641 /// ```
1642 declare_clippy_lint! {
1643     pub IMPLICIT_HASHER,
1644     style,
1645     "missing generalization over different hashers"
1646 }
1647
1648 pub struct ImplicitHasher;
1649
1650 impl LintPass for ImplicitHasher {
1651     fn get_lints(&self) -> LintArray {
1652         lint_array!(IMPLICIT_HASHER)
1653     }
1654 }
1655
1656 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
1657     #[allow(cast_possible_truncation)]
1658     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1659         use syntax_pos::BytePos;
1660
1661         fn suggestion<'a, 'tcx>(
1662             cx: &LateContext<'a, 'tcx>,
1663             db: &mut DiagnosticBuilder,
1664             generics_span: Span,
1665             generics_suggestion_span: Span,
1666             target: &ImplicitHasherType,
1667             vis: ImplicitHasherConstructorVisitor,
1668         ) {
1669             let generics_snip = snippet(cx, generics_span, "");
1670             // trim `<` `>`
1671             let generics_snip = if generics_snip.is_empty() {
1672                 ""
1673             } else {
1674                 &generics_snip[1..generics_snip.len() - 1]
1675             };
1676
1677             multispan_sugg(
1678                 db,
1679                 "consider adding a type parameter".to_string(),
1680                 vec![
1681                     (
1682                         generics_suggestion_span,
1683                         format!(
1684                             "<{}{}S: ::std::hash::BuildHasher{}>",
1685                             generics_snip,
1686                             if generics_snip.is_empty() { "" } else { ", " },
1687                             if vis.suggestions.is_empty() {
1688                                 ""
1689                             } else {
1690                                 // request users to add `Default` bound so that generic constructors can be used
1691                                 " + Default"
1692                             },
1693                         ),
1694                     ),
1695                     (
1696                         target.span(),
1697                         format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
1698                     ),
1699                 ],
1700             );
1701
1702             if !vis.suggestions.is_empty() {
1703                 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
1704             }
1705         }
1706
1707         if !cx.access_levels.is_exported(item.id) {
1708             return;
1709         }
1710
1711         match item.node {
1712             ItemImpl(_, _, _, ref generics, _, ref ty, ref items) => {
1713                 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1714                 vis.visit_ty(ty);
1715
1716                 for target in &vis.found {
1717                     if differing_macro_contexts(item.span, target.span()) {
1718                         return;
1719                     }
1720
1721                     let generics_suggestion_span = generics.span.substitute_dummy({
1722                         let pos = snippet_opt(cx, item.span.until(target.span()))
1723                             .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)))
1724                             .expect("failed to create span for type arguments");
1725                         Span::new(pos, pos, item.span.data().ctxt)
1726                     });
1727
1728                     let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1729                     for item in items.iter().map(|item| cx.tcx.hir.impl_item(item.id)) {
1730                         ctr_vis.visit_impl_item(item);
1731                     }
1732
1733                     span_lint_and_then(
1734                         cx,
1735                         IMPLICIT_HASHER,
1736                         target.span(),
1737                         &format!("impl for `{}` should be generalized over different hashers", target.type_name()),
1738                         move |db| {
1739                             suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1740                         },
1741                     );
1742                 }
1743             },
1744             ItemFn(ref decl, .., ref generics, body_id) => {
1745                 let body = cx.tcx.hir.body(body_id);
1746
1747                 for ty in &decl.inputs {
1748                     let mut vis = ImplicitHasherTypeVisitor::new(cx);
1749                     vis.visit_ty(ty);
1750
1751                     for target in &vis.found {
1752                         let generics_suggestion_span = generics.span.substitute_dummy({
1753                             let pos = snippet_opt(cx, item.span.until(body.arguments[0].pat.span))
1754                                 .and_then(|snip| {
1755                                     let i = snip.find("fn")?;
1756                                     Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
1757                                 })
1758                                 .expect("failed to create span for type parameters");
1759                             Span::new(pos, pos, item.span.data().ctxt)
1760                         });
1761
1762                         let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1763                         ctr_vis.visit_body(body);
1764
1765                         span_lint_and_then(
1766                             cx,
1767                             IMPLICIT_HASHER,
1768                             target.span(),
1769                             &format!(
1770                                 "parameter of type `{}` should be generalized over different hashers",
1771                                 target.type_name()
1772                             ),
1773                             move |db| {
1774                                 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1775                             },
1776                         );
1777                     }
1778                 }
1779             },
1780             _ => {},
1781         }
1782     }
1783 }
1784
1785 enum ImplicitHasherType<'tcx> {
1786     HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
1787     HashSet(Span, Ty<'tcx>, Cow<'static, str>),
1788 }
1789
1790 impl<'tcx> ImplicitHasherType<'tcx> {
1791     /// Checks that `ty` is a target type without a BuildHasher.
1792     fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
1793         if let TyPath(QPath::Resolved(None, ref path)) = hir_ty.node {
1794             let params = &path.segments.last().as_ref()?.parameters.as_ref()?.types;
1795             let params_len = params.len();
1796
1797             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1798
1799             if match_path(path, &paths::HASHMAP) && params_len == 2 {
1800                 Some(ImplicitHasherType::HashMap(
1801                     hir_ty.span,
1802                     ty,
1803                     snippet(cx, params[0].span, "K"),
1804                     snippet(cx, params[1].span, "V"),
1805                 ))
1806             } else if match_path(path, &paths::HASHSET) && params_len == 1 {
1807                 Some(ImplicitHasherType::HashSet(hir_ty.span, ty, snippet(cx, params[0].span, "T")))
1808             } else {
1809                 None
1810             }
1811         } else {
1812             None
1813         }
1814     }
1815
1816     fn type_name(&self) -> &'static str {
1817         match *self {
1818             ImplicitHasherType::HashMap(..) => "HashMap",
1819             ImplicitHasherType::HashSet(..) => "HashSet",
1820         }
1821     }
1822
1823     fn type_arguments(&self) -> String {
1824         match *self {
1825             ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
1826             ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
1827         }
1828     }
1829
1830     fn ty(&self) -> Ty<'tcx> {
1831         match *self {
1832             ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
1833         }
1834     }
1835
1836     fn span(&self) -> Span {
1837         match *self {
1838             ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
1839         }
1840     }
1841 }
1842
1843 struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
1844     cx: &'a LateContext<'a, 'tcx>,
1845     found: Vec<ImplicitHasherType<'tcx>>,
1846 }
1847
1848 impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
1849     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
1850         Self { cx, found: vec![] }
1851     }
1852 }
1853
1854 impl<'a, 'tcx: 'a> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
1855     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1856         if let Some(target) = ImplicitHasherType::new(self.cx, t) {
1857             self.found.push(target);
1858         }
1859
1860         walk_ty(self, t);
1861     }
1862
1863     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1864         NestedVisitorMap::None
1865     }
1866 }
1867
1868 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
1869 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx: 'a + 'b> {
1870     cx: &'a LateContext<'a, 'tcx>,
1871     body: &'a TypeckTables<'tcx>,
1872     target: &'b ImplicitHasherType<'tcx>,
1873     suggestions: BTreeMap<Span, String>,
1874 }
1875
1876 impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1877     fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
1878         Self {
1879             cx,
1880             body: cx.tables,
1881             target,
1882             suggestions: BTreeMap::new(),
1883         }
1884     }
1885 }
1886
1887 impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1888     fn visit_body(&mut self, body: &'tcx Body) {
1889         self.body = self.cx.tcx.body_tables(body.id());
1890         walk_body(self, body);
1891     }
1892
1893     fn visit_expr(&mut self, e: &'tcx Expr) {
1894         if_chain! {
1895             if let ExprCall(ref fun, ref args) = e.node;
1896             if let ExprPath(QPath::TypeRelative(ref ty, ref method)) = fun.node;
1897             if let TyPath(QPath::Resolved(None, ref ty_path)) = ty.node;
1898             then {
1899                 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
1900                     return;
1901                 }
1902
1903                 if match_path(ty_path, &paths::HASHMAP) {
1904                     if method.name == "new" {
1905                         self.suggestions
1906                             .insert(e.span, "HashMap::default()".to_string());
1907                     } else if method.name == "with_capacity" {
1908                         self.suggestions.insert(
1909                             e.span,
1910                             format!(
1911                                 "HashMap::with_capacity_and_hasher({}, Default::default())",
1912                                 snippet(self.cx, args[0].span, "capacity"),
1913                             ),
1914                         );
1915                     }
1916                 } else if match_path(ty_path, &paths::HASHSET) {
1917                     if method.name == "new" {
1918                         self.suggestions
1919                             .insert(e.span, "HashSet::default()".to_string());
1920                     } else if method.name == "with_capacity" {
1921                         self.suggestions.insert(
1922                             e.span,
1923                             format!(
1924                                 "HashSet::with_capacity_and_hasher({}, Default::default())",
1925                                 snippet(self.cx, args[0].span, "capacity"),
1926                             ),
1927                         );
1928                     }
1929                 }
1930             }
1931         }
1932
1933         walk_expr(self, e);
1934     }
1935
1936     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1937         NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)
1938     }
1939 }