1 #![allow(clippy::default_hash_types)]
3 use crate::consts::{constant, Constant};
4 use crate::reexport::*;
5 use crate::utils::paths;
7 clip, comparisons, differing_macro_contexts, higher, in_constant, in_macro, int_bits, last_path_segment,
8 match_def_path, match_path, multispan_sugg, opt_def_id, same_tys, sext, snippet, snippet_opt,
9 snippet_with_applicability, span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then, unsext,
12 use if_chain::if_chain;
14 use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
16 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
17 use rustc::ty::layout::LayoutOf;
18 use rustc::ty::{self, Ty, TyCtxt, TypeckTables};
19 use rustc::{declare_tool_lint, lint_array};
20 use rustc_errors::Applicability;
21 use rustc_target::spec::abi::Abi;
22 use rustc_typeck::hir_ty_to_ty;
24 use std::cmp::Ordering;
25 use std::collections::BTreeMap;
26 use syntax::ast::{FloatTy, IntTy, UintTy};
27 use syntax::errors::DiagnosticBuilder;
28 use syntax::source_map::Span;
30 /// Handles all the linting of funky types
33 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
35 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
36 /// the heap. So if you `Box` it, you just add another level of indirection
37 /// without any benefit whatsoever.
39 /// **Known problems:** None.
44 /// values: Box<Vec<Foo>>,
55 declare_clippy_lint! {
58 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
61 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
63 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
64 /// the heap. So if you `Box` its contents, you just add another level of indirection.
66 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
72 /// values: Vec<Box<i32>>,
83 declare_clippy_lint! {
86 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
89 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
92 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
93 /// represents an optional optional value which is logically the same thing as an optional
94 /// value but has an unneeded extra level of wrapping.
96 /// **Known problems:** None.
100 /// fn x() -> Option<Option<u32>> {
103 declare_clippy_lint! {
106 "usage of `Option<Option<T>>`"
109 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
110 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
112 /// **Why is this bad?** Gankro says:
114 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
115 /// pointers and indirection.
116 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
118 /// > "only" amortized for push/pop, should be faster in the general case for
119 /// almost every possible
120 /// > workload, and isn't even amortized at all if you can predict the capacity
123 /// > `LinkedList`s are only really good if you're doing a lot of merging or
124 /// splitting of lists.
125 /// > This is because they can just mangle some pointers instead of actually
126 /// copying the data. Even
127 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
128 /// can still be better
129 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
131 /// **Known problems:** False positives – the instances where using a
132 /// `LinkedList` makes sense are few and far between, but they can still happen.
136 /// let x = LinkedList::new();
138 declare_clippy_lint! {
141 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a VecDeque"
144 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
146 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
149 /// **Known problems:** None.
153 /// fn foo(bar: &Box<T>) { ... }
159 /// fn foo(bar: &T) { ... }
161 declare_clippy_lint! {
164 "a borrow of a boxed type"
167 impl LintPass for TypePass {
168 fn get_lints(&self) -> LintArray {
169 lint_array!(BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
173 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
174 fn check_fn(&mut self, cx: &LateContext<'_, '_>, _: FnKind<'_>, decl: &FnDecl, _: &Body, _: Span, id: NodeId) {
175 // skip trait implementations, see #605
176 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent(id)) {
177 if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
182 check_fn_decl(cx, decl);
185 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &StructField) {
186 check_ty(cx, &field.ty, false);
189 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &TraitItem) {
191 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
192 TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
197 fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local) {
198 if let Some(ref ty) = local.ty {
199 check_ty(cx, ty, true);
204 fn check_fn_decl(cx: &LateContext<'_, '_>, decl: &FnDecl) {
205 for input in &decl.inputs {
206 check_ty(cx, input, false);
209 if let FunctionRetTy::Return(ref ty) = decl.output {
210 check_ty(cx, ty, false);
214 /// Check if `qpath` has last segment with type parameter matching `path`
215 fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath, path: &[&str]) -> bool {
216 let last = last_path_segment(qpath);
218 if let Some(ref params) = last.args;
219 if !params.parenthesized;
220 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
221 GenericArg::Type(ty) => Some(ty),
222 GenericArg::Lifetime(_) => None,
224 if let TyKind::Path(ref qpath) = ty.node;
225 if let Some(did) = opt_def_id(cx.tables.qpath_def(qpath, cx.tcx.hir().node_to_hir_id(ty.id)));
226 if match_def_path(cx.tcx, did, path);
234 /// Recursively check for `TypePass` lints in the given type. Stop at the first
237 /// The parameter `is_local` distinguishes the context of the type; types from
238 /// local bindings should only be checked for the `BORROWED_BOX` lint.
239 fn check_ty(cx: &LateContext<'_, '_>, ast_ty: &hir::Ty, is_local: bool) {
240 if in_macro(ast_ty.span) {
244 TyKind::Path(ref qpath) if !is_local => {
245 let hir_id = cx.tcx.hir().node_to_hir_id(ast_ty.id);
246 let def = cx.tables.qpath_def(qpath, hir_id);
247 if let Some(def_id) = opt_def_id(def) {
248 if Some(def_id) == cx.tcx.lang_items().owned_box() {
249 if match_type_parameter(cx, qpath, &paths::VEC) {
254 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
255 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
257 return; // don't recurse into the type
259 } else if match_def_path(cx.tcx, def_id, &paths::VEC) {
261 // Get the _ part of Vec<_>
262 if let Some(ref last) = last_path_segment(qpath).args;
263 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
264 GenericArg::Type(ty) => Some(ty),
265 GenericArg::Lifetime(_) => None,
267 // ty is now _ at this point
268 if let TyKind::Path(ref ty_qpath) = ty.node;
269 let def = cx.tables.qpath_def(ty_qpath, ty.hir_id);
270 if let Some(def_id) = opt_def_id(def);
271 if Some(def_id) == cx.tcx.lang_items().owned_box();
272 // At this point, we know ty is Box<T>, now get T
273 if let Some(ref last) = last_path_segment(ty_qpath).args;
274 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
275 GenericArg::Type(ty) => Some(ty),
276 GenericArg::Lifetime(_) => None,
278 if let TyKind::Path(ref ty_qpath) = ty.node;
279 let def = cx.tables.qpath_def(ty_qpath, ty.hir_id);
280 if let Some(def_id) = opt_def_id(def);
281 let boxed_type = cx.tcx.type_of(def_id);
282 if boxed_type.is_sized(cx.tcx.at(ty.span), cx.param_env);
288 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
290 format!("Vec<{}>", boxed_type),
291 Applicability::MaybeIncorrect,
293 return; // don't recurse into the type
296 } else if match_def_path(cx.tcx, def_id, &paths::OPTION) {
297 if match_type_parameter(cx, qpath, &paths::OPTION) {
302 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
303 enum if you need to distinguish all 3 cases",
305 return; // don't recurse into the type
307 } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
312 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
313 "a VecDeque might work",
315 return; // don't recurse into the type
319 QPath::Resolved(Some(ref ty), ref p) => {
320 check_ty(cx, ty, is_local);
321 for ty in p.segments.iter().flat_map(|seg| {
324 .map_or_else(|| [].iter(), |params| params.args.iter())
325 .filter_map(|arg| match arg {
326 GenericArg::Type(ty) => Some(ty),
327 GenericArg::Lifetime(_) => None,
330 check_ty(cx, ty, is_local);
333 QPath::Resolved(None, ref p) => {
334 for ty in p.segments.iter().flat_map(|seg| {
337 .map_or_else(|| [].iter(), |params| params.args.iter())
338 .filter_map(|arg| match arg {
339 GenericArg::Type(ty) => Some(ty),
340 GenericArg::Lifetime(_) => None,
343 check_ty(cx, ty, is_local);
346 QPath::TypeRelative(ref ty, ref seg) => {
347 check_ty(cx, ty, is_local);
348 if let Some(ref params) = seg.args {
349 for ty in params.args.iter().filter_map(|arg| match arg {
350 GenericArg::Type(ty) => Some(ty),
351 GenericArg::Lifetime(_) => None,
353 check_ty(cx, ty, is_local);
359 TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, ast_ty, is_local, lt, mut_ty),
361 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
362 check_ty(cx, ty, is_local)
364 TyKind::Tup(ref tys) => {
366 check_ty(cx, ty, is_local);
373 fn check_ty_rptr(cx: &LateContext<'_, '_>, ast_ty: &hir::Ty, is_local: bool, lt: &Lifetime, mut_ty: &MutTy) {
374 match mut_ty.ty.node {
375 TyKind::Path(ref qpath) => {
376 let hir_id = cx.tcx.hir().node_to_hir_id(mut_ty.ty.id);
377 let def = cx.tables.qpath_def(qpath, hir_id);
379 if let Some(def_id) = opt_def_id(def);
380 if Some(def_id) == cx.tcx.lang_items().owned_box();
381 if let QPath::Resolved(None, ref path) = *qpath;
382 if let [ref bx] = *path.segments;
383 if let Some(ref params) = bx.args;
384 if !params.parenthesized;
385 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
386 GenericArg::Type(ty) => Some(ty),
387 GenericArg::Lifetime(_) => None,
390 if is_any_trait(inner) {
391 // Ignore `Box<Any>` types, see #1884 for details.
395 let ltopt = if lt.is_elided() {
398 format!("{} ", lt.name.ident().as_str())
400 let mutopt = if mut_ty.mutbl == Mutability::MutMutable {
405 let mut applicability = Applicability::MachineApplicable;
410 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
416 &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
418 Applicability::Unspecified,
420 return; // don't recurse into the type
423 check_ty(cx, &mut_ty.ty, is_local);
425 _ => check_ty(cx, &mut_ty.ty, is_local),
429 // Returns true if given type is `Any` trait.
430 fn is_any_trait(t: &hir::Ty) -> bool {
432 if let TyKind::TraitObject(ref traits, _) = t.node;
433 if traits.len() >= 1;
434 // Only Send/Sync can be used as additional traits, so it is enough to
435 // check only the first trait.
436 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
447 /// **What it does:** Checks for binding a unit value.
449 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
450 /// binding one is kind of pointless.
452 /// **Known problems:** None.
460 declare_clippy_lint! {
463 "creating a let binding to a value of unit type, which usually can't be used afterwards"
466 impl LintPass for LetPass {
467 fn get_lints(&self) -> LintArray {
468 lint_array!(LET_UNIT_VALUE)
472 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
473 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
474 if let StmtKind::Local(ref local) = stmt.node {
475 if is_unit(cx.tables.pat_ty(&local.pat)) {
476 if in_external_macro(cx.sess(), stmt.span) || in_macro(local.pat.span) {
479 if higher::is_from_for_desugar(local) {
487 "this let-binding has unit value. Consider omitting `let {} =`",
488 snippet(cx, local.pat.span, "..")
496 /// **What it does:** Checks for comparisons to unit.
498 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
499 /// clumsily written constant. Mostly this happens when someone accidentally
500 /// adds semicolons at the end of the operands.
502 /// **Known problems:** None.
522 declare_clippy_lint! {
525 "comparing unit values"
530 impl LintPass for UnitCmp {
531 fn get_lints(&self) -> LintArray {
532 lint_array!(UNIT_CMP)
536 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
537 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
538 if in_macro(expr.span) {
541 if let ExprKind::Binary(ref cmp, ref left, _) = expr.node {
543 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
544 let result = match op {
545 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
553 "{}-comparison of unit values detected. This will always be {}",
563 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
564 /// unit literal (`()`).
566 /// **Why is this bad?** This is likely the result of an accidental semicolon.
568 /// **Known problems:** None.
577 declare_clippy_lint! {
580 "passing unit to a function"
585 impl LintPass for UnitArg {
586 fn get_lints(&self) -> LintArray {
587 lint_array!(UNIT_ARG)
591 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
592 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
593 if in_macro(expr.span) {
597 ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
599 if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
600 let map = &cx.tcx.hir();
601 // apparently stuff in the desugaring of `?` can trigger this
602 // so check for that here
603 // only the calls to `Try::from_error` is marked as desugared,
604 // so we need to check both the current Expr and its parent.
605 if !is_questionmark_desugar_marked_call(expr) {
607 let opt_parent_node = map.find(map.get_parent_node(expr.id));
608 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
609 if is_questionmark_desugar_marked_call(parent_expr);
612 // `expr` and `parent_expr` where _both_ not from
613 // desugaring `?`, so lint
618 "passing a unit value to a function",
619 "if you intended to pass a unit value, use a unit literal instead",
621 Applicability::MachineApplicable,
634 fn is_questionmark_desugar_marked_call(expr: &Expr) -> bool {
635 use syntax_pos::hygiene::CompilerDesugaringKind;
636 if let ExprKind::Call(ref callee, _) = expr.node {
637 callee.span.is_compiler_desugaring(CompilerDesugaringKind::QuestionMark)
643 fn is_unit(ty: Ty<'_>) -> bool {
645 ty::Tuple(slice) if slice.is_empty() => true,
650 fn is_unit_literal(expr: &Expr) -> bool {
652 ExprKind::Tup(ref slice) if slice.is_empty() => true,
659 /// **What it does:** Checks for casts from any numerical to a float type where
660 /// the receiving type cannot store all values from the original type without
661 /// rounding errors. This possible rounding is to be expected, so this lint is
662 /// `Allow` by default.
664 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
665 /// or any 64-bit integer to `f64`.
667 /// **Why is this bad?** It's not bad at all. But in some applications it can be
668 /// helpful to know where precision loss can take place. This lint can help find
669 /// those places in the code.
671 /// **Known problems:** None.
675 /// let x = u64::MAX;
678 declare_clippy_lint! {
679 pub CAST_PRECISION_LOSS,
681 "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
684 /// **What it does:** Checks for casts from a signed to an unsigned numerical
685 /// type. In this case, negative values wrap around to large positive values,
686 /// which can be quite surprising in practice. However, as the cast works as
687 /// defined, this lint is `Allow` by default.
689 /// **Why is this bad?** Possibly surprising results. You can activate this lint
690 /// as a one-time check to see where numerical wrapping can arise.
692 /// **Known problems:** None.
697 /// y as u128 // will return 18446744073709551615
699 declare_clippy_lint! {
702 "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
705 /// **What it does:** Checks for on casts between numerical types that may
706 /// truncate large values. This is expected behavior, so the cast is `Allow` by
709 /// **Why is this bad?** In some problem domains, it is good practice to avoid
710 /// truncation. This lint can be activated to help assess where additional
711 /// checks could be beneficial.
713 /// **Known problems:** None.
717 /// fn as_u8(x: u64) -> u8 {
721 declare_clippy_lint! {
722 pub CAST_POSSIBLE_TRUNCATION,
724 "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
727 /// **What it does:** Checks for casts from an unsigned type to a signed type of
728 /// the same size. Performing such a cast is a 'no-op' for the compiler,
729 /// i.e. nothing is changed at the bit level, and the binary representation of
730 /// the value is reinterpreted. This can cause wrapping if the value is too big
731 /// for the target signed type. However, the cast works as defined, so this lint
732 /// is `Allow` by default.
734 /// **Why is this bad?** While such a cast is not bad in itself, the results can
735 /// be surprising when this is not the intended behavior, as demonstrated by the
738 /// **Known problems:** None.
742 /// u32::MAX as i32 // will yield a value of `-1`
744 declare_clippy_lint! {
745 pub CAST_POSSIBLE_WRAP,
747 "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` and `x > i32::MAX`"
750 /// **What it does:** Checks for on casts between numerical types that may
751 /// be replaced by safe conversion functions.
753 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
754 /// conversions, including silently lossy conversions. Conversion functions such
755 /// as `i32::from` will only perform lossless conversions. Using the conversion
756 /// functions prevents conversions from turning into silent lossy conversions if
757 /// the types of the input expressions ever change, and make it easier for
758 /// people reading the code to know that the conversion is lossless.
760 /// **Known problems:** None.
764 /// fn as_u64(x: u8) -> u64 {
769 /// Using `::from` would look like this:
772 /// fn as_u64(x: u8) -> u64 {
776 declare_clippy_lint! {
779 "casts using `as` that are known to be lossless, e.g. `x as u64` where `x: u8`"
782 /// **What it does:** Checks for casts to the same type.
784 /// **Why is this bad?** It's just unnecessary.
786 /// **Known problems:** None.
790 /// let _ = 2i32 as i32
792 declare_clippy_lint! {
793 pub UNNECESSARY_CAST,
795 "cast to the same type, e.g. `x as i32` where `x: i32`"
798 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
799 /// more-strictly-aligned pointer
801 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
804 /// **Known problems:** None.
808 /// let _ = (&1u8 as *const u8) as *const u16;
809 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
811 declare_clippy_lint! {
812 pub CAST_PTR_ALIGNMENT,
814 "cast from a pointer to a more-strictly-aligned pointer"
817 /// **What it does:** Checks for casts of function pointers to something other than usize
819 /// **Why is this bad?**
820 /// Casting a function pointer to anything other than usize/isize is not portable across
821 /// architectures, because you end up losing bits if the target type is too small or end up with a
822 /// bunch of extra bits that waste space and add more instructions to the final binary than
823 /// strictly necessary for the problem
825 /// Casting to isize also doesn't make sense since there are no signed addresses.
831 /// fn fun() -> i32 {}
832 /// let a = fun as i64;
835 /// fn fun2() -> i32 {}
836 /// let a = fun2 as usize;
838 declare_clippy_lint! {
839 pub FN_TO_NUMERIC_CAST,
841 "casting a function pointer to a numeric type other than usize"
844 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
847 /// **Why is this bad?**
848 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
849 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
850 /// a comment) to perform the truncation.
856 /// fn fn1() -> i16 {
859 /// let _ = fn1 as i32;
861 /// // Better: Cast to usize first, then comment with the reason for the truncation
862 /// fn fn2() -> i16 {
865 /// let fn_ptr = fn2 as usize;
866 /// let fn_ptr_truncated = fn_ptr as i32;
868 declare_clippy_lint! {
869 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
871 "casting a function pointer to a numeric type not wide enough to store the address"
874 /// Returns the size in bits of an integral type.
875 /// Will return 0 if the type is not an int or uint variant
876 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_, '_, '_>) -> u64 {
878 ty::Int(i) => match i {
879 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
886 ty::Uint(i) => match i {
887 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
898 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
900 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => true,
905 fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr, cast_from: Ty<'_>, cast_to_f64: bool) {
906 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
907 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
908 let arch_dependent_str = "on targets with 64-bit wide pointers ";
909 let from_nbits_str = if arch_dependent {
911 } else if is_isize_or_usize(cast_from) {
912 "32 or 64".to_owned()
914 int_ty_to_nbits(cast_from, cx.tcx).to_string()
921 "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
922 is only {4} bits wide)",
924 if cast_to_f64 { "f64" } else { "f32" },
925 if arch_dependent { arch_dependent_str } else { "" },
932 fn should_strip_parens(op: &Expr, snip: &str) -> bool {
933 if let ExprKind::Binary(_, _, _) = op.node {
934 if snip.starts_with('(') && snip.ends_with(')') {
941 fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
942 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
943 if in_constant(cx, expr.id) {
946 // The suggestion is to use a function call, so if the original expression
947 // has parens on the outside, they are no longer needed.
948 let mut applicability = Applicability::MachineApplicable;
949 let opt = snippet_opt(cx, op.span);
950 let sugg = if let Some(ref snip) = opt {
951 if should_strip_parens(op, snip) {
952 &snip[1..snip.len() - 1]
957 applicability = Applicability::HasPlaceholders;
966 "casting {} to {} may become silently lossy if types change",
970 format!("{}::from({})", cast_to, sugg),
981 fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
982 let arch_64_suffix = " on targets with 64-bit wide pointers";
983 let arch_32_suffix = " on targets with 32-bit wide pointers";
984 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
985 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
986 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
987 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
988 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
989 (true, true) | (false, false) => (
990 to_nbits < from_nbits,
992 to_nbits == from_nbits && cast_unsigned_to_signed,
1002 to_nbits <= 32 && cast_unsigned_to_signed,
1008 cast_unsigned_to_signed,
1009 if from_nbits == 64 {
1016 if span_truncation {
1019 CAST_POSSIBLE_TRUNCATION,
1022 "casting {} to {} may truncate the value{}",
1025 match suffix_truncation {
1026 ArchSuffix::_32 => arch_32_suffix,
1027 ArchSuffix::_64 => arch_64_suffix,
1028 ArchSuffix::None => "",
1039 "casting {} to {} may wrap around the value{}",
1043 ArchSuffix::_32 => arch_32_suffix,
1044 ArchSuffix::_64 => arch_64_suffix,
1045 ArchSuffix::None => "",
1052 fn check_lossless(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1053 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1054 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1055 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1056 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1058 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1062 impl LintPass for CastPass {
1063 fn get_lints(&self) -> LintArray {
1065 CAST_PRECISION_LOSS,
1067 CAST_POSSIBLE_TRUNCATION,
1073 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1078 // Check if the given type is either `core::ffi::c_void` or
1079 // one of the platform specific `libc::<platform>::c_void` of libc.
1080 fn is_c_void(tcx: TyCtxt<'_, '_, '_>, ty: Ty<'_>) -> bool {
1081 if let ty::Adt(adt, _) = ty.sty {
1082 let mut apb = AbsolutePathBuffer { names: vec![] };
1083 tcx.push_item_path(&mut apb, adt.did, false);
1085 if apb.names.is_empty() {
1088 if apb.names[0] == "libc" || apb.names[0] == "core" && *apb.names.last().unwrap() == "c_void" {
1095 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
1096 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1097 if let ExprKind::Cast(ref ex, _) = expr.node {
1098 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
1099 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1100 if let ExprKind::Lit(ref lit) = ex.node {
1101 use syntax::ast::{LitIntType, LitKind};
1103 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
1105 if cast_from.sty == cast_to.sty && !in_external_macro(cx.sess(), expr.span) {
1111 "casting to the same type is unnecessary (`{}` -> `{}`)",
1119 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1120 match (cast_from.is_integral(), cast_to.is_integral()) {
1122 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1123 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.sty {
1128 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1129 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1131 if from_nbits < to_nbits {
1132 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1138 CAST_POSSIBLE_TRUNCATION,
1140 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
1142 if !cast_to.is_signed() {
1147 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1152 if cast_from.is_signed() && !cast_to.is_signed() {
1157 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1160 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1161 check_lossless(cx, expr, ex, cast_from, cast_to);
1164 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty) {
1167 CAST_POSSIBLE_TRUNCATION,
1169 "casting f64 to f32 may truncate the value",
1172 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty) {
1173 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1180 if let ty::RawPtr(from_ptr_ty) = &cast_from.sty;
1181 if let ty::RawPtr(to_ptr_ty) = &cast_to.sty;
1182 if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi);
1183 if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi);
1184 if from_align < to_align;
1185 // with c_void, we inherently need to trust the user
1186 if !is_c_void(cx.tcx, from_ptr_ty.ty);
1192 &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
1200 fn lint_fn_to_numeric_cast(
1201 cx: &LateContext<'_, '_>,
1207 // We only want to check casts to `ty::Uint` or `ty::Int`
1209 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1212 match cast_from.sty {
1213 ty::FnDef(..) | ty::FnPtr(_) => {
1214 let mut applicability = Applicability::MachineApplicable;
1215 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1217 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1218 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1221 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1224 "casting function pointer `{}` to `{}`, which truncates the value",
1225 from_snippet, cast_to
1228 format!("{} as usize", from_snippet),
1231 } else if cast_to.sty != ty::Uint(UintTy::Usize) {
1236 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1238 format!("{} as usize", from_snippet),
1247 /// **What it does:** Checks for types used in structs, parameters and `let`
1248 /// declarations above a certain complexity threshold.
1250 /// **Why is this bad?** Too complex types make the code less readable. Consider
1251 /// using a `type` definition to simplify them.
1253 /// **Known problems:** None.
1258 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1261 declare_clippy_lint! {
1262 pub TYPE_COMPLEXITY,
1264 "usage of very complex types that might be better factored into `type` definitions"
1267 pub struct TypeComplexityPass {
1271 impl TypeComplexityPass {
1272 pub fn new(threshold: u64) -> Self {
1277 impl LintPass for TypeComplexityPass {
1278 fn get_lints(&self) -> LintArray {
1279 lint_array!(TYPE_COMPLEXITY)
1283 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
1286 cx: &LateContext<'a, 'tcx>,
1293 self.check_fndecl(cx, decl);
1296 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx StructField) {
1297 // enum variants are also struct fields now
1298 self.check_type(cx, &field.ty);
1301 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1303 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1304 // functions, enums, structs, impls and traits are covered
1309 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
1311 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1312 TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1313 // methods with default impl are covered by check_fn
1318 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
1320 ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
1321 // methods are covered by check_fn
1326 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
1327 if let Some(ref ty) = local.ty {
1328 self.check_type(cx, ty);
1333 impl<'a, 'tcx> TypeComplexityPass {
1334 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
1335 for arg in &decl.inputs {
1336 self.check_type(cx, arg);
1338 if let Return(ref ty) = decl.output {
1339 self.check_type(cx, ty);
1343 fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty) {
1344 if in_macro(ty.span) {
1348 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1349 visitor.visit_ty(ty);
1353 if score > self.threshold {
1358 "very complex type used. Consider factoring parts into `type` definitions",
1364 /// Walks a type and assigns a complexity score to it.
1365 struct TypeComplexityVisitor {
1366 /// total complexity score of the type
1368 /// current nesting level
1372 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1373 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1374 let (add_score, sub_nest) = match ty.node {
1375 // _, &x and *x have only small overhead; don't mess with nesting level
1376 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1378 // the "normal" components of a type: named types, arrays/tuples
1379 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1381 // function types bring a lot of overhead
1382 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1384 TyKind::TraitObject(ref param_bounds, _) => {
1385 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1386 bound.bound_generic_params.iter().any(|gen| match gen.kind {
1387 GenericParamKind::Lifetime { .. } => true,
1391 if has_lifetime_parameters {
1392 // complex trait bounds like A<'a, 'b>
1395 // simple trait bounds like A + B
1402 self.score += add_score;
1403 self.nest += sub_nest;
1405 self.nest -= sub_nest;
1407 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1408 NestedVisitorMap::None
1412 /// **What it does:** Checks for expressions where a character literal is cast
1413 /// to `u8` and suggests using a byte literal instead.
1415 /// **Why is this bad?** In general, casting values to smaller types is
1416 /// error-prone and should be avoided where possible. In the particular case of
1417 /// converting a character literal to u8, it is easy to avoid by just using a
1418 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1419 /// than `'a' as u8`.
1421 /// **Known problems:** None.
1428 /// A better version, using the byte literal:
1433 declare_clippy_lint! {
1436 "casting a character literal to u8"
1439 pub struct CharLitAsU8;
1441 impl LintPass for CharLitAsU8 {
1442 fn get_lints(&self) -> LintArray {
1443 lint_array!(CHAR_LIT_AS_U8)
1447 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1448 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1449 use syntax::ast::{LitKind, UintTy};
1451 if let ExprKind::Cast(ref e, _) = expr.node {
1452 if let ExprKind::Lit(ref l) = e.node {
1453 if let LitKind::Char(_) = l.node {
1454 if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
1455 let msg = "casting character literal to u8. `char`s \
1456 are 4 bytes wide in rust, so casting to u8 \
1459 "Consider using a byte literal instead:\nb{}",
1460 snippet(cx, e.span, "'x'")
1462 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
1470 /// **What it does:** Checks for comparisons where one side of the relation is
1471 /// either the minimum or maximum value for its type and warns if it involves a
1472 /// case that is always true or always false. Only integer and boolean types are
1475 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1476 /// that is is possible for `x` to be less than the minimum. Expressions like
1477 /// `max < x` are probably mistakes.
1479 /// **Known problems:** For `usize` the size of the current compile target will
1480 /// be assumed (e.g. 64 bits on 64 bit systems). This means code that uses such
1481 /// a comparison to detect target pointer width will trigger this lint. One can
1482 /// use `mem::sizeof` and compare its value or conditional compilation
1484 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1489 /// 100 > std::i32::MAX
1491 declare_clippy_lint! {
1492 pub ABSURD_EXTREME_COMPARISONS,
1494 "a comparison with a maximum or minimum value that is always true or false"
1497 pub struct AbsurdExtremeComparisons;
1499 impl LintPass for AbsurdExtremeComparisons {
1500 fn get_lints(&self) -> LintArray {
1501 lint_array!(ABSURD_EXTREME_COMPARISONS)
1510 struct ExtremeExpr<'a> {
1515 enum AbsurdComparisonResult {
1518 InequalityImpossible,
1521 fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
1522 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1523 let precast_ty = cx.tables.expr_ty(cast_exp);
1524 let cast_ty = cx.tables.expr_ty(expr);
1526 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1532 fn detect_absurd_comparison<'a, 'tcx>(
1533 cx: &LateContext<'a, 'tcx>,
1537 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1538 use crate::types::AbsurdComparisonResult::*;
1539 use crate::types::ExtremeType::*;
1540 use crate::utils::comparisons::*;
1542 // absurd comparison only makes sense on primitive types
1543 // primitive types don't implement comparison operators with each other
1544 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1548 // comparisons between fix sized types and target sized types are considered unanalyzable
1549 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1553 let normalized = normalize_comparison(op, lhs, rhs);
1554 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1560 let lx = detect_extreme_expr(cx, normalized_lhs);
1561 let rx = detect_extreme_expr(cx, normalized_rhs);
1566 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1567 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1573 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1574 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1575 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1576 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1580 Rel::Ne | Rel::Eq => return None,
1584 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<ExtremeExpr<'tcx>> {
1585 use crate::types::ExtremeType::*;
1587 let ty = cx.tables.expr_ty(expr);
1589 let cv = constant(cx, cx.tables, expr)?.0;
1591 let which = match (&ty.sty, cv) {
1592 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1593 (&ty::Int(ity), Constant::Int(i))
1594 if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1599 (&ty::Bool, Constant::Bool(true)) => Maximum,
1600 (&ty::Int(ity), Constant::Int(i))
1601 if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1605 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1609 Some(ExtremeExpr { which, expr })
1612 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1613 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1614 use crate::types::AbsurdComparisonResult::*;
1615 use crate::types::ExtremeType::*;
1617 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1618 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1619 if !in_macro(expr.span) {
1620 let msg = "this comparison involving the minimum or maximum element for this \
1621 type contains a case that is always true or always false";
1623 let conclusion = match result {
1624 AlwaysFalse => "this comparison is always false".to_owned(),
1625 AlwaysTrue => "this comparison is always true".to_owned(),
1626 InequalityImpossible => format!(
1627 "the case where the two sides are not equal never occurs, consider using {} == {} \
1629 snippet(cx, lhs.span, "lhs"),
1630 snippet(cx, rhs.span, "rhs")
1635 "because {} is the {} value for this type, {}",
1636 snippet(cx, culprit.expr.span, "x"),
1637 match culprit.which {
1638 Minimum => "minimum",
1639 Maximum => "maximum",
1644 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1651 /// **What it does:** Checks for comparisons where the relation is always either
1652 /// true or false, but where one side has been upcast so that the comparison is
1653 /// necessary. Only integer types are checked.
1655 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1656 /// will mistakenly imply that it is possible for `x` to be outside the range of
1659 /// **Known problems:**
1660 /// https://github.com/rust-lang/rust-clippy/issues/886
1664 /// let x : u8 = ...; (x as u32) > 300
1666 declare_clippy_lint! {
1667 pub INVALID_UPCAST_COMPARISONS,
1669 "a comparison involving an upcast which is always true or false"
1672 pub struct InvalidUpcastComparisons;
1674 impl LintPass for InvalidUpcastComparisons {
1675 fn get_lints(&self) -> LintArray {
1676 lint_array!(INVALID_UPCAST_COMPARISONS)
1680 #[derive(Copy, Clone, Debug, Eq)]
1687 #[allow(clippy::cast_sign_loss)]
1688 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1691 } else if u > (i128::max_value() as u128) {
1699 impl PartialEq for FullInt {
1700 fn eq(&self, other: &Self) -> bool {
1701 self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
1705 impl PartialOrd for FullInt {
1706 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1707 Some(match (self, other) {
1708 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1709 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1710 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1711 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1715 impl Ord for FullInt {
1716 fn cmp(&self, other: &Self) -> Ordering {
1717 self.partial_cmp(other)
1718 .expect("partial_cmp for FullInt can never return None")
1722 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1724 use syntax::ast::{IntTy, UintTy};
1726 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1727 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1728 let cast_ty = cx.tables.expr_ty(expr);
1729 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1730 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1733 match pre_cast_ty.sty {
1734 ty::Int(int_ty) => Some(match int_ty {
1736 FullInt::S(i128::from(i8::min_value())),
1737 FullInt::S(i128::from(i8::max_value())),
1740 FullInt::S(i128::from(i16::min_value())),
1741 FullInt::S(i128::from(i16::max_value())),
1744 FullInt::S(i128::from(i32::min_value())),
1745 FullInt::S(i128::from(i32::max_value())),
1748 FullInt::S(i128::from(i64::min_value())),
1749 FullInt::S(i128::from(i64::max_value())),
1751 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
1753 FullInt::S(isize::min_value() as i128),
1754 FullInt::S(isize::max_value() as i128),
1757 ty::Uint(uint_ty) => Some(match uint_ty {
1759 FullInt::U(u128::from(u8::min_value())),
1760 FullInt::U(u128::from(u8::max_value())),
1763 FullInt::U(u128::from(u16::min_value())),
1764 FullInt::U(u128::from(u16::max_value())),
1767 FullInt::U(u128::from(u32::min_value())),
1768 FullInt::U(u128::from(u32::max_value())),
1771 FullInt::U(u128::from(u64::min_value())),
1772 FullInt::U(u128::from(u64::max_value())),
1774 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
1776 FullInt::U(usize::min_value() as u128),
1777 FullInt::U(usize::max_value() as u128),
1787 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<FullInt> {
1788 let val = constant(cx, cx.tables, expr)?.0;
1789 if let Constant::Int(const_int) = val {
1790 match cx.tables.expr_ty(expr).sty {
1791 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1792 ty::Uint(_) => Some(FullInt::U(const_int)),
1800 fn err_upcast_comparison(cx: &LateContext<'_, '_>, span: Span, expr: &Expr, always: bool) {
1801 if let ExprKind::Cast(ref cast_val, _) = expr.node {
1804 INVALID_UPCAST_COMPARISONS,
1807 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1808 snippet(cx, cast_val.span, "the expression"),
1809 if always { "true" } else { "false" },
1815 fn upcast_comparison_bounds_err<'a, 'tcx>(
1816 cx: &LateContext<'a, 'tcx>,
1818 rel: comparisons::Rel,
1819 lhs_bounds: Option<(FullInt, FullInt)>,
1824 use crate::utils::comparisons::*;
1826 if let Some((lb, ub)) = lhs_bounds {
1827 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1828 if rel == Rel::Eq || rel == Rel::Ne {
1829 if norm_rhs_val < lb || norm_rhs_val > ub {
1830 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1832 } else if match rel {
1847 Rel::Eq | Rel::Ne => unreachable!(),
1849 err_upcast_comparison(cx, span, lhs, true)
1850 } else if match rel {
1865 Rel::Eq | Rel::Ne => unreachable!(),
1867 err_upcast_comparison(cx, span, lhs, false)
1873 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1874 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1875 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1876 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1877 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1883 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1884 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1886 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1887 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1892 /// **What it does:** Checks for public `impl` or `fn` missing generalization
1893 /// over different hashers and implicitly defaulting to the default hashing
1894 /// algorithm (SipHash).
1896 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
1899 /// **Known problems:** Suggestions for replacing constructors can contain
1900 /// false-positives. Also applying suggestions can require modification of other
1901 /// pieces of code, possibly including external crates.
1905 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { ... }
1907 /// pub foo(map: &mut HashMap<i32, i32>) { .. }
1909 declare_clippy_lint! {
1910 pub IMPLICIT_HASHER,
1912 "missing generalization over different hashers"
1915 pub struct ImplicitHasher;
1917 impl LintPass for ImplicitHasher {
1918 fn get_lints(&self) -> LintArray {
1919 lint_array!(IMPLICIT_HASHER)
1923 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
1924 #[allow(clippy::cast_possible_truncation)]
1925 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1926 use syntax_pos::BytePos;
1928 fn suggestion<'a, 'tcx>(
1929 cx: &LateContext<'a, 'tcx>,
1930 db: &mut DiagnosticBuilder<'_>,
1931 generics_span: Span,
1932 generics_suggestion_span: Span,
1933 target: &ImplicitHasherType<'_>,
1934 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
1936 let generics_snip = snippet(cx, generics_span, "");
1938 let generics_snip = if generics_snip.is_empty() {
1941 &generics_snip[1..generics_snip.len() - 1]
1946 "consider adding a type parameter".to_string(),
1949 generics_suggestion_span,
1951 "<{}{}S: ::std::hash::BuildHasher{}>",
1953 if generics_snip.is_empty() { "" } else { ", " },
1954 if vis.suggestions.is_empty() {
1957 // request users to add `Default` bound so that generic constructors can be used
1964 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
1969 if !vis.suggestions.is_empty() {
1970 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
1974 if !cx.access_levels.is_exported(item.id) {
1979 ItemKind::Impl(_, _, _, ref generics, _, ref ty, ref items) => {
1980 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1983 for target in &vis.found {
1984 if differing_macro_contexts(item.span, target.span()) {
1988 let generics_suggestion_span = generics.span.substitute_dummy({
1989 let pos = snippet_opt(cx, item.span.until(target.span()))
1990 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
1991 if let Some(pos) = pos {
1992 Span::new(pos, pos, item.span.data().ctxt)
1998 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
1999 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2000 ctr_vis.visit_impl_item(item);
2008 "impl for `{}` should be generalized over different hashers",
2012 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2017 ItemKind::Fn(ref decl, .., ref generics, body_id) => {
2018 let body = cx.tcx.hir().body(body_id);
2020 for ty in &decl.inputs {
2021 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2024 for target in &vis.found {
2025 let generics_suggestion_span = generics.span.substitute_dummy({
2026 let pos = snippet_opt(cx, item.span.until(body.arguments[0].pat.span))
2028 let i = snip.find("fn")?;
2029 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2031 .expect("failed to create span for type parameters");
2032 Span::new(pos, pos, item.span.data().ctxt)
2035 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2036 ctr_vis.visit_body(body);
2043 "parameter of type `{}` should be generalized over different hashers",
2047 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2058 enum ImplicitHasherType<'tcx> {
2059 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2060 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2063 impl<'tcx> ImplicitHasherType<'tcx> {
2064 /// Checks that `ty` is a target type without a BuildHasher.
2065 fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
2066 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.node {
2067 let params: Vec<_> = path
2075 .filter_map(|arg| match arg {
2076 GenericArg::Type(ty) => Some(ty),
2077 GenericArg::Lifetime(_) => None,
2080 let params_len = params.len();
2082 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2084 if match_path(path, &paths::HASHMAP) && params_len == 2 {
2085 Some(ImplicitHasherType::HashMap(
2088 snippet(cx, params[0].span, "K"),
2089 snippet(cx, params[1].span, "V"),
2091 } else if match_path(path, &paths::HASHSET) && params_len == 1 {
2092 Some(ImplicitHasherType::HashSet(
2095 snippet(cx, params[0].span, "T"),
2105 fn type_name(&self) -> &'static str {
2107 ImplicitHasherType::HashMap(..) => "HashMap",
2108 ImplicitHasherType::HashSet(..) => "HashSet",
2112 fn type_arguments(&self) -> String {
2114 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2115 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2119 fn ty(&self) -> Ty<'tcx> {
2121 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2125 fn span(&self) -> Span {
2127 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2132 struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
2133 cx: &'a LateContext<'a, 'tcx>,
2134 found: Vec<ImplicitHasherType<'tcx>>,
2137 impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
2138 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
2139 Self { cx, found: vec![] }
2143 impl<'a, 'tcx: 'a> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2144 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
2145 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2146 self.found.push(target);
2152 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2153 NestedVisitorMap::None
2157 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2158 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx: 'a + 'b> {
2159 cx: &'a LateContext<'a, 'tcx>,
2160 body: &'a TypeckTables<'tcx>,
2161 target: &'b ImplicitHasherType<'tcx>,
2162 suggestions: BTreeMap<Span, String>,
2165 impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2166 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2171 suggestions: BTreeMap::new(),
2176 impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2177 fn visit_body(&mut self, body: &'tcx Body) {
2178 self.body = self.cx.tcx.body_tables(body.id());
2179 walk_body(self, body);
2182 fn visit_expr(&mut self, e: &'tcx Expr) {
2184 if let ExprKind::Call(ref fun, ref args) = e.node;
2185 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.node;
2186 if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.node;
2188 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
2192 if match_path(ty_path, &paths::HASHMAP) {
2193 if method.ident.name == "new" {
2195 .insert(e.span, "HashMap::default()".to_string());
2196 } else if method.ident.name == "with_capacity" {
2197 self.suggestions.insert(
2200 "HashMap::with_capacity_and_hasher({}, Default::default())",
2201 snippet(self.cx, args[0].span, "capacity"),
2205 } else if match_path(ty_path, &paths::HASHSET) {
2206 if method.ident.name == "new" {
2208 .insert(e.span, "HashSet::default()".to_string());
2209 } else if method.ident.name == "with_capacity" {
2210 self.suggestions.insert(
2213 "HashSet::with_capacity_and_hasher({}, Default::default())",
2214 snippet(self.cx, args[0].span, "capacity"),
2225 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2226 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
2230 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2232 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2233 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2236 /// **Known problems:** None.
2242 /// *(r as *const _ as *mut _) += 1;
2247 /// Instead consider using interior mutability types.
2250 /// fn x(r: &UnsafeCell<i32>) {
2256 declare_clippy_lint! {
2257 pub CAST_REF_TO_MUT,
2259 "a cast of reference to a mutable pointer"
2262 pub struct RefToMut;
2264 impl LintPass for RefToMut {
2265 fn get_lints(&self) -> LintArray {
2266 lint_array!(CAST_REF_TO_MUT)
2270 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2271 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2273 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.node;
2274 if let ExprKind::Cast(e, t) = &e.node;
2275 if let TyKind::Ptr(MutTy { mutbl: Mutability::MutMutable, .. }) = t.node;
2276 if let ExprKind::Cast(e, t) = &e.node;
2277 if let TyKind::Ptr(MutTy { mutbl: Mutability::MutImmutable, .. }) = t.node;
2278 if let ty::Ref(..) = cx.tables.node_id_to_type(e.hir_id).sty;
2284 "casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell",