4 use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
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;
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};
19 use consts::{constant, Constant};
21 /// Handles all the linting of funky types
22 #[allow(missing_copy_implementations)]
25 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
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.
31 /// **Known problems:** None.
36 /// values: Box<Vec<Foo>>,
47 declare_clippy_lint! {
50 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
53 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
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.
60 /// **Known problems:** None.
64 /// fn x() -> Option<Option<u32>> {
67 declare_clippy_lint! {
70 "usage of `Option<Option<T>>`"
73 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
74 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
76 /// **Why is this bad?** Gankro says:
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.
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
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`.
95 /// **Known problems:** False positives – the instances where using a
96 /// `LinkedList` makes sense are few and far between, but they can still happen.
100 /// let x = LinkedList::new();
102 declare_clippy_lint! {
105 "usage of LinkedList, usually a vector is faster, or a more specialized data \
106 structure like a VecDeque"
109 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
111 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
114 /// **Known problems:** None.
118 /// fn foo(bar: &Box<T>) { ... }
124 /// fn foo(bar: &T) { ... }
126 declare_clippy_lint! {
129 "a borrow of a boxed type"
132 impl LintPass for TypePass {
133 fn get_lints(&self) -> LintArray {
134 lint_array!(BOX_VEC, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
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 {
147 check_fn_decl(cx, decl);
150 fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
151 check_ty(cx, &field.ty, false);
154 fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
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),
162 fn check_local(&mut self, cx: &LateContext, local: &Local) {
163 if let Some(ref ty) = local.ty {
164 check_ty(cx, ty, true);
169 fn check_fn_decl(cx: &LateContext, decl: &FnDecl) {
170 for input in &decl.inputs {
171 check_ty(cx, input, false);
174 if let FunctionRetTy::Return(ref ty) = decl.output {
175 check_ty(cx, ty, false);
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);
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);
196 /// Recursively check for `TypePass` lints in the given type. Stop at the first
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) {
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) {
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.",
219 return; // don't recurse into the type
221 } else if match_def_path(cx.tcx, def_id, &paths::OPTION) {
222 if match_type_parameter(cx, qpath, &paths::OPTION) {
227 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
228 enum if you need to distinguish all 3 cases",
230 return; // don't recurse into the type
232 } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
237 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
238 "a VecDeque might work",
240 return; // don't recurse into the type
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| {
249 .map_or_else(|| [].iter(), |params| params.types.iter())
251 check_ty(cx, ty, is_local);
254 QPath::Resolved(None, ref p) => for ty in p.segments.iter().flat_map(|seg| {
257 .map_or_else(|| [].iter(), |params| params.types.iter())
259 check_ty(cx, ty, is_local);
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);
271 TyRptr(ref lt, ref mut_ty) => check_ty_rptr(cx, ast_ty, is_local, lt, mut_ty),
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);
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);
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;
295 if is_any_trait(inner) {
296 // Ignore `Box<Any>` types, see #1884 for details.
300 let ltopt = if lt.is_elided() {
303 format!("{} ", lt.name.name().as_str())
305 let mutopt = if mut_ty.mutbl == Mutability::MutMutable {
310 span_lint_and_sugg(cx,
313 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
315 format!("&{}{}{}", ltopt, mutopt, &snippet(cx, inner.span, ".."))
317 return; // don't recurse into the type
320 check_ty(cx, &mut_ty.ty, is_local);
322 _ => check_ty(cx, &mut_ty.ty, is_local),
326 // Returns true if given type is `Any` trait.
327 fn is_any_trait(t: &hir::Ty) -> bool {
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);
342 #[allow(missing_copy_implementations)]
345 /// **What it does:** Checks for binding a unit value.
347 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
348 /// binding one is kind of pointless.
350 /// **Known problems:** None.
356 declare_clippy_lint! {
359 "creating a let binding to a value of unit type, which usually can't be used afterwards"
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) {
368 if higher::is_from_for_desugar(decl) {
376 "this let-binding has unit value. Consider omitting `let {} =`",
377 snippet(cx, local.pat.span, "..")
384 impl LintPass for LetPass {
385 fn get_lints(&self) -> LintArray {
386 lint_array!(LET_UNIT_VALUE)
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)
396 /// **What it does:** Checks for comparisons to unit.
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.
402 /// **Known problems:** None.
406 /// if { foo(); } == { bar(); } { baz(); }
410 /// { foo(); bar(); baz(); }
412 declare_clippy_lint! {
415 "comparing unit values"
418 #[allow(missing_copy_implementations)]
421 impl LintPass for UnitCmp {
422 fn get_lints(&self) -> LintArray {
423 lint_array!(UNIT_CMP)
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) {
432 if let ExprBinary(ref cmp, ref left, _) = expr.node {
434 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
435 let result = match op {
436 BiEq | BiLe | BiGe => "true",
444 "{}-comparison of unit values detected. This will always be {}",
454 /// **What it does:** Checks for passing a unit value as an argument to a function without using a unit literal (`()`).
456 /// **Why is this bad?** This is likely the result of an accidental semicolon.
458 /// **Known problems:** None.
467 declare_clippy_lint! {
470 "passing unit to a function"
475 impl LintPass for UnitArg {
476 fn get_lints(&self) -> LintArray {
477 lint_array!(UNIT_ARG)
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) {
487 ExprCall(_, ref args) | ExprMethodCall(_, _, ref 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) {
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);
502 // `expr` and `parent_expr` where _both_ not from
503 // desugaring `?`, so lint
508 "passing a unit value to a function",
509 "if you intended to pass a unit value, use a unit literal instead",
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)
532 fn is_unit(ty: Ty) -> bool {
534 ty::TyTuple(slice) if slice.is_empty() => true,
539 fn is_unit_literal(expr: &Expr) -> bool {
541 ExprTup(ref slice) if slice.is_empty() => true,
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.
553 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
554 /// or any 64-bit integer to `f64`.
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.
560 /// **Known problems:** None.
564 /// let x = u64::MAX; x as f64
566 declare_clippy_lint! {
567 pub CAST_PRECISION_LOSS,
569 "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
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.
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.
580 /// **Known problems:** None.
585 /// y as u128 // will return 18446744073709551615
587 declare_clippy_lint! {
590 "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
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
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.
601 /// **Known problems:** None.
605 /// fn as_u8(x: u64) -> u8 { x as u8 }
607 declare_clippy_lint! {
608 pub CAST_POSSIBLE_TRUNCATION,
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`"
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.
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
625 /// **Known problems:** None.
629 /// u32::MAX as i32 // will yield a value of `-1`
631 declare_clippy_lint! {
632 pub CAST_POSSIBLE_WRAP,
634 "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` \
638 /// **What it does:** Checks for on casts between numerical types that may
639 /// be replaced by safe conversion functions.
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.
648 /// **Known problems:** None.
652 /// fn as_u64(x: u8) -> u64 { x as u64 }
655 /// Using `::from` would look like this:
658 /// fn as_u64(x: u8) -> u64 { u64::from(x) }
660 declare_clippy_lint! {
663 "casts using `as` that are known to be lossless, e.g. `x as u64` where `x: u8`"
666 /// **What it does:** Checks for casts to the same type.
668 /// **Why is this bad?** It's just unnecessary.
670 /// **Known problems:** None.
674 /// let _ = 2i32 as i32
676 declare_clippy_lint! {
677 pub UNNECESSARY_CAST,
679 "cast to the same type, e.g. `x as i32` where `x: i32`"
682 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
683 /// more-strictly-aligned pointer
685 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
688 /// **Known problems:** None.
692 /// let _ = (&1u8 as *const u8) as *const u16;
693 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
695 declare_clippy_lint! {
696 pub CAST_PTR_ALIGNMENT,
698 "cast from a pointer to a more-strictly-aligned pointer"
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 {
705 ty::TyInt(i) => match i {
706 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
713 ty::TyUint(i) => match i {
714 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
725 fn is_isize_or_usize(typ: Ty) -> bool {
727 ty::TyInt(IntTy::Isize) | ty::TyUint(UintTy::Usize) => true,
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 {
738 } else if is_isize_or_usize(cast_from) {
739 "32 or 64".to_owned()
741 int_ty_to_nbits(cast_from, cx.tcx).to_string()
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)",
751 if cast_to_f64 { "f64" } else { "f32" },
763 fn should_strip_parens(op: &Expr, snip: &str) -> bool {
764 if let ExprBinary(_, _, _) = op.node {
765 if snip.starts_with('(') && snip.ends_with(')') {
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]
792 &format!("casting {} to {} may become silently lossy if types change", cast_from, cast_to),
794 format!("{}::from({})", cast_to, sugg),
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,
815 to_nbits == from_nbits && cast_unsigned_to_signed,
825 to_nbits <= 32 && cast_unsigned_to_signed,
831 cast_unsigned_to_signed,
832 if from_nbits == 64 {
842 CAST_POSSIBLE_TRUNCATION,
845 "casting {} to {} may truncate the value{}",
848 match suffix_truncation {
849 ArchSuffix::_32 => arch_32_suffix,
850 ArchSuffix::_64 => arch_64_suffix,
851 ArchSuffix::None => "",
862 "casting {} to {} may wrap around the value{}",
866 ArchSuffix::_32 => arch_32_suffix,
867 ArchSuffix::_64 => arch_64_suffix,
868 ArchSuffix::None => "",
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
881 span_lossless_lint(cx, expr, op, cast_from, cast_to);
885 impl LintPass for CastPass {
886 fn get_lints(&self) -> LintArray {
890 CAST_POSSIBLE_TRUNCATION,
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};
906 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
907 _ => if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
912 &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
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()) {
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 {
926 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
927 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
929 if from_nbits < to_nbits {
930 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
936 CAST_POSSIBLE_TRUNCATION,
938 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
940 if !cast_to.is_signed() {
945 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
950 if cast_from.is_signed() && !cast_to.is_signed() {
955 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
958 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
959 check_lossless(cx, expr, ex, cast_from, cast_to);
962 if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty)
966 CAST_POSSIBLE_TRUNCATION,
968 "casting f64 to f32 may truncate the value",
971 if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty)
973 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
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
986 match_type(cx, from_ptr_ty.ty, &paths::C_VOID)
987 || match_type(cx, from_ptr_ty.ty, &paths::C_VOID_LIBC)
994 &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
1002 /// **What it does:** Checks for types used in structs, parameters and `let`
1003 /// declarations above a certain complexity threshold.
1005 /// **Why is this bad?** Too complex types make the code less readable. Consider
1006 /// using a `type` definition to simplify them.
1008 /// **Known problems:** None.
1012 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
1014 declare_clippy_lint! {
1015 pub TYPE_COMPLEXITY,
1017 "usage of very complex types that might be better factored into `type` definitions"
1020 #[allow(missing_copy_implementations)]
1021 pub struct TypeComplexityPass {
1025 impl TypeComplexityPass {
1026 pub fn new(threshold: u64) -> Self {
1033 impl LintPass for TypeComplexityPass {
1034 fn get_lints(&self) -> LintArray {
1035 lint_array!(TYPE_COMPLEXITY)
1039 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
1042 cx: &LateContext<'a, 'tcx>,
1049 self.check_fndecl(cx, decl);
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);
1057 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1059 ItemStatic(ref ty, _, _) | ItemConst(ref ty, _) => self.check_type(cx, ty),
1060 // functions, enums, structs, impls and traits are covered
1065 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
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
1074 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
1076 ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
1077 // methods are covered by check_fn
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);
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);
1094 if let Return(ref ty) = decl.output {
1095 self.check_type(cx, ty);
1099 fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
1100 if in_macro(ty.span) {
1104 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1105 visitor.visit_ty(ty);
1109 if score > self.threshold {
1114 "very complex type used. Consider factoring parts into `type` definitions",
1120 /// Walks a type and assigns a complexity score to it.
1121 struct TypeComplexityVisitor {
1122 /// total complexity score of the type
1124 /// current nesting level
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),
1134 // the "normal" components of a type: named types, arrays/tuples
1135 TyPath(..) | TySlice(..) | TyTup(..) | TyArray(..) => (10 * self.nest, 1),
1137 // function types bring a lot of overhead
1138 TyBareFn(..) => (50 * self.nest, 1),
1140 TyTraitObject(ref param_bounds, _) => {
1141 let has_lifetime_parameters = param_bounds
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>
1148 // simple trait bounds like A + B
1155 self.score += add_score;
1156 self.nest += sub_nest;
1158 self.nest -= sub_nest;
1160 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1161 NestedVisitorMap::None
1165 /// **What it does:** Checks for expressions where a character literal is cast
1166 /// to `u8` and suggests using a byte literal instead.
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`.
1174 /// **Known problems:** None.
1181 /// A better version, using the byte literal:
1186 declare_clippy_lint! {
1189 "casting a character literal to u8"
1192 pub struct CharLitAsU8;
1194 impl LintPass for CharLitAsU8 {
1195 fn get_lints(&self) -> LintArray {
1196 lint_array!(CHAR_LIT_AS_U8)
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};
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 \
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);
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
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.
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
1234 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1239 /// 100 > std::i32::MAX
1241 declare_clippy_lint! {
1242 pub ABSURD_EXTREME_COMPARISONS,
1244 "a comparison with a maximum or minimum value that is always true or false"
1247 pub struct AbsurdExtremeComparisons;
1249 impl LintPass for AbsurdExtremeComparisons {
1250 fn get_lints(&self) -> LintArray {
1251 lint_array!(ABSURD_EXTREME_COMPARISONS)
1260 struct ExtremeExpr<'a> {
1265 enum AbsurdComparisonResult {
1268 InequalityImpossible,
1272 fn is_cast_between_fixed_and_target<'a, 'tcx>(
1273 cx: &LateContext<'a, 'tcx>,
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);
1281 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty)
1287 fn detect_absurd_comparison<'a, 'tcx>(
1288 cx: &LateContext<'a, 'tcx>,
1292 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1293 use types::ExtremeType::*;
1294 use types::AbsurdComparisonResult::*;
1295 use utils::comparisons::*;
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) {
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) {
1308 let normalized = normalize_comparison(op, lhs, rhs);
1309 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1315 let lx = detect_extreme_expr(cx, normalized_lhs);
1316 let rx = detect_extreme_expr(cx, normalized_rhs);
1321 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1322 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
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
1335 Rel::Ne | Rel::Eq => return None,
1339 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<ExtremeExpr<'tcx>> {
1340 use types::ExtremeType::*;
1342 let ty = cx.tables.expr_ty(expr);
1344 let cv = constant(cx, cx.tables, expr)?.0;
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,
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,
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::*;
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";
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 {} == {} \
1380 snippet(cx, lhs.span, "lhs"),
1381 snippet(cx, rhs.span, "rhs")
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",
1395 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
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.
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
1410 /// **Known problems:**
1411 /// https://github.com/rust-lang-nursery/rust-clippy/issues/886
1415 /// let x : u8 = ...; (x as u32) > 300
1417 declare_clippy_lint! {
1418 pub INVALID_UPCAST_COMPARISONS,
1420 "a comparison involving an upcast which is always true or false"
1423 pub struct InvalidUpcastComparisons;
1425 impl LintPass for InvalidUpcastComparisons {
1426 fn get_lints(&self) -> LintArray {
1427 lint_array!(INVALID_UPCAST_COMPARISONS)
1431 #[derive(Copy, Clone, Debug, Eq)]
1438 #[allow(cast_sign_loss)]
1439 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1442 } else if u > (i128::max_value() as u128) {
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
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(),
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")
1475 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1476 use syntax::ast::{IntTy, UintTy};
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) {
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()))),
1490 FullInt::S(i128::from(i16::min_value())),
1491 FullInt::S(i128::from(i16::max_value())),
1494 FullInt::S(i128::from(i32::min_value())),
1495 FullInt::S(i128::from(i32::max_value())),
1498 FullInt::S(i128::from(i64::min_value())),
1499 FullInt::S(i128::from(i64::max_value())),
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)),
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()))),
1507 FullInt::U(u128::from(u16::min_value())),
1508 FullInt::U(u128::from(u16::max_value())),
1511 FullInt::U(u128::from(u32::min_value())),
1512 FullInt::U(u128::from(u32::max_value())),
1515 FullInt::U(u128::from(u64::min_value())),
1516 FullInt::U(u128::from(u64::max_value())),
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)),
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)),
1541 fn err_upcast_comparison(cx: &LateContext, span: &Span, expr: &Expr, always: bool) {
1542 if let ExprCast(ref cast_val, _) = expr.node {
1545 INVALID_UPCAST_COMPARISONS,
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" },
1556 fn upcast_comparison_bounds_err<'a, 'tcx>(
1557 cx: &LateContext<'a, 'tcx>,
1559 rel: comparisons::Rel,
1560 lhs_bounds: Option<(FullInt, FullInt)>,
1565 use utils::comparisons::*;
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);
1573 } else if match rel {
1574 Rel::Lt => if invert {
1579 Rel::Le => if invert {
1584 Rel::Eq | Rel::Ne => unreachable!(),
1586 err_upcast_comparison(cx, span, lhs, true)
1587 } else if match rel {
1588 Rel::Lt => if invert {
1593 Rel::Le => if invert {
1598 Rel::Eq | Rel::Ne => unreachable!(),
1600 err_upcast_comparison(cx, span, lhs, false)
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 {
1616 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1617 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
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);
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).
1629 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
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.
1638 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { ... }
1640 /// pub foo(map: &mut HashMap<i32, i32>) { .. }
1642 declare_clippy_lint! {
1643 pub IMPLICIT_HASHER,
1645 "missing generalization over different hashers"
1648 pub struct ImplicitHasher;
1650 impl LintPass for ImplicitHasher {
1651 fn get_lints(&self) -> LintArray {
1652 lint_array!(IMPLICIT_HASHER)
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;
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,
1669 let generics_snip = snippet(cx, generics_span, "");
1671 let generics_snip = if generics_snip.is_empty() {
1674 &generics_snip[1..generics_snip.len() - 1]
1679 "consider adding a type parameter".to_string(),
1682 generics_suggestion_span,
1684 "<{}{}S: ::std::hash::BuildHasher{}>",
1686 if generics_snip.is_empty() { "" } else { ", " },
1687 if vis.suggestions.is_empty() {
1690 // request users to add `Default` bound so that generic constructors can be used
1697 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
1702 if !vis.suggestions.is_empty() {
1703 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
1707 if !cx.access_levels.is_exported(item.id) {
1712 ItemImpl(_, _, _, ref generics, _, ref ty, ref items) => {
1713 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1716 for target in &vis.found {
1717 if differing_macro_contexts(item.span, target.span()) {
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)
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);
1737 &format!("impl for `{}` should be generalized over different hashers", target.type_name()),
1739 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1744 ItemFn(ref decl, .., ref generics, body_id) => {
1745 let body = cx.tcx.hir.body(body_id);
1747 for ty in &decl.inputs {
1748 let mut vis = ImplicitHasherTypeVisitor::new(cx);
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))
1755 let i = snip.find("fn")?;
1756 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
1758 .expect("failed to create span for type parameters");
1759 Span::new(pos, pos, item.span.data().ctxt)
1762 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1763 ctr_vis.visit_body(body);
1770 "parameter of type `{}` should be generalized over different hashers",
1774 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1785 enum ImplicitHasherType<'tcx> {
1786 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
1787 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
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();
1797 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1799 if match_path(path, &paths::HASHMAP) && params_len == 2 {
1800 Some(ImplicitHasherType::HashMap(
1803 snippet(cx, params[0].span, "K"),
1804 snippet(cx, params[1].span, "V"),
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")))
1816 fn type_name(&self) -> &'static str {
1818 ImplicitHasherType::HashMap(..) => "HashMap",
1819 ImplicitHasherType::HashSet(..) => "HashSet",
1823 fn type_arguments(&self) -> String {
1825 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
1826 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
1830 fn ty(&self) -> Ty<'tcx> {
1832 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
1836 fn span(&self) -> Span {
1838 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
1843 struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
1844 cx: &'a LateContext<'a, 'tcx>,
1845 found: Vec<ImplicitHasherType<'tcx>>,
1848 impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
1849 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
1850 Self { cx, found: vec![] }
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);
1863 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1864 NestedVisitorMap::None
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>,
1876 impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1877 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
1882 suggestions: BTreeMap::new(),
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);
1893 fn visit_expr(&mut self, e: &'tcx Expr) {
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;
1899 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
1903 if match_path(ty_path, &paths::HASHMAP) {
1904 if method.name == "new" {
1906 .insert(e.span, "HashMap::default()".to_string());
1907 } else if method.name == "with_capacity" {
1908 self.suggestions.insert(
1911 "HashMap::with_capacity_and_hasher({}, Default::default())",
1912 snippet(self.cx, args[0].span, "capacity"),
1916 } else if match_path(ty_path, &paths::HASHSET) {
1917 if method.name == "new" {
1919 .insert(e.span, "HashSet::default()".to_string());
1920 } else if method.name == "with_capacity" {
1921 self.suggestions.insert(
1924 "HashSet::with_capacity_and_hasher({}, Default::default())",
1925 snippet(self.cx, args[0].span, "capacity"),
1936 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1937 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)