1 #![allow(default_hash_types)]
4 use std::cmp::Ordering;
5 use std::collections::BTreeMap;
7 use if_chain::if_chain;
9 use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
11 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
12 use rustc::ty::layout::LayoutOf;
13 use rustc::ty::{self, InferTy, Ty, TyCtxt, TypeckTables};
14 use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
15 use rustc_errors::Applicability;
16 use rustc_target::spec::abi::Abi;
17 use rustc_typeck::hir_ty_to_ty;
18 use syntax::ast::{FloatTy, IntTy, UintTy};
19 use syntax::errors::DiagnosticBuilder;
20 use syntax::source_map::Span;
22 use crate::consts::{constant, Constant};
23 use crate::utils::paths;
25 clip, comparisons, differing_macro_contexts, higher, in_constant, in_macro, int_bits, last_path_segment,
26 match_path, multispan_sugg, same_tys, sext, snippet, snippet_opt, snippet_with_applicability, span_help_and_lint,
27 span_lint, span_lint_and_sugg, span_lint_and_then, unsext,
30 declare_clippy_lint! {
31 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
33 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
34 /// the heap. So if you `Box` it, you just add another level of indirection
35 /// without any benefit whatsoever.
37 /// **Known problems:** None.
42 /// values: Box<Vec<Foo>>,
55 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
58 declare_clippy_lint! {
59 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
61 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
62 /// the heap. So if you `Box` its contents, you just add another level of indirection.
64 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
70 /// values: Vec<Box<i32>>,
83 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
86 declare_clippy_lint! {
87 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
90 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
91 /// represents an optional optional value which is logically the same thing as an optional
92 /// value but has an unneeded extra level of wrapping.
94 /// **Known problems:** None.
98 /// fn x() -> Option<Option<u32>> {
104 "usage of `Option<Option<T>>`"
107 declare_clippy_lint! {
108 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
109 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
111 /// **Why is this bad?** Gankro says:
113 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
114 /// pointers and indirection.
115 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
117 /// > "only" amortized for push/pop, should be faster in the general case for
118 /// almost every possible
119 /// > workload, and isn't even amortized at all if you can predict the capacity
122 /// > `LinkedList`s are only really good if you're doing a lot of merging or
123 /// splitting of lists.
124 /// > This is because they can just mangle some pointers instead of actually
125 /// copying the data. Even
126 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
127 /// can still be better
128 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
130 /// **Known problems:** False positives – the instances where using a
131 /// `LinkedList` makes sense are few and far between, but they can still happen.
135 /// let x = LinkedList::new();
139 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a VecDeque"
142 declare_clippy_lint! {
143 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
145 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
148 /// **Known problems:** None.
152 /// fn foo(bar: &Box<T>) { ... }
158 /// fn foo(bar: &T) { ... }
162 "a borrow of a boxed type"
165 declare_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX]);
167 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types {
168 fn check_fn(&mut self, cx: &LateContext<'_, '_>, _: FnKind<'_>, decl: &FnDecl, _: &Body, _: Span, id: HirId) {
169 // Skip trait implementations; see issue #605.
170 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_hir_id(cx.tcx.hir().get_parent_item(id)) {
171 if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
176 check_fn_decl(cx, decl);
179 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
180 check_ty(cx, &field.ty, false);
183 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &TraitItem) {
185 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
186 TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
191 fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local) {
192 if let Some(ref ty) = local.ty {
193 check_ty(cx, ty, true);
198 fn check_fn_decl(cx: &LateContext<'_, '_>, decl: &FnDecl) {
199 for input in &decl.inputs {
200 check_ty(cx, input, false);
203 if let FunctionRetTy::Return(ref ty) = decl.output {
204 check_ty(cx, ty, false);
208 /// Checks if `qpath` has last segment with type parameter matching `path`
209 fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath, path: &[&str]) -> bool {
210 let last = last_path_segment(qpath);
212 if let Some(ref params) = last.args;
213 if !params.parenthesized;
214 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
215 GenericArg::Type(ty) => Some(ty),
218 if let TyKind::Path(ref qpath) = ty.node;
219 if let Some(did) = cx.tables.qpath_def(qpath, ty.hir_id).opt_def_id();
220 if cx.match_def_path(did, path);
228 /// Recursively check for `TypePass` lints in the given type. Stop at the first
231 /// The parameter `is_local` distinguishes the context of the type; types from
232 /// local bindings should only be checked for the `BORROWED_BOX` lint.
233 #[allow(clippy::too_many_lines)]
234 fn check_ty(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty, is_local: bool) {
235 if in_macro(hir_ty.span) {
239 TyKind::Path(ref qpath) if !is_local => {
240 let hir_id = hir_ty.hir_id;
241 let def = cx.tables.qpath_def(qpath, hir_id);
242 if let Some(def_id) = def.opt_def_id() {
243 if Some(def_id) == cx.tcx.lang_items().owned_box() {
244 if match_type_parameter(cx, qpath, &paths::VEC) {
249 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
250 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
252 return; // don't recurse into the type
254 } else if cx.match_def_path(def_id, &paths::VEC) {
256 // Get the _ part of Vec<_>
257 if let Some(ref last) = last_path_segment(qpath).args;
258 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
259 GenericArg::Type(ty) => Some(ty),
262 // ty is now _ at this point
263 if let TyKind::Path(ref ty_qpath) = ty.node;
264 let def = cx.tables.qpath_def(ty_qpath, ty.hir_id);
265 if let Some(def_id) = def.opt_def_id();
266 if Some(def_id) == cx.tcx.lang_items().owned_box();
267 // At this point, we know ty is Box<T>, now get T
268 if let Some(ref last) = last_path_segment(ty_qpath).args;
269 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
270 GenericArg::Type(ty) => Some(ty),
274 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
275 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env) {
280 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
282 format!("Vec<{}>", ty_ty),
283 Applicability::MachineApplicable,
285 return; // don't recurse into the type
289 } else if cx.match_def_path(def_id, &paths::OPTION) {
290 if match_type_parameter(cx, qpath, &paths::OPTION) {
295 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
296 enum if you need to distinguish all 3 cases",
298 return; // don't recurse into the type
300 } else if cx.match_def_path(def_id, &paths::LINKED_LIST) {
305 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
306 "a VecDeque might work",
308 return; // don't recurse into the type
312 QPath::Resolved(Some(ref ty), ref p) => {
313 check_ty(cx, ty, is_local);
314 for ty in p.segments.iter().flat_map(|seg| {
317 .map_or_else(|| [].iter(), |params| params.args.iter())
318 .filter_map(|arg| match arg {
319 GenericArg::Type(ty) => Some(ty),
323 check_ty(cx, ty, is_local);
326 QPath::Resolved(None, ref p) => {
327 for ty in p.segments.iter().flat_map(|seg| {
330 .map_or_else(|| [].iter(), |params| params.args.iter())
331 .filter_map(|arg| match arg {
332 GenericArg::Type(ty) => Some(ty),
336 check_ty(cx, ty, is_local);
339 QPath::TypeRelative(ref ty, ref seg) => {
340 check_ty(cx, ty, is_local);
341 if let Some(ref params) = seg.args {
342 for ty in params.args.iter().filter_map(|arg| match arg {
343 GenericArg::Type(ty) => Some(ty),
346 check_ty(cx, ty, is_local);
352 TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
354 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
355 check_ty(cx, ty, is_local)
357 TyKind::Tup(ref tys) => {
359 check_ty(cx, ty, is_local);
366 fn check_ty_rptr(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty, is_local: bool, lt: &Lifetime, mut_ty: &MutTy) {
367 match mut_ty.ty.node {
368 TyKind::Path(ref qpath) => {
369 let hir_id = mut_ty.ty.hir_id;
370 let def = cx.tables.qpath_def(qpath, hir_id);
372 if let Some(def_id) = def.opt_def_id();
373 if Some(def_id) == cx.tcx.lang_items().owned_box();
374 if let QPath::Resolved(None, ref path) = *qpath;
375 if let [ref bx] = *path.segments;
376 if let Some(ref params) = bx.args;
377 if !params.parenthesized;
378 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
379 GenericArg::Type(ty) => Some(ty),
383 if is_any_trait(inner) {
384 // Ignore `Box<Any>` types; see issue #1884 for details.
388 let ltopt = if lt.is_elided() {
391 format!("{} ", lt.name.ident().as_str())
393 let mutopt = if mut_ty.mutbl == Mutability::MutMutable {
398 let mut applicability = Applicability::MachineApplicable;
403 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
409 &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
411 Applicability::Unspecified,
413 return; // don't recurse into the type
416 check_ty(cx, &mut_ty.ty, is_local);
418 _ => check_ty(cx, &mut_ty.ty, is_local),
422 // Returns true if given type is `Any` trait.
423 fn is_any_trait(t: &hir::Ty) -> bool {
425 if let TyKind::TraitObject(ref traits, _) = t.node;
426 if traits.len() >= 1;
427 // Only Send/Sync can be used as additional traits, so it is enough to
428 // check only the first trait.
429 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
438 declare_clippy_lint! {
439 /// **What it does:** Checks for binding a unit value.
441 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
442 /// binding one is kind of pointless.
444 /// **Known problems:** None.
454 "creating a let binding to a value of unit type, which usually can't be used afterwards"
457 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
459 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue {
460 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
461 if let StmtKind::Local(ref local) = stmt.node {
462 if is_unit(cx.tables.pat_ty(&local.pat)) {
463 if in_external_macro(cx.sess(), stmt.span) || in_macro(local.pat.span) {
466 if higher::is_from_for_desugar(local) {
474 "this let-binding has unit value. Consider omitting `let {} =`",
475 snippet(cx, local.pat.span, "..")
483 declare_clippy_lint! {
484 /// **What it does:** Checks for comparisons to unit.
486 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
487 /// clumsily written constant. Mostly this happens when someone accidentally
488 /// adds semicolons at the end of the operands.
490 /// **Known problems:** None.
518 "comparing unit values"
521 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
523 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
524 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
525 if in_macro(expr.span) {
528 if let ExprKind::Binary(ref cmp, ref left, _) = expr.node {
530 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
531 let result = match op {
532 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
540 "{}-comparison of unit values detected. This will always be {}",
550 declare_clippy_lint! {
551 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
552 /// unit literal (`()`).
554 /// **Why is this bad?** This is likely the result of an accidental semicolon.
556 /// **Known problems:** None.
567 "passing unit to a function"
570 declare_lint_pass!(UnitArg => [UNIT_ARG]);
572 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
573 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
574 if in_macro(expr.span) {
578 // apparently stuff in the desugaring of `?` can trigger this
579 // so check for that here
580 // only the calls to `Try::from_error` is marked as desugared,
581 // so we need to check both the current Expr and its parent.
582 if is_questionmark_desugar_marked_call(expr) {
586 let map = &cx.tcx.hir();
587 let opt_parent_node = map.find_by_hir_id(map.get_parent_node_by_hir_id(expr.hir_id));
588 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
589 if is_questionmark_desugar_marked_call(parent_expr);
596 ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
598 if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
599 if let ExprKind::Match(.., match_source) = &arg.node {
600 if *match_source == MatchSource::TryDesugar {
609 "passing a unit value to a function",
610 "if you intended to pass a unit value, use a unit literal instead",
612 Applicability::MachineApplicable,
622 fn is_questionmark_desugar_marked_call(expr: &Expr) -> bool {
623 use syntax_pos::hygiene::CompilerDesugaringKind;
624 if let ExprKind::Call(ref callee, _) = expr.node {
625 callee.span.is_compiler_desugaring(CompilerDesugaringKind::QuestionMark)
631 fn is_unit(ty: Ty<'_>) -> bool {
633 ty::Tuple(slice) if slice.is_empty() => true,
638 fn is_unit_literal(expr: &Expr) -> bool {
640 ExprKind::Tup(ref slice) if slice.is_empty() => true,
645 declare_clippy_lint! {
646 /// **What it does:** Checks for casts from any numerical to a float type where
647 /// the receiving type cannot store all values from the original type without
648 /// rounding errors. This possible rounding is to be expected, so this lint is
649 /// `Allow` by default.
651 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
652 /// or any 64-bit integer to `f64`.
654 /// **Why is this bad?** It's not bad at all. But in some applications it can be
655 /// helpful to know where precision loss can take place. This lint can help find
656 /// those places in the code.
658 /// **Known problems:** None.
662 /// let x = u64::MAX;
665 pub CAST_PRECISION_LOSS,
667 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
670 declare_clippy_lint! {
671 /// **What it does:** Checks for casts from a signed to an unsigned numerical
672 /// type. In this case, negative values wrap around to large positive values,
673 /// which can be quite surprising in practice. However, as the cast works as
674 /// defined, this lint is `Allow` by default.
676 /// **Why is this bad?** Possibly surprising results. You can activate this lint
677 /// as a one-time check to see where numerical wrapping can arise.
679 /// **Known problems:** None.
684 /// y as u128 // will return 18446744073709551615
688 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
691 declare_clippy_lint! {
692 /// **What it does:** Checks for on casts between numerical types that may
693 /// truncate large values. This is expected behavior, so the cast is `Allow` by
696 /// **Why is this bad?** In some problem domains, it is good practice to avoid
697 /// truncation. This lint can be activated to help assess where additional
698 /// checks could be beneficial.
700 /// **Known problems:** None.
704 /// fn as_u8(x: u64) -> u8 {
708 pub CAST_POSSIBLE_TRUNCATION,
710 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
713 declare_clippy_lint! {
714 /// **What it does:** Checks for casts from an unsigned type to a signed type of
715 /// the same size. Performing such a cast is a 'no-op' for the compiler,
716 /// i.e., nothing is changed at the bit level, and the binary representation of
717 /// the value is reinterpreted. This can cause wrapping if the value is too big
718 /// for the target signed type. However, the cast works as defined, so this lint
719 /// is `Allow` by default.
721 /// **Why is this bad?** While such a cast is not bad in itself, the results can
722 /// be surprising when this is not the intended behavior, as demonstrated by the
725 /// **Known problems:** None.
729 /// u32::MAX as i32 // will yield a value of `-1`
731 pub CAST_POSSIBLE_WRAP,
733 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
736 declare_clippy_lint! {
737 /// **What it does:** Checks for on casts between numerical types that may
738 /// be replaced by safe conversion functions.
740 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
741 /// conversions, including silently lossy conversions. Conversion functions such
742 /// as `i32::from` will only perform lossless conversions. Using the conversion
743 /// functions prevents conversions from turning into silent lossy conversions if
744 /// the types of the input expressions ever change, and make it easier for
745 /// people reading the code to know that the conversion is lossless.
747 /// **Known problems:** None.
751 /// fn as_u64(x: u8) -> u64 {
756 /// Using `::from` would look like this:
759 /// fn as_u64(x: u8) -> u64 {
765 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
768 declare_clippy_lint! {
769 /// **What it does:** Checks for casts to the same type.
771 /// **Why is this bad?** It's just unnecessary.
773 /// **Known problems:** None.
777 /// let _ = 2i32 as i32
779 pub UNNECESSARY_CAST,
781 "cast to the same type, e.g., `x as i32` where `x: i32`"
784 declare_clippy_lint! {
785 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
786 /// more-strictly-aligned pointer
788 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
791 /// **Known problems:** None.
795 /// let _ = (&1u8 as *const u8) as *const u16;
796 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
798 pub CAST_PTR_ALIGNMENT,
800 "cast from a pointer to a more-strictly-aligned pointer"
803 declare_clippy_lint! {
804 /// **What it does:** Checks for casts of function pointers to something other than usize
806 /// **Why is this bad?**
807 /// Casting a function pointer to anything other than usize/isize is not portable across
808 /// architectures, because you end up losing bits if the target type is too small or end up with a
809 /// bunch of extra bits that waste space and add more instructions to the final binary than
810 /// strictly necessary for the problem
812 /// Casting to isize also doesn't make sense since there are no signed addresses.
818 /// fn fun() -> i32 { 1 }
819 /// let a = fun as i64;
822 /// fn fun2() -> i32 { 1 }
823 /// let a = fun2 as usize;
825 pub FN_TO_NUMERIC_CAST,
827 "casting a function pointer to a numeric type other than usize"
830 declare_clippy_lint! {
831 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
834 /// **Why is this bad?**
835 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
836 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
837 /// a comment) to perform the truncation.
843 /// fn fn1() -> i16 {
846 /// let _ = fn1 as i32;
848 /// // Better: Cast to usize first, then comment with the reason for the truncation
849 /// fn fn2() -> i16 {
852 /// let fn_ptr = fn2 as usize;
853 /// let fn_ptr_truncated = fn_ptr as i32;
855 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
857 "casting a function pointer to a numeric type not wide enough to store the address"
860 /// Returns the size in bits of an integral type.
861 /// Will return 0 if the type is not an int or uint variant
862 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_, '_, '_>) -> u64 {
864 ty::Int(i) => match i {
865 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
872 ty::Uint(i) => match i {
873 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
884 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
886 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => true,
891 fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr, cast_from: Ty<'_>, cast_to_f64: bool) {
892 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
893 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
894 let arch_dependent_str = "on targets with 64-bit wide pointers ";
895 let from_nbits_str = if arch_dependent {
897 } else if is_isize_or_usize(cast_from) {
898 "32 or 64".to_owned()
900 int_ty_to_nbits(cast_from, cx.tcx).to_string()
907 "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
908 is only {4} bits wide)",
910 if cast_to_f64 { "f64" } else { "f32" },
911 if arch_dependent { arch_dependent_str } else { "" },
918 fn should_strip_parens(op: &Expr, snip: &str) -> bool {
919 if let ExprKind::Binary(_, _, _) = op.node {
920 if snip.starts_with('(') && snip.ends_with(')') {
927 fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
928 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
929 if in_constant(cx, expr.hir_id) {
932 // The suggestion is to use a function call, so if the original expression
933 // has parens on the outside, they are no longer needed.
934 let mut applicability = Applicability::MachineApplicable;
935 let opt = snippet_opt(cx, op.span);
936 let sugg = if let Some(ref snip) = opt {
937 if should_strip_parens(op, snip) {
938 &snip[1..snip.len() - 1]
943 applicability = Applicability::HasPlaceholders;
952 "casting {} to {} may become silently lossy if you later change the type",
956 format!("{}::from({})", cast_to, sugg),
967 fn check_loss_of_sign(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
968 if !cast_from.is_signed() || cast_to.is_signed() {
972 // don't lint for positive constants
973 let const_val = constant(cx, &cx.tables, op);
975 if let Some((const_val, _)) = const_val;
976 if let Constant::Int(n) = const_val;
977 if let ty::Int(ity) = cast_from.sty;
978 if sext(cx.tcx, n, ity) >= 0;
988 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
992 fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
993 let arch_64_suffix = " on targets with 64-bit wide pointers";
994 let arch_32_suffix = " on targets with 32-bit wide pointers";
995 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
996 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
997 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
998 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
999 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1000 (true, true) | (false, false) => (
1001 to_nbits < from_nbits,
1003 to_nbits == from_nbits && cast_unsigned_to_signed,
1013 to_nbits <= 32 && cast_unsigned_to_signed,
1019 cast_unsigned_to_signed,
1020 if from_nbits == 64 {
1027 if span_truncation {
1030 CAST_POSSIBLE_TRUNCATION,
1033 "casting {} to {} may truncate the value{}",
1036 match suffix_truncation {
1037 ArchSuffix::_32 => arch_32_suffix,
1038 ArchSuffix::_64 => arch_64_suffix,
1039 ArchSuffix::None => "",
1050 "casting {} to {} may wrap around the value{}",
1054 ArchSuffix::_32 => arch_32_suffix,
1055 ArchSuffix::_64 => arch_64_suffix,
1056 ArchSuffix::None => "",
1063 fn check_lossless(cx: &LateContext<'_, '_>, expr: &Expr, op: &Expr, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1064 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1065 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1066 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1067 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1069 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1073 declare_lint_pass!(Casts => [
1074 CAST_PRECISION_LOSS,
1076 CAST_POSSIBLE_TRUNCATION,
1082 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1085 // Check if the given type is either `core::ffi::c_void` or
1086 // one of the platform specific `libc::<platform>::c_void` of libc.
1087 fn is_c_void(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1088 if let ty::Adt(adt, _) = ty.sty {
1089 let names = cx.get_def_path(adt.did);
1091 if names.is_empty() {
1094 if names[0] == "libc" || names[0] == "core" && *names.last().unwrap() == "c_void" {
1101 /// Returns the mantissa bits wide of a fp type.
1102 /// Will return 0 if the type is not a fp
1103 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1105 ty::Float(FloatTy::F32) => 23,
1106 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1111 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
1112 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1113 if let ExprKind::Cast(ref ex, _) = expr.node {
1114 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
1115 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1116 if let ExprKind::Lit(ref lit) = ex.node {
1117 use syntax::ast::{LitIntType, LitKind};
1118 if let LitKind::Int(n, _) = lit.node {
1119 if cast_to.is_fp() {
1120 let from_nbits = 128 - n.leading_zeros();
1121 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1122 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits {
1127 &format!("casting integer literal to {} is unnecessary", cast_to),
1129 format!("{}_{}", n, cast_to),
1130 Applicability::MachineApplicable,
1137 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
1139 if cast_from.sty == cast_to.sty && !in_external_macro(cx.sess(), expr.span) {
1145 "casting to the same type is unnecessary (`{}` -> `{}`)",
1153 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1154 match (cast_from.is_integral(), cast_to.is_integral()) {
1156 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1157 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.sty {
1162 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1163 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1165 if from_nbits < to_nbits {
1166 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1172 CAST_POSSIBLE_TRUNCATION,
1174 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
1176 if !cast_to.is_signed() {
1181 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1186 check_loss_of_sign(cx, expr, ex, cast_from, cast_to);
1187 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1188 check_lossless(cx, expr, ex, cast_from, cast_to);
1191 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty) {
1194 CAST_POSSIBLE_TRUNCATION,
1196 "casting f64 to f32 may truncate the value",
1199 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty) {
1200 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1207 if let ty::RawPtr(from_ptr_ty) = &cast_from.sty;
1208 if let ty::RawPtr(to_ptr_ty) = &cast_to.sty;
1209 if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi);
1210 if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi);
1211 if from_align < to_align;
1212 // with c_void, we inherently need to trust the user
1213 if !is_c_void(cx, from_ptr_ty.ty);
1219 &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
1227 fn lint_fn_to_numeric_cast(
1228 cx: &LateContext<'_, '_>,
1234 // We only want to check casts to `ty::Uint` or `ty::Int`
1236 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1239 match cast_from.sty {
1240 ty::FnDef(..) | ty::FnPtr(_) => {
1241 let mut applicability = Applicability::MachineApplicable;
1242 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1244 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1245 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1248 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1251 "casting function pointer `{}` to `{}`, which truncates the value",
1252 from_snippet, cast_to
1255 format!("{} as usize", from_snippet),
1258 } else if cast_to.sty != ty::Uint(UintTy::Usize) {
1263 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1265 format!("{} as usize", from_snippet),
1274 declare_clippy_lint! {
1275 /// **What it does:** Checks for types used in structs, parameters and `let`
1276 /// declarations above a certain complexity threshold.
1278 /// **Why is this bad?** Too complex types make the code less readable. Consider
1279 /// using a `type` definition to simplify them.
1281 /// **Known problems:** None.
1286 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1289 pub TYPE_COMPLEXITY,
1291 "usage of very complex types that might be better factored into `type` definitions"
1294 pub struct TypeComplexity {
1298 impl TypeComplexity {
1299 pub fn new(threshold: u64) -> Self {
1304 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1306 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity {
1309 cx: &LateContext<'a, 'tcx>,
1316 self.check_fndecl(cx, decl);
1319 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
1320 // enum variants are also struct fields now
1321 self.check_type(cx, &field.ty);
1324 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1326 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1327 // functions, enums, structs, impls and traits are covered
1332 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
1334 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1335 TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1336 // methods with default impl are covered by check_fn
1341 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
1343 ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
1344 // methods are covered by check_fn
1349 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
1350 if let Some(ref ty) = local.ty {
1351 self.check_type(cx, ty);
1356 impl<'a, 'tcx> TypeComplexity {
1357 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
1358 for arg in &decl.inputs {
1359 self.check_type(cx, arg);
1361 if let Return(ref ty) = decl.output {
1362 self.check_type(cx, ty);
1366 fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty) {
1367 if in_macro(ty.span) {
1371 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1372 visitor.visit_ty(ty);
1376 if score > self.threshold {
1381 "very complex type used. Consider factoring parts into `type` definitions",
1387 /// Walks a type and assigns a complexity score to it.
1388 struct TypeComplexityVisitor {
1389 /// total complexity score of the type
1391 /// current nesting level
1395 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1396 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1397 let (add_score, sub_nest) = match ty.node {
1398 // _, &x and *x have only small overhead; don't mess with nesting level
1399 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1401 // the "normal" components of a type: named types, arrays/tuples
1402 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1404 // function types bring a lot of overhead
1405 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1407 TyKind::TraitObject(ref param_bounds, _) => {
1408 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1409 bound.bound_generic_params.iter().any(|gen| match gen.kind {
1410 GenericParamKind::Lifetime { .. } => true,
1414 if has_lifetime_parameters {
1415 // complex trait bounds like A<'a, 'b>
1418 // simple trait bounds like A + B
1425 self.score += add_score;
1426 self.nest += sub_nest;
1428 self.nest -= sub_nest;
1430 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1431 NestedVisitorMap::None
1435 declare_clippy_lint! {
1436 /// **What it does:** Checks for expressions where a character literal is cast
1437 /// to `u8` and suggests using a byte literal instead.
1439 /// **Why is this bad?** In general, casting values to smaller types is
1440 /// error-prone and should be avoided where possible. In the particular case of
1441 /// converting a character literal to u8, it is easy to avoid by just using a
1442 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1443 /// than `'a' as u8`.
1445 /// **Known problems:** None.
1452 /// A better version, using the byte literal:
1459 "casting a character literal to u8"
1462 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1464 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1465 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1466 use syntax::ast::LitKind;
1468 if let ExprKind::Cast(ref e, _) = expr.node {
1469 if let ExprKind::Lit(ref l) = e.node {
1470 if let LitKind::Char(_) = l.node {
1471 if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
1472 let msg = "casting character literal to u8. `char`s \
1473 are 4 bytes wide in rust, so casting to u8 \
1476 "Consider using a byte literal instead:\nb{}",
1477 snippet(cx, e.span, "'x'")
1479 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
1487 declare_clippy_lint! {
1488 /// **What it does:** Checks for comparisons where one side of the relation is
1489 /// either the minimum or maximum value for its type and warns if it involves a
1490 /// case that is always true or always false. Only integer and boolean types are
1493 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1494 /// that is is possible for `x` to be less than the minimum. Expressions like
1495 /// `max < x` are probably mistakes.
1497 /// **Known problems:** For `usize` the size of the current compile target will
1498 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1499 /// a comparison to detect target pointer width will trigger this lint. One can
1500 /// use `mem::sizeof` and compare its value or conditional compilation
1502 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1507 /// let vec: Vec<isize> = vec![];
1508 /// if vec.len() <= 0 {}
1509 /// if 100 > std::i32::MAX {}
1511 pub ABSURD_EXTREME_COMPARISONS,
1513 "a comparison with a maximum or minimum value that is always true or false"
1516 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1523 struct ExtremeExpr<'a> {
1528 enum AbsurdComparisonResult {
1531 InequalityImpossible,
1534 fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
1535 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1536 let precast_ty = cx.tables.expr_ty(cast_exp);
1537 let cast_ty = cx.tables.expr_ty(expr);
1539 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1545 fn detect_absurd_comparison<'a, 'tcx>(
1546 cx: &LateContext<'a, 'tcx>,
1550 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1551 use crate::types::AbsurdComparisonResult::*;
1552 use crate::types::ExtremeType::*;
1553 use crate::utils::comparisons::*;
1555 // absurd comparison only makes sense on primitive types
1556 // primitive types don't implement comparison operators with each other
1557 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1561 // comparisons between fix sized types and target sized types are considered unanalyzable
1562 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1566 let normalized = normalize_comparison(op, lhs, rhs);
1567 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1573 let lx = detect_extreme_expr(cx, normalized_lhs);
1574 let rx = detect_extreme_expr(cx, normalized_rhs);
1579 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1580 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1586 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1587 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1588 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1589 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1593 Rel::Ne | Rel::Eq => return None,
1597 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<ExtremeExpr<'tcx>> {
1598 use crate::types::ExtremeType::*;
1600 let ty = cx.tables.expr_ty(expr);
1602 let cv = constant(cx, cx.tables, expr)?.0;
1604 let which = match (&ty.sty, cv) {
1605 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1606 (&ty::Int(ity), Constant::Int(i))
1607 if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1612 (&ty::Bool, Constant::Bool(true)) => Maximum,
1613 (&ty::Int(ity), Constant::Int(i))
1614 if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1618 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1622 Some(ExtremeExpr { which, expr })
1625 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1626 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1627 use crate::types::AbsurdComparisonResult::*;
1628 use crate::types::ExtremeType::*;
1630 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1631 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1632 if !in_macro(expr.span) {
1633 let msg = "this comparison involving the minimum or maximum element for this \
1634 type contains a case that is always true or always false";
1636 let conclusion = match result {
1637 AlwaysFalse => "this comparison is always false".to_owned(),
1638 AlwaysTrue => "this comparison is always true".to_owned(),
1639 InequalityImpossible => format!(
1640 "the case where the two sides are not equal never occurs, consider using {} == {} \
1642 snippet(cx, lhs.span, "lhs"),
1643 snippet(cx, rhs.span, "rhs")
1648 "because {} is the {} value for this type, {}",
1649 snippet(cx, culprit.expr.span, "x"),
1650 match culprit.which {
1651 Minimum => "minimum",
1652 Maximum => "maximum",
1657 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1664 declare_clippy_lint! {
1665 /// **What it does:** Checks for comparisons where the relation is always either
1666 /// true or false, but where one side has been upcast so that the comparison is
1667 /// necessary. Only integer types are checked.
1669 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1670 /// will mistakenly imply that it is possible for `x` to be outside the range of
1673 /// **Known problems:**
1674 /// https://github.com/rust-lang/rust-clippy/issues/886
1678 /// let x : u8 = ...; (x as u32) > 300
1680 pub INVALID_UPCAST_COMPARISONS,
1682 "a comparison involving an upcast which is always true or false"
1685 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
1687 #[derive(Copy, Clone, Debug, Eq)]
1694 #[allow(clippy::cast_sign_loss)]
1695 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1698 } else if u > (i128::max_value() as u128) {
1706 impl PartialEq for FullInt {
1707 fn eq(&self, other: &Self) -> bool {
1708 self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
1712 impl PartialOrd for FullInt {
1713 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1714 Some(match (self, other) {
1715 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1716 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1717 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1718 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1722 impl Ord for FullInt {
1723 fn cmp(&self, other: &Self) -> Ordering {
1724 self.partial_cmp(other)
1725 .expect("partial_cmp for FullInt can never return None")
1729 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1732 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1733 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1734 let cast_ty = cx.tables.expr_ty(expr);
1735 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1736 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1739 match pre_cast_ty.sty {
1740 ty::Int(int_ty) => Some(match int_ty {
1742 FullInt::S(i128::from(i8::min_value())),
1743 FullInt::S(i128::from(i8::max_value())),
1746 FullInt::S(i128::from(i16::min_value())),
1747 FullInt::S(i128::from(i16::max_value())),
1750 FullInt::S(i128::from(i32::min_value())),
1751 FullInt::S(i128::from(i32::max_value())),
1754 FullInt::S(i128::from(i64::min_value())),
1755 FullInt::S(i128::from(i64::max_value())),
1757 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
1759 FullInt::S(isize::min_value() as i128),
1760 FullInt::S(isize::max_value() as i128),
1763 ty::Uint(uint_ty) => Some(match uint_ty {
1765 FullInt::U(u128::from(u8::min_value())),
1766 FullInt::U(u128::from(u8::max_value())),
1769 FullInt::U(u128::from(u16::min_value())),
1770 FullInt::U(u128::from(u16::max_value())),
1773 FullInt::U(u128::from(u32::min_value())),
1774 FullInt::U(u128::from(u32::max_value())),
1777 FullInt::U(u128::from(u64::min_value())),
1778 FullInt::U(u128::from(u64::max_value())),
1780 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
1782 FullInt::U(usize::min_value() as u128),
1783 FullInt::U(usize::max_value() as u128),
1793 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<FullInt> {
1794 let val = constant(cx, cx.tables, expr)?.0;
1795 if let Constant::Int(const_int) = val {
1796 match cx.tables.expr_ty(expr).sty {
1797 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1798 ty::Uint(_) => Some(FullInt::U(const_int)),
1806 fn err_upcast_comparison(cx: &LateContext<'_, '_>, span: Span, expr: &Expr, always: bool) {
1807 if let ExprKind::Cast(ref cast_val, _) = expr.node {
1810 INVALID_UPCAST_COMPARISONS,
1813 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1814 snippet(cx, cast_val.span, "the expression"),
1815 if always { "true" } else { "false" },
1821 fn upcast_comparison_bounds_err<'a, 'tcx>(
1822 cx: &LateContext<'a, 'tcx>,
1824 rel: comparisons::Rel,
1825 lhs_bounds: Option<(FullInt, FullInt)>,
1830 use crate::utils::comparisons::*;
1832 if let Some((lb, ub)) = lhs_bounds {
1833 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1834 if rel == Rel::Eq || rel == Rel::Ne {
1835 if norm_rhs_val < lb || norm_rhs_val > ub {
1836 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1838 } else if match rel {
1853 Rel::Eq | Rel::Ne => unreachable!(),
1855 err_upcast_comparison(cx, span, lhs, true)
1856 } else if match rel {
1871 Rel::Eq | Rel::Ne => unreachable!(),
1873 err_upcast_comparison(cx, span, lhs, false)
1879 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1880 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1881 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1882 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1883 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1889 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1890 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1892 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1893 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1898 declare_clippy_lint! {
1899 /// **What it does:** Checks for public `impl` or `fn` missing generalization
1900 /// over different hashers and implicitly defaulting to the default hashing
1901 /// algorithm (SipHash).
1903 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
1906 /// **Known problems:** Suggestions for replacing constructors can contain
1907 /// false-positives. Also applying suggestions can require modification of other
1908 /// pieces of code, possibly including external crates.
1912 /// # use std::collections::HashMap;
1913 /// # use std::hash::Hash;
1914 /// # trait Serialize {};
1915 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
1917 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
1919 pub IMPLICIT_HASHER,
1921 "missing generalization over different hashers"
1924 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
1926 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
1927 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
1928 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1929 use syntax_pos::BytePos;
1931 fn suggestion<'a, 'tcx>(
1932 cx: &LateContext<'a, 'tcx>,
1933 db: &mut DiagnosticBuilder<'_>,
1934 generics_span: Span,
1935 generics_suggestion_span: Span,
1936 target: &ImplicitHasherType<'_>,
1937 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
1939 let generics_snip = snippet(cx, generics_span, "");
1941 let generics_snip = if generics_snip.is_empty() {
1944 &generics_snip[1..generics_snip.len() - 1]
1949 "consider adding a type parameter".to_string(),
1952 generics_suggestion_span,
1954 "<{}{}S: ::std::hash::BuildHasher{}>",
1956 if generics_snip.is_empty() { "" } else { ", " },
1957 if vis.suggestions.is_empty() {
1960 // request users to add `Default` bound so that generic constructors can be used
1967 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
1972 if !vis.suggestions.is_empty() {
1973 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
1977 if !cx.access_levels.is_exported(item.hir_id) {
1982 ItemKind::Impl(_, _, _, ref generics, _, ref ty, ref items) => {
1983 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1986 for target in &vis.found {
1987 if differing_macro_contexts(item.span, target.span()) {
1991 let generics_suggestion_span = generics.span.substitute_dummy({
1992 let pos = snippet_opt(cx, item.span.until(target.span()))
1993 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
1994 if let Some(pos) = pos {
1995 Span::new(pos, pos, item.span.data().ctxt)
2001 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2002 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2003 ctr_vis.visit_impl_item(item);
2011 "impl for `{}` should be generalized over different hashers",
2015 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2020 ItemKind::Fn(ref decl, .., ref generics, body_id) => {
2021 let body = cx.tcx.hir().body(body_id);
2023 for ty in &decl.inputs {
2024 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2027 for target in &vis.found {
2028 let generics_suggestion_span = generics.span.substitute_dummy({
2029 let pos = snippet_opt(cx, item.span.until(body.arguments[0].pat.span))
2031 let i = snip.find("fn")?;
2032 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2034 .expect("failed to create span for type parameters");
2035 Span::new(pos, pos, item.span.data().ctxt)
2038 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2039 ctr_vis.visit_body(body);
2046 "parameter of type `{}` should be generalized over different hashers",
2050 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2061 enum ImplicitHasherType<'tcx> {
2062 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2063 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2066 impl<'tcx> ImplicitHasherType<'tcx> {
2067 /// Checks that `ty` is a target type without a BuildHasher.
2068 fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
2069 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.node {
2070 let params: Vec<_> = path
2078 .filter_map(|arg| match arg {
2079 GenericArg::Type(ty) => Some(ty),
2083 let params_len = params.len();
2085 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2087 if match_path(path, &paths::HASHMAP) && params_len == 2 {
2088 Some(ImplicitHasherType::HashMap(
2091 snippet(cx, params[0].span, "K"),
2092 snippet(cx, params[1].span, "V"),
2094 } else if match_path(path, &paths::HASHSET) && params_len == 1 {
2095 Some(ImplicitHasherType::HashSet(
2098 snippet(cx, params[0].span, "T"),
2108 fn type_name(&self) -> &'static str {
2110 ImplicitHasherType::HashMap(..) => "HashMap",
2111 ImplicitHasherType::HashSet(..) => "HashSet",
2115 fn type_arguments(&self) -> String {
2117 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2118 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2122 fn ty(&self) -> Ty<'tcx> {
2124 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2128 fn span(&self) -> Span {
2130 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2135 struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
2136 cx: &'a LateContext<'a, 'tcx>,
2137 found: Vec<ImplicitHasherType<'tcx>>,
2140 impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
2141 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
2142 Self { cx, found: vec![] }
2146 impl<'a, 'tcx: 'a> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2147 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
2148 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2149 self.found.push(target);
2155 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2156 NestedVisitorMap::None
2160 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2161 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx: 'a + 'b> {
2162 cx: &'a LateContext<'a, 'tcx>,
2163 body: &'a TypeckTables<'tcx>,
2164 target: &'b ImplicitHasherType<'tcx>,
2165 suggestions: BTreeMap<Span, String>,
2168 impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2169 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2174 suggestions: BTreeMap::new(),
2179 impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2180 fn visit_body(&mut self, body: &'tcx Body) {
2181 let prev_body = self.body;
2182 self.body = self.cx.tcx.body_tables(body.id());
2183 walk_body(self, body);
2184 self.body = prev_body;
2187 fn visit_expr(&mut self, e: &'tcx Expr) {
2189 if let ExprKind::Call(ref fun, ref args) = e.node;
2190 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.node;
2191 if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.node;
2193 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
2197 if match_path(ty_path, &paths::HASHMAP) {
2198 if method.ident.name == "new" {
2200 .insert(e.span, "HashMap::default()".to_string());
2201 } else if method.ident.name == "with_capacity" {
2202 self.suggestions.insert(
2205 "HashMap::with_capacity_and_hasher({}, Default::default())",
2206 snippet(self.cx, args[0].span, "capacity"),
2210 } else if match_path(ty_path, &paths::HASHSET) {
2211 if method.ident.name == "new" {
2213 .insert(e.span, "HashSet::default()".to_string());
2214 } else if method.ident.name == "with_capacity" {
2215 self.suggestions.insert(
2218 "HashSet::with_capacity_and_hasher({}, Default::default())",
2219 snippet(self.cx, args[0].span, "capacity"),
2230 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2231 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
2235 declare_clippy_lint! {
2236 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2238 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2239 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2242 /// **Known problems:** None.
2248 /// *(r as *const _ as *mut _) += 1;
2253 /// Instead consider using interior mutability types.
2256 /// use std::cell::UnsafeCell;
2258 /// fn x(r: &UnsafeCell<i32>) {
2264 pub CAST_REF_TO_MUT,
2266 "a cast of reference to a mutable pointer"
2269 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2271 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2272 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2274 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.node;
2275 if let ExprKind::Cast(e, t) = &e.node;
2276 if let TyKind::Ptr(MutTy { mutbl: Mutability::MutMutable, .. }) = t.node;
2277 if let ExprKind::Cast(e, t) = &e.node;
2278 if let TyKind::Ptr(MutTy { mutbl: Mutability::MutImmutable, .. }) = t.node;
2279 if let ty::Ref(..) = cx.tables.node_type(e.hir_id).sty;
2285 "casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell",