1 use crate::reexport::*;
4 use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
6 use rustc::{declare_lint, lint_array};
7 use if_chain::if_chain;
8 use rustc::ty::{self, Ty, TyCtxt, TypeckTables};
9 use rustc::ty::layout::LayoutOf;
10 use rustc_typeck::hir_ty_to_ty;
11 use std::cmp::Ordering;
12 use std::collections::BTreeMap;
14 use syntax::ast::{FloatTy, IntTy, UintTy};
15 use syntax::codemap::Span;
16 use syntax::errors::DiagnosticBuilder;
17 use crate::utils::{comparisons, differing_macro_contexts, higher, in_constant, in_external_macro, in_macro, last_path_segment, match_def_path, match_path,
18 match_type, multispan_sugg, opt_def_id, same_tys, snippet, snippet_opt, span_help_and_lint, span_lint,
19 span_lint_and_sugg, span_lint_and_then, clip, unsext, sext, int_bits};
20 use crate::utils::paths;
21 use crate::consts::{constant, Constant};
23 /// Handles all the linting of funky types
24 #[allow(missing_copy_implementations)]
27 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
29 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
30 /// the heap. So if you `Box` it, you just add another level of indirection
31 /// without any benefit whatsoever.
33 /// **Known problems:** None.
38 /// values: Box<Vec<Foo>>,
49 declare_clippy_lint! {
52 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
55 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
58 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
59 /// represents an optional optional value which is logically the same thing as an optional
60 /// value but has an unneeded extra level of wrapping.
62 /// **Known problems:** None.
66 /// fn x() -> Option<Option<u32>> {
69 declare_clippy_lint! {
72 "usage of `Option<Option<T>>`"
75 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
76 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
78 /// **Why is this bad?** Gankro says:
80 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
81 /// pointers and indirection.
82 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
84 /// > "only" amortized for push/pop, should be faster in the general case for
85 /// almost every possible
86 /// > workload, and isn't even amortized at all if you can predict the capacity
89 /// > `LinkedList`s are only really good if you're doing a lot of merging or
90 /// splitting of lists.
91 /// > This is because they can just mangle some pointers instead of actually
92 /// copying the data. Even
93 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
94 /// can still be better
95 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
97 /// **Known problems:** False positives – the instances where using a
98 /// `LinkedList` makes sense are few and far between, but they can still happen.
102 /// let x = LinkedList::new();
104 declare_clippy_lint! {
107 "usage of LinkedList, usually a vector is faster, or a more specialized data \
108 structure like a VecDeque"
111 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
113 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
116 /// **Known problems:** None.
120 /// fn foo(bar: &Box<T>) { ... }
126 /// fn foo(bar: &T) { ... }
128 declare_clippy_lint! {
131 "a borrow of a boxed type"
134 impl LintPass for TypePass {
135 fn get_lints(&self) -> LintArray {
136 lint_array!(BOX_VEC, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
140 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
141 fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &FnDecl, _: &Body, _: Span, id: NodeId) {
142 // skip trait implementations, see #605
143 if let Some(map::NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(id)) {
144 if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
149 check_fn_decl(cx, decl);
152 fn check_struct_field(&mut self, cx: &LateContext, field: &StructField) {
153 check_ty(cx, &field.ty, false);
156 fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
158 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
159 TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
164 fn check_local(&mut self, cx: &LateContext, local: &Local) {
165 if let Some(ref ty) = local.ty {
166 check_ty(cx, ty, true);
171 fn check_fn_decl(cx: &LateContext, decl: &FnDecl) {
172 for input in &decl.inputs {
173 check_ty(cx, input, false);
176 if let FunctionRetTy::Return(ref ty) = decl.output {
177 check_ty(cx, ty, false);
181 /// Check if `qpath` has last segment with type parameter matching `path`
182 fn match_type_parameter(cx: &LateContext, qpath: &QPath, path: &[&str]) -> bool {
183 let last = last_path_segment(qpath);
185 if let Some(ref params) = last.args;
186 if !params.parenthesized;
187 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
188 GenericArg::Type(ty) => Some(ty),
189 GenericArg::Lifetime(_) => None,
191 if let TyKind::Path(ref qpath) = ty.node;
192 if let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir.node_to_hir_id(ty.id)));
193 if match_def_path(cx.tcx, did, path);
201 /// Recursively check for `TypePass` lints in the given type. Stop at the first
204 /// The parameter `is_local` distinguishes the context of the type; types from
205 /// local bindings should only be checked for the `BORROWED_BOX` lint.
206 fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
207 if in_macro(ast_ty.span) {
211 TyKind::Path(ref qpath) if !is_local => {
212 let hir_id = cx.tcx.hir.node_to_hir_id(ast_ty.id);
213 let def = cx.tables.qpath_def(qpath, hir_id);
214 if let Some(def_id) = opt_def_id(def) {
215 if Some(def_id) == cx.tcx.lang_items().owned_box() {
216 if match_type_parameter(cx, qpath, &paths::VEC) {
221 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
222 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
224 return; // don't recurse into the type
226 } else if match_def_path(cx.tcx, def_id, &paths::OPTION) {
227 if match_type_parameter(cx, qpath, &paths::OPTION) {
232 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
233 enum if you need to distinguish all 3 cases",
235 return; // don't recurse into the type
237 } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
242 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
243 "a VecDeque might work",
245 return; // don't recurse into the type
249 QPath::Resolved(Some(ref ty), ref p) => {
250 check_ty(cx, ty, is_local);
251 for ty in p.segments.iter().flat_map(|seg| {
254 .map_or_else(|| [].iter(), |params| params.args.iter())
255 .filter_map(|arg| match arg {
256 GenericArg::Type(ty) => Some(ty),
257 GenericArg::Lifetime(_) => None,
260 check_ty(cx, ty, is_local);
263 QPath::Resolved(None, ref p) => for ty in p.segments.iter().flat_map(|seg| {
266 .map_or_else(|| [].iter(), |params| params.args.iter())
267 .filter_map(|arg| match arg {
268 GenericArg::Type(ty) => Some(ty),
269 GenericArg::Lifetime(_) => None,
272 check_ty(cx, ty, is_local);
274 QPath::TypeRelative(ref ty, ref seg) => {
275 check_ty(cx, ty, is_local);
276 if let Some(ref params) = seg.args {
277 for ty in params.args.iter().filter_map(|arg| match arg {
278 GenericArg::Type(ty) => Some(ty),
279 GenericArg::Lifetime(_) => None,
281 check_ty(cx, ty, is_local);
287 TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, ast_ty, is_local, lt, mut_ty),
289 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
290 TyKind::Tup(ref tys) => for ty in tys {
291 check_ty(cx, ty, is_local);
297 fn check_ty_rptr(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool, lt: &Lifetime, mut_ty: &MutTy) {
298 match mut_ty.ty.node {
299 TyKind::Path(ref qpath) => {
300 let hir_id = cx.tcx.hir.node_to_hir_id(mut_ty.ty.id);
301 let def = cx.tables.qpath_def(qpath, hir_id);
303 if let Some(def_id) = opt_def_id(def);
304 if Some(def_id) == cx.tcx.lang_items().owned_box();
305 if let QPath::Resolved(None, ref path) = *qpath;
306 if let [ref bx] = *path.segments;
307 if let Some(ref params) = bx.args;
308 if !params.parenthesized;
309 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
310 GenericArg::Type(ty) => Some(ty),
311 GenericArg::Lifetime(_) => None,
314 if is_any_trait(inner) {
315 // Ignore `Box<Any>` types, see #1884 for details.
319 let ltopt = if lt.is_elided() {
322 format!("{} ", lt.name.ident().name.as_str())
324 let mutopt = if mut_ty.mutbl == Mutability::MutMutable {
329 span_lint_and_sugg(cx,
332 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
334 format!("&{}{}{}", ltopt, mutopt, &snippet(cx, inner.span, ".."))
336 return; // don't recurse into the type
339 check_ty(cx, &mut_ty.ty, is_local);
341 _ => check_ty(cx, &mut_ty.ty, is_local),
345 // Returns true if given type is `Any` trait.
346 fn is_any_trait(t: &hir::Ty) -> bool {
348 if let TyKind::TraitObject(ref traits, _) = t.node;
349 if traits.len() >= 1;
350 // Only Send/Sync can be used as additional traits, so it is enough to
351 // check only the first trait.
352 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
361 #[allow(missing_copy_implementations)]
364 /// **What it does:** Checks for binding a unit value.
366 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
367 /// binding one is kind of pointless.
369 /// **Known problems:** None.
375 declare_clippy_lint! {
378 "creating a let binding to a value of unit type, which usually can't be used afterwards"
381 fn check_let_unit(cx: &LateContext, decl: &Decl) {
382 if let DeclKind::Local(ref local) = decl.node {
383 if is_unit(cx.tables.pat_ty(&local.pat)) {
384 if in_external_macro(cx, decl.span) || in_macro(local.pat.span) {
387 if higher::is_from_for_desugar(decl) {
395 "this let-binding has unit value. Consider omitting `let {} =`",
396 snippet(cx, local.pat.span, "..")
403 impl LintPass for LetPass {
404 fn get_lints(&self) -> LintArray {
405 lint_array!(LET_UNIT_VALUE)
409 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
410 fn check_decl(&mut self, cx: &LateContext<'a, 'tcx>, decl: &'tcx Decl) {
411 check_let_unit(cx, decl)
415 /// **What it does:** Checks for comparisons to unit.
417 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
418 /// clumsily written constant. Mostly this happens when someone accidentally
419 /// adds semicolons at the end of the operands.
421 /// **Known problems:** None.
425 /// if { foo(); } == { bar(); } { baz(); }
429 /// { foo(); bar(); baz(); }
431 declare_clippy_lint! {
434 "comparing unit values"
437 #[allow(missing_copy_implementations)]
440 impl LintPass for UnitCmp {
441 fn get_lints(&self) -> LintArray {
442 lint_array!(UNIT_CMP)
446 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
447 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
448 if in_macro(expr.span) {
451 if let ExprKind::Binary(ref cmp, ref left, _) = expr.node {
453 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
454 let result = match op {
455 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
463 "{}-comparison of unit values detected. This will always be {}",
473 /// **What it does:** Checks for passing a unit value as an argument to a function without using a unit literal (`()`).
475 /// **Why is this bad?** This is likely the result of an accidental semicolon.
477 /// **Known problems:** None.
486 declare_clippy_lint! {
489 "passing unit to a function"
494 impl LintPass for UnitArg {
495 fn get_lints(&self) -> LintArray {
496 lint_array!(UNIT_ARG)
500 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
501 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
502 if in_macro(expr.span) {
506 ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
508 if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
509 let map = &cx.tcx.hir;
510 // apparently stuff in the desugaring of `?` can trigger this
511 // so check for that here
512 // only the calls to `Try::from_error` is marked as desugared,
513 // so we need to check both the current Expr and its parent.
514 if !is_questionmark_desugar_marked_call(expr) {
516 let opt_parent_node = map.find(map.get_parent_node(expr.id));
517 if let Some(hir::map::NodeExpr(parent_expr)) = opt_parent_node;
518 if is_questionmark_desugar_marked_call(parent_expr);
521 // `expr` and `parent_expr` where _both_ not from
522 // desugaring `?`, so lint
527 "passing a unit value to a function",
528 "if you intended to pass a unit value, use a unit literal instead",
542 fn is_questionmark_desugar_marked_call(expr: &Expr) -> bool {
543 use syntax_pos::hygiene::CompilerDesugaringKind;
544 if let ExprKind::Call(ref callee, _) = expr.node {
545 callee.span.is_compiler_desugaring(CompilerDesugaringKind::QuestionMark)
551 fn is_unit(ty: Ty) -> bool {
553 ty::TyTuple(slice) if slice.is_empty() => true,
558 fn is_unit_literal(expr: &Expr) -> bool {
560 ExprKind::Tup(ref slice) if slice.is_empty() => true,
567 /// **What it does:** Checks for casts from any numerical to a float type where
568 /// the receiving type cannot store all values from the original type without
569 /// rounding errors. This possible rounding is to be expected, so this lint is
570 /// `Allow` by default.
572 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
573 /// or any 64-bit integer to `f64`.
575 /// **Why is this bad?** It's not bad at all. But in some applications it can be
576 /// helpful to know where precision loss can take place. This lint can help find
577 /// those places in the code.
579 /// **Known problems:** None.
583 /// let x = u64::MAX; x as f64
585 declare_clippy_lint! {
586 pub CAST_PRECISION_LOSS,
588 "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
591 /// **What it does:** Checks for casts from a signed to an unsigned numerical
592 /// type. In this case, negative values wrap around to large positive values,
593 /// which can be quite surprising in practice. However, as the cast works as
594 /// defined, this lint is `Allow` by default.
596 /// **Why is this bad?** Possibly surprising results. You can activate this lint
597 /// as a one-time check to see where numerical wrapping can arise.
599 /// **Known problems:** None.
604 /// y as u128 // will return 18446744073709551615
606 declare_clippy_lint! {
609 "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
612 /// **What it does:** Checks for on casts between numerical types that may
613 /// truncate large values. This is expected behavior, so the cast is `Allow` by
616 /// **Why is this bad?** In some problem domains, it is good practice to avoid
617 /// truncation. This lint can be activated to help assess where additional
618 /// checks could be beneficial.
620 /// **Known problems:** None.
624 /// fn as_u8(x: u64) -> u8 { x as u8 }
626 declare_clippy_lint! {
627 pub CAST_POSSIBLE_TRUNCATION,
629 "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, \
630 or `x as i32` where `x: f32`"
633 /// **What it does:** Checks for casts from an unsigned type to a signed type of
634 /// the same size. Performing such a cast is a 'no-op' for the compiler,
635 /// i.e. nothing is changed at the bit level, and the binary representation of
636 /// the value is reinterpreted. This can cause wrapping if the value is too big
637 /// for the target signed type. However, the cast works as defined, so this lint
638 /// is `Allow` by default.
640 /// **Why is this bad?** While such a cast is not bad in itself, the results can
641 /// be surprising when this is not the intended behavior, as demonstrated by the
644 /// **Known problems:** None.
648 /// u32::MAX as i32 // will yield a value of `-1`
650 declare_clippy_lint! {
651 pub CAST_POSSIBLE_WRAP,
653 "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` \
657 /// **What it does:** Checks for on casts between numerical types that may
658 /// be replaced by safe conversion functions.
660 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
661 /// conversions, including silently lossy conversions. Conversion functions such
662 /// as `i32::from` will only perform lossless conversions. Using the conversion
663 /// functions prevents conversions from turning into silent lossy conversions if
664 /// the types of the input expressions ever change, and make it easier for
665 /// people reading the code to know that the conversion is lossless.
667 /// **Known problems:** None.
671 /// fn as_u64(x: u8) -> u64 { x as u64 }
674 /// Using `::from` would look like this:
677 /// fn as_u64(x: u8) -> u64 { u64::from(x) }
679 declare_clippy_lint! {
682 "casts using `as` that are known to be lossless, e.g. `x as u64` where `x: u8`"
685 /// **What it does:** Checks for casts to the same type.
687 /// **Why is this bad?** It's just unnecessary.
689 /// **Known problems:** None.
693 /// let _ = 2i32 as i32
695 declare_clippy_lint! {
696 pub UNNECESSARY_CAST,
698 "cast to the same type, e.g. `x as i32` where `x: i32`"
701 /// **What it does:** Checks for casts of a function pointer to a numeric type not enough to store address.
703 /// **Why is this bad?** Casting a function pointer to not eligable type could truncate the address value.
705 /// **Known problems:** None.
709 /// fn test_fn() -> i16;
710 /// let _ = test_fn as i32
712 declare_clippy_lint! {
713 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
715 "cast function pointer to the numeric type with value truncation"
718 /// **What it does:** Checks for casts of a function pointer to a numeric type except `usize`.
720 /// **Why is this bad?** Casting a function pointer to something other than `usize` is not a good style.
722 /// **Known problems:** None.
726 /// fn test_fn() -> i16;
727 /// let _ = test_fn as i128
729 declare_clippy_lint! {
730 pub FN_TO_NUMERIC_CAST,
732 "cast function pointer to the numeric type"
735 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
736 /// more-strictly-aligned pointer
738 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
741 /// **Known problems:** None.
745 /// let _ = (&1u8 as *const u8) as *const u16;
746 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
748 declare_clippy_lint! {
749 pub CAST_PTR_ALIGNMENT,
751 "cast from a pointer to a more-strictly-aligned pointer"
754 /// Returns the size in bits of an integral type.
755 /// Will return 0 if the type is not an int or uint variant
756 fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
758 ty::TyInt(i) => match i {
759 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
766 ty::TyUint(i) => match i {
767 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
778 fn is_isize_or_usize(typ: Ty) -> bool {
780 ty::TyInt(IntTy::Isize) | ty::TyUint(UintTy::Usize) => true,
785 fn span_precision_loss_lint(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to_f64: bool) {
786 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
787 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
788 let arch_dependent_str = "on targets with 64-bit wide pointers ";
789 let from_nbits_str = if arch_dependent {
791 } else if is_isize_or_usize(cast_from) {
792 "32 or 64".to_owned()
794 int_ty_to_nbits(cast_from, cx.tcx).to_string()
801 "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
802 is only {4} bits wide)",
804 if cast_to_f64 { "f64" } else { "f32" },
816 fn should_strip_parens(op: &Expr, snip: &str) -> bool {
817 if let ExprKind::Binary(_, _, _) = op.node {
818 if snip.starts_with('(') && snip.ends_with(')') {
825 fn span_lossless_lint(cx: &LateContext, expr: &Expr, op: &Expr, cast_from: Ty, cast_to: Ty) {
826 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
827 if in_constant(cx, expr.id) { return }
828 // The suggestion is to use a function call, so if the original expression
829 // has parens on the outside, they are no longer needed.
830 let opt = snippet_opt(cx, op.span);
831 let sugg = if let Some(ref snip) = opt {
832 if should_strip_parens(op, snip) {
833 &snip[1..snip.len() - 1]
845 &format!("casting {} to {} may become silently lossy if types change", cast_from, cast_to),
847 format!("{}::from({})", cast_to, sugg),
857 fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, cast_to: Ty) {
858 let arch_64_suffix = " on targets with 64-bit wide pointers";
859 let arch_32_suffix = " on targets with 32-bit wide pointers";
860 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
861 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
862 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
863 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
864 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
865 (true, true) | (false, false) => (
866 to_nbits < from_nbits,
868 to_nbits == from_nbits && cast_unsigned_to_signed,
878 to_nbits <= 32 && cast_unsigned_to_signed,
884 cast_unsigned_to_signed,
885 if from_nbits == 64 {
895 CAST_POSSIBLE_TRUNCATION,
898 "casting {} to {} may truncate the value{}",
901 match suffix_truncation {
902 ArchSuffix::_32 => arch_32_suffix,
903 ArchSuffix::_64 => arch_64_suffix,
904 ArchSuffix::None => "",
915 "casting {} to {} may wrap around the value{}",
919 ArchSuffix::_32 => arch_32_suffix,
920 ArchSuffix::_64 => arch_64_suffix,
921 ArchSuffix::None => "",
928 fn check_lossless(cx: &LateContext, expr: &Expr, op: &Expr, cast_from: Ty, cast_to: Ty) {
929 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
930 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
931 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
932 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
934 span_lossless_lint(cx, expr, op, cast_from, cast_to);
938 impl LintPass for CastPass {
939 fn get_lints(&self) -> LintArray {
943 CAST_POSSIBLE_TRUNCATION,
949 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
954 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
955 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
956 if let ExprKind::Cast(ref ex, _) = expr.node {
957 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
958 if let ExprKind::Lit(ref lit) = ex.node {
959 use syntax::ast::{LitIntType, LitKind};
961 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
962 _ => if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
967 &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
972 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx, expr.span) {
973 match (cast_from.is_integral(), cast_to.is_integral()) {
975 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
976 let to_nbits = if let ty::TyFloat(FloatTy::F32) = cast_to.sty {
981 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
982 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
984 if from_nbits < to_nbits {
985 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
991 CAST_POSSIBLE_TRUNCATION,
993 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
995 if !cast_to.is_signed() {
1000 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1005 if cast_from.is_signed() && !cast_to.is_signed() {
1010 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1013 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1014 check_lossless(cx, expr, ex, cast_from, cast_to);
1017 if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty)
1021 CAST_POSSIBLE_TRUNCATION,
1023 "casting f64 to f32 may truncate the value",
1026 if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty)
1028 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1034 match &cast_from.sty {
1036 ty::TyFnPtr(..) => {
1037 if cast_to.is_numeric() && cast_to.sty != ty::TyUint(UintTy::Usize){
1038 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1039 let pointer_nbits = cx.tcx.data_layout.pointer_size.bits();
1040 if to_nbits < pointer_nbits || (to_nbits == pointer_nbits && cast_to.is_signed()) {
1043 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1045 &format!("casting a `{}` to `{}` may truncate the function address value.", cast_from, cast_to),
1046 "if you need the address of the function, consider",
1047 format!("{} as usize", &snippet(cx, ex.span, "x"))
1054 &format!("casting a `{}` to `{}` is bad style.", cast_from, cast_to),
1055 "if you need the address of the function, consider",
1056 format!("{} as usize", &snippet(cx, ex.span, "x"))
1066 if let ty::TyRawPtr(from_ptr_ty) = &cast_from.sty;
1067 if let ty::TyRawPtr(to_ptr_ty) = &cast_to.sty;
1068 if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi());
1069 if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi());
1070 if from_align < to_align;
1071 // with c_void, we inherently need to trust the user
1073 match_type(cx, from_ptr_ty.ty, &paths::C_VOID)
1074 || match_type(cx, from_ptr_ty.ty, &paths::C_VOID_LIBC)
1081 &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
1089 /// **What it does:** Checks for types used in structs, parameters and `let`
1090 /// declarations above a certain complexity threshold.
1092 /// **Why is this bad?** Too complex types make the code less readable. Consider
1093 /// using a `type` definition to simplify them.
1095 /// **Known problems:** None.
1099 /// struct Foo { inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>> }
1101 declare_clippy_lint! {
1102 pub TYPE_COMPLEXITY,
1104 "usage of very complex types that might be better factored into `type` definitions"
1107 #[allow(missing_copy_implementations)]
1108 pub struct TypeComplexityPass {
1112 impl TypeComplexityPass {
1113 pub fn new(threshold: u64) -> Self {
1120 impl LintPass for TypeComplexityPass {
1121 fn get_lints(&self) -> LintArray {
1122 lint_array!(TYPE_COMPLEXITY)
1126 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
1129 cx: &LateContext<'a, 'tcx>,
1136 self.check_fndecl(cx, decl);
1139 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
1140 // enum variants are also struct fields now
1141 self.check_type(cx, &field.ty);
1144 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1146 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1147 // functions, enums, structs, impls and traits are covered
1152 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
1154 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1155 TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1156 // methods with default impl are covered by check_fn
1161 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
1163 ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
1164 // methods are covered by check_fn
1169 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
1170 if let Some(ref ty) = local.ty {
1171 self.check_type(cx, ty);
1176 impl<'a, 'tcx> TypeComplexityPass {
1177 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
1178 for arg in &decl.inputs {
1179 self.check_type(cx, arg);
1181 if let Return(ref ty) = decl.output {
1182 self.check_type(cx, ty);
1186 fn check_type(&self, cx: &LateContext, ty: &hir::Ty) {
1187 if in_macro(ty.span) {
1191 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1192 visitor.visit_ty(ty);
1196 if score > self.threshold {
1201 "very complex type used. Consider factoring parts into `type` definitions",
1207 /// Walks a type and assigns a complexity score to it.
1208 struct TypeComplexityVisitor {
1209 /// total complexity score of the type
1211 /// current nesting level
1215 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1216 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1217 let (add_score, sub_nest) = match ty.node {
1218 // _, &x and *x have only small overhead; don't mess with nesting level
1219 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1221 // the "normal" components of a type: named types, arrays/tuples
1222 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1224 // function types bring a lot of overhead
1225 TyKind::BareFn(..) => (50 * self.nest, 1),
1227 TyKind::TraitObject(ref param_bounds, _) => {
1228 let has_lifetime_parameters = param_bounds
1230 .any(|bound| bound.bound_generic_params.iter().any(|gen| match gen.kind {
1231 GenericParamKind::Lifetime { .. } => true,
1234 if has_lifetime_parameters {
1235 // complex trait bounds like A<'a, 'b>
1238 // simple trait bounds like A + B
1245 self.score += add_score;
1246 self.nest += sub_nest;
1248 self.nest -= sub_nest;
1250 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1251 NestedVisitorMap::None
1255 /// **What it does:** Checks for expressions where a character literal is cast
1256 /// to `u8` and suggests using a byte literal instead.
1258 /// **Why is this bad?** In general, casting values to smaller types is
1259 /// error-prone and should be avoided where possible. In the particular case of
1260 /// converting a character literal to u8, it is easy to avoid by just using a
1261 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1262 /// than `'a' as u8`.
1264 /// **Known problems:** None.
1271 /// A better version, using the byte literal:
1276 declare_clippy_lint! {
1279 "casting a character literal to u8"
1282 pub struct CharLitAsU8;
1284 impl LintPass for CharLitAsU8 {
1285 fn get_lints(&self) -> LintArray {
1286 lint_array!(CHAR_LIT_AS_U8)
1290 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1291 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1292 use syntax::ast::{LitKind, UintTy};
1294 if let ExprKind::Cast(ref e, _) = expr.node {
1295 if let ExprKind::Lit(ref l) = e.node {
1296 if let LitKind::Char(_) = l.node {
1297 if ty::TyUint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
1298 let msg = "casting character literal to u8. `char`s \
1299 are 4 bytes wide in rust, so casting to u8 \
1301 let help = format!("Consider using a byte literal instead:\nb{}", snippet(cx, e.span, "'x'"));
1302 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
1310 /// **What it does:** Checks for comparisons where one side of the relation is
1311 /// either the minimum or maximum value for its type and warns if it involves a
1312 /// case that is always true or always false. Only integer and boolean types are
1315 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1316 /// that is is possible for `x` to be less than the minimum. Expressions like
1317 /// `max < x` are probably mistakes.
1319 /// **Known problems:** For `usize` the size of the current compile target will
1320 /// be assumed (e.g. 64 bits on 64 bit systems). This means code that uses such
1321 /// a comparison to detect target pointer width will trigger this lint. One can
1322 /// use `mem::sizeof` and compare its value or conditional compilation
1324 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1329 /// 100 > std::i32::MAX
1331 declare_clippy_lint! {
1332 pub ABSURD_EXTREME_COMPARISONS,
1334 "a comparison with a maximum or minimum value that is always true or false"
1337 pub struct AbsurdExtremeComparisons;
1339 impl LintPass for AbsurdExtremeComparisons {
1340 fn get_lints(&self) -> LintArray {
1341 lint_array!(ABSURD_EXTREME_COMPARISONS)
1350 struct ExtremeExpr<'a> {
1355 enum AbsurdComparisonResult {
1358 InequalityImpossible,
1362 fn is_cast_between_fixed_and_target<'a, 'tcx>(
1363 cx: &LateContext<'a, 'tcx>,
1367 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1368 let precast_ty = cx.tables.expr_ty(cast_exp);
1369 let cast_ty = cx.tables.expr_ty(expr);
1371 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty)
1377 fn detect_absurd_comparison<'a, 'tcx>(
1378 cx: &LateContext<'a, 'tcx>,
1382 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1383 use crate::types::ExtremeType::*;
1384 use crate::types::AbsurdComparisonResult::*;
1385 use crate::utils::comparisons::*;
1387 // absurd comparison only makes sense on primitive types
1388 // primitive types don't implement comparison operators with each other
1389 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1393 // comparisons between fix sized types and target sized types are considered unanalyzable
1394 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1398 let normalized = normalize_comparison(op, lhs, rhs);
1399 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1405 let lx = detect_extreme_expr(cx, normalized_lhs);
1406 let rx = detect_extreme_expr(cx, normalized_rhs);
1411 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1412 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1418 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1419 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1420 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1421 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1425 Rel::Ne | Rel::Eq => return None,
1429 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<ExtremeExpr<'tcx>> {
1430 use crate::types::ExtremeType::*;
1432 let ty = cx.tables.expr_ty(expr);
1434 let cv = constant(cx, cx.tables, expr)?.0;
1436 let which = match (&ty.sty, cv) {
1437 (&ty::TyBool, Constant::Bool(false)) |
1438 (&ty::TyUint(_), Constant::Int(0)) => Minimum,
1439 (&ty::TyInt(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Minimum,
1441 (&ty::TyBool, Constant::Bool(true)) => Maximum,
1442 (&ty::TyInt(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) => Maximum,
1443 (&ty::TyUint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1453 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1454 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1455 use crate::types::ExtremeType::*;
1456 use crate::types::AbsurdComparisonResult::*;
1458 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1459 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1460 if !in_macro(expr.span) {
1461 let msg = "this comparison involving the minimum or maximum element for this \
1462 type contains a case that is always true or always false";
1464 let conclusion = match result {
1465 AlwaysFalse => "this comparison is always false".to_owned(),
1466 AlwaysTrue => "this comparison is always true".to_owned(),
1467 InequalityImpossible => format!(
1468 "the case where the two sides are not equal never occurs, consider using {} == {} \
1470 snippet(cx, lhs.span, "lhs"),
1471 snippet(cx, rhs.span, "rhs")
1476 "because {} is the {} value for this type, {}",
1477 snippet(cx, culprit.expr.span, "x"),
1478 match culprit.which {
1479 Minimum => "minimum",
1480 Maximum => "maximum",
1485 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1492 /// **What it does:** Checks for comparisons where the relation is always either
1493 /// true or false, but where one side has been upcast so that the comparison is
1494 /// necessary. Only integer types are checked.
1496 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1497 /// will mistakenly imply that it is possible for `x` to be outside the range of
1500 /// **Known problems:**
1501 /// https://github.com/rust-lang-nursery/rust-clippy/issues/886
1505 /// let x : u8 = ...; (x as u32) > 300
1507 declare_clippy_lint! {
1508 pub INVALID_UPCAST_COMPARISONS,
1510 "a comparison involving an upcast which is always true or false"
1513 pub struct InvalidUpcastComparisons;
1515 impl LintPass for InvalidUpcastComparisons {
1516 fn get_lints(&self) -> LintArray {
1517 lint_array!(INVALID_UPCAST_COMPARISONS)
1521 #[derive(Copy, Clone, Debug, Eq)]
1528 #[allow(cast_sign_loss)]
1529 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1532 } else if u > (i128::max_value() as u128) {
1540 impl PartialEq for FullInt {
1541 fn eq(&self, other: &Self) -> bool {
1542 self.partial_cmp(other)
1543 .expect("partial_cmp only returns Some(_)") == Ordering::Equal
1547 impl PartialOrd for FullInt {
1548 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1549 Some(match (self, other) {
1550 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1551 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1552 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1553 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1557 impl Ord for FullInt {
1558 fn cmp(&self, other: &Self) -> Ordering {
1559 self.partial_cmp(other)
1560 .expect("partial_cmp for FullInt can never return None")
1565 fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1566 use syntax::ast::{IntTy, UintTy};
1569 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1570 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1571 let cast_ty = cx.tables.expr_ty(expr);
1572 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1573 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1576 match pre_cast_ty.sty {
1577 ty::TyInt(int_ty) => Some(match int_ty {
1578 IntTy::I8 => (FullInt::S(i128::from(i8::min_value())), FullInt::S(i128::from(i8::max_value()))),
1580 FullInt::S(i128::from(i16::min_value())),
1581 FullInt::S(i128::from(i16::max_value())),
1584 FullInt::S(i128::from(i32::min_value())),
1585 FullInt::S(i128::from(i32::max_value())),
1588 FullInt::S(i128::from(i64::min_value())),
1589 FullInt::S(i128::from(i64::max_value())),
1591 IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
1592 IntTy::Isize => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
1594 ty::TyUint(uint_ty) => Some(match uint_ty {
1595 UintTy::U8 => (FullInt::U(u128::from(u8::min_value())), FullInt::U(u128::from(u8::max_value()))),
1597 FullInt::U(u128::from(u16::min_value())),
1598 FullInt::U(u128::from(u16::max_value())),
1601 FullInt::U(u128::from(u32::min_value())),
1602 FullInt::U(u128::from(u32::max_value())),
1605 FullInt::U(u128::from(u64::min_value())),
1606 FullInt::U(u128::from(u64::max_value())),
1608 UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
1609 UintTy::Usize => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
1618 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<FullInt> {
1619 let val = constant(cx, cx.tables, expr)?.0;
1620 if let Constant::Int(const_int) = val {
1621 match cx.tables.expr_ty(expr).sty {
1622 ty::TyInt(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1623 ty::TyUint(_) => Some(FullInt::U(const_int)),
1631 fn err_upcast_comparison(cx: &LateContext, span: Span, expr: &Expr, always: bool) {
1632 if let ExprKind::Cast(ref cast_val, _) = expr.node {
1635 INVALID_UPCAST_COMPARISONS,
1638 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1639 snippet(cx, cast_val.span, "the expression"),
1640 if always { "true" } else { "false" },
1646 fn upcast_comparison_bounds_err<'a, 'tcx>(
1647 cx: &LateContext<'a, 'tcx>,
1649 rel: comparisons::Rel,
1650 lhs_bounds: Option<(FullInt, FullInt)>,
1655 use crate::utils::comparisons::*;
1657 if let Some((lb, ub)) = lhs_bounds {
1658 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1659 if rel == Rel::Eq || rel == Rel::Ne {
1660 if norm_rhs_val < lb || norm_rhs_val > ub {
1661 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1663 } else if match rel {
1664 Rel::Lt => if invert {
1669 Rel::Le => if invert {
1674 Rel::Eq | Rel::Ne => unreachable!(),
1676 err_upcast_comparison(cx, span, lhs, true)
1677 } else if match rel {
1678 Rel::Lt => if invert {
1683 Rel::Le => if invert {
1688 Rel::Eq | Rel::Ne => unreachable!(),
1690 err_upcast_comparison(cx, span, lhs, false)
1696 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1697 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1698 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1699 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1700 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1706 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1707 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1709 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1710 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1715 /// **What it does:** Checks for public `impl` or `fn` missing generalization
1716 /// over different hashers and implicitly defaulting to the default hashing
1717 /// algorithm (SipHash).
1719 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
1722 /// **Known problems:** Suggestions for replacing constructors can contain
1723 /// false-positives. Also applying suggestions can require modification of other
1724 /// pieces of code, possibly including external crates.
1728 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { ... }
1730 /// pub foo(map: &mut HashMap<i32, i32>) { .. }
1732 declare_clippy_lint! {
1733 pub IMPLICIT_HASHER,
1735 "missing generalization over different hashers"
1738 pub struct ImplicitHasher;
1740 impl LintPass for ImplicitHasher {
1741 fn get_lints(&self) -> LintArray {
1742 lint_array!(IMPLICIT_HASHER)
1746 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
1747 #[allow(cast_possible_truncation)]
1748 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1749 use syntax_pos::BytePos;
1751 fn suggestion<'a, 'tcx>(
1752 cx: &LateContext<'a, 'tcx>,
1753 db: &mut DiagnosticBuilder,
1754 generics_span: Span,
1755 generics_suggestion_span: Span,
1756 target: &ImplicitHasherType,
1757 vis: ImplicitHasherConstructorVisitor,
1759 let generics_snip = snippet(cx, generics_span, "");
1761 let generics_snip = if generics_snip.is_empty() {
1764 &generics_snip[1..generics_snip.len() - 1]
1769 "consider adding a type parameter".to_string(),
1772 generics_suggestion_span,
1774 "<{}{}S: ::std::hash::BuildHasher{}>",
1776 if generics_snip.is_empty() { "" } else { ", " },
1777 if vis.suggestions.is_empty() {
1780 // request users to add `Default` bound so that generic constructors can be used
1787 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
1792 if !vis.suggestions.is_empty() {
1793 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
1797 if !cx.access_levels.is_exported(item.id) {
1802 ItemKind::Impl(_, _, _, ref generics, _, ref ty, ref items) => {
1803 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1806 for target in &vis.found {
1807 if differing_macro_contexts(item.span, target.span()) {
1811 let generics_suggestion_span = generics.span.substitute_dummy({
1812 let pos = snippet_opt(cx, item.span.until(target.span()))
1813 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)))
1814 .expect("failed to create span for type arguments");
1815 Span::new(pos, pos, item.span.data().ctxt)
1818 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1819 for item in items.iter().map(|item| cx.tcx.hir.impl_item(item.id)) {
1820 ctr_vis.visit_impl_item(item);
1827 &format!("impl for `{}` should be generalized over different hashers", target.type_name()),
1829 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1834 ItemKind::Fn(ref decl, .., ref generics, body_id) => {
1835 let body = cx.tcx.hir.body(body_id);
1837 for ty in &decl.inputs {
1838 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1841 for target in &vis.found {
1842 let generics_suggestion_span = generics.span.substitute_dummy({
1843 let pos = snippet_opt(cx, item.span.until(body.arguments[0].pat.span))
1845 let i = snip.find("fn")?;
1846 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
1848 .expect("failed to create span for type parameters");
1849 Span::new(pos, pos, item.span.data().ctxt)
1852 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1853 ctr_vis.visit_body(body);
1860 "parameter of type `{}` should be generalized over different hashers",
1864 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
1875 enum ImplicitHasherType<'tcx> {
1876 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
1877 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
1880 impl<'tcx> ImplicitHasherType<'tcx> {
1881 /// Checks that `ty` is a target type without a BuildHasher.
1882 fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
1883 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.node {
1884 let params: Vec<_> = path.segments.last().as_ref()?.args.as_ref()?
1885 .args.iter().filter_map(|arg| match arg {
1886 GenericArg::Type(ty) => Some(ty),
1887 GenericArg::Lifetime(_) => None,
1889 let params_len = params.len();
1891 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1893 if match_path(path, &paths::HASHMAP) && params_len == 2 {
1894 Some(ImplicitHasherType::HashMap(
1897 snippet(cx, params[0].span, "K"),
1898 snippet(cx, params[1].span, "V"),
1900 } else if match_path(path, &paths::HASHSET) && params_len == 1 {
1901 Some(ImplicitHasherType::HashSet(hir_ty.span, ty, snippet(cx, params[0].span, "T")))
1910 fn type_name(&self) -> &'static str {
1912 ImplicitHasherType::HashMap(..) => "HashMap",
1913 ImplicitHasherType::HashSet(..) => "HashSet",
1917 fn type_arguments(&self) -> String {
1919 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
1920 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
1924 fn ty(&self) -> Ty<'tcx> {
1926 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
1930 fn span(&self) -> Span {
1932 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
1937 struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
1938 cx: &'a LateContext<'a, 'tcx>,
1939 found: Vec<ImplicitHasherType<'tcx>>,
1942 impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
1943 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
1944 Self { cx, found: vec![] }
1948 impl<'a, 'tcx: 'a> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
1949 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1950 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
1951 self.found.push(target);
1957 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1958 NestedVisitorMap::None
1962 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
1963 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx: 'a + 'b> {
1964 cx: &'a LateContext<'a, 'tcx>,
1965 body: &'a TypeckTables<'tcx>,
1966 target: &'b ImplicitHasherType<'tcx>,
1967 suggestions: BTreeMap<Span, String>,
1970 impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1971 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
1976 suggestions: BTreeMap::new(),
1981 impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
1982 fn visit_body(&mut self, body: &'tcx Body) {
1983 self.body = self.cx.tcx.body_tables(body.id());
1984 walk_body(self, body);
1987 fn visit_expr(&mut self, e: &'tcx Expr) {
1989 if let ExprKind::Call(ref fun, ref args) = e.node;
1990 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.node;
1991 if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.node;
1993 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
1997 if match_path(ty_path, &paths::HASHMAP) {
1998 if method.ident.name == "new" {
2000 .insert(e.span, "HashMap::default()".to_string());
2001 } else if method.ident.name == "with_capacity" {
2002 self.suggestions.insert(
2005 "HashMap::with_capacity_and_hasher({}, Default::default())",
2006 snippet(self.cx, args[0].span, "capacity"),
2010 } else if match_path(ty_path, &paths::HASHSET) {
2011 if method.ident.name == "new" {
2013 .insert(e.span, "HashSet::default()".to_string());
2014 } else if method.ident.name == "with_capacity" {
2015 self.suggestions.insert(
2018 "HashSet::with_capacity_and_hasher({}, Default::default())",
2019 snippet(self.cx, args[0].span, "capacity"),
2030 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2031 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)