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_res(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 res = cx.tables.qpath_res(qpath, hir_id);
242 if let Some(def_id) = res.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 res = cx.tables.qpath_res(ty_qpath, ty.hir_id);
265 if let Some(def_id) = res.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_res(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 in_macro(expr.span) {
1116 if let ExprKind::Cast(ref ex, _) = expr.node {
1117 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
1118 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1119 if let ExprKind::Lit(ref lit) = ex.node {
1120 use syntax::ast::{LitIntType, LitKind};
1121 if let LitKind::Int(n, _) = lit.node {
1122 if cast_to.is_fp() {
1123 let from_nbits = 128 - n.leading_zeros();
1124 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1125 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits {
1130 &format!("casting integer literal to {} is unnecessary", cast_to),
1132 format!("{}_{}", n, cast_to),
1133 Applicability::MachineApplicable,
1140 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
1142 if cast_from.sty == cast_to.sty && !in_external_macro(cx.sess(), expr.span) {
1148 "casting to the same type is unnecessary (`{}` -> `{}`)",
1156 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1157 match (cast_from.is_integral(), cast_to.is_integral()) {
1159 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1160 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.sty {
1165 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1166 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1168 if from_nbits < to_nbits {
1169 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1175 CAST_POSSIBLE_TRUNCATION,
1177 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
1179 if !cast_to.is_signed() {
1184 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1189 check_loss_of_sign(cx, expr, ex, cast_from, cast_to);
1190 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1191 check_lossless(cx, expr, ex, cast_from, cast_to);
1194 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty) {
1197 CAST_POSSIBLE_TRUNCATION,
1199 "casting f64 to f32 may truncate the value",
1202 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty) {
1203 span_lossless_lint(cx, expr, ex, cast_from, cast_to);
1210 if let ty::RawPtr(from_ptr_ty) = &cast_from.sty;
1211 if let ty::RawPtr(to_ptr_ty) = &cast_to.sty;
1212 if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi);
1213 if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi);
1214 if from_align < to_align;
1215 // with c_void, we inherently need to trust the user
1216 if !is_c_void(cx, from_ptr_ty.ty);
1222 &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
1230 fn lint_fn_to_numeric_cast(
1231 cx: &LateContext<'_, '_>,
1237 // We only want to check casts to `ty::Uint` or `ty::Int`
1239 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1242 match cast_from.sty {
1243 ty::FnDef(..) | ty::FnPtr(_) => {
1244 let mut applicability = Applicability::MachineApplicable;
1245 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1247 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1248 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1251 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1254 "casting function pointer `{}` to `{}`, which truncates the value",
1255 from_snippet, cast_to
1258 format!("{} as usize", from_snippet),
1261 } else if cast_to.sty != ty::Uint(UintTy::Usize) {
1266 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1268 format!("{} as usize", from_snippet),
1277 declare_clippy_lint! {
1278 /// **What it does:** Checks for types used in structs, parameters and `let`
1279 /// declarations above a certain complexity threshold.
1281 /// **Why is this bad?** Too complex types make the code less readable. Consider
1282 /// using a `type` definition to simplify them.
1284 /// **Known problems:** None.
1289 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1292 pub TYPE_COMPLEXITY,
1294 "usage of very complex types that might be better factored into `type` definitions"
1297 pub struct TypeComplexity {
1301 impl TypeComplexity {
1302 pub fn new(threshold: u64) -> Self {
1307 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1309 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity {
1312 cx: &LateContext<'a, 'tcx>,
1319 self.check_fndecl(cx, decl);
1322 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
1323 // enum variants are also struct fields now
1324 self.check_type(cx, &field.ty);
1327 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1329 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1330 // functions, enums, structs, impls and traits are covered
1335 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
1337 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1338 TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1339 // methods with default impl are covered by check_fn
1344 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
1346 ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
1347 // methods are covered by check_fn
1352 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
1353 if let Some(ref ty) = local.ty {
1354 self.check_type(cx, ty);
1359 impl<'a, 'tcx> TypeComplexity {
1360 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
1361 for arg in &decl.inputs {
1362 self.check_type(cx, arg);
1364 if let Return(ref ty) = decl.output {
1365 self.check_type(cx, ty);
1369 fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty) {
1370 if in_macro(ty.span) {
1374 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1375 visitor.visit_ty(ty);
1379 if score > self.threshold {
1384 "very complex type used. Consider factoring parts into `type` definitions",
1390 /// Walks a type and assigns a complexity score to it.
1391 struct TypeComplexityVisitor {
1392 /// total complexity score of the type
1394 /// current nesting level
1398 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1399 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1400 let (add_score, sub_nest) = match ty.node {
1401 // _, &x and *x have only small overhead; don't mess with nesting level
1402 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1404 // the "normal" components of a type: named types, arrays/tuples
1405 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1407 // function types bring a lot of overhead
1408 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1410 TyKind::TraitObject(ref param_bounds, _) => {
1411 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1412 bound.bound_generic_params.iter().any(|gen| match gen.kind {
1413 GenericParamKind::Lifetime { .. } => true,
1417 if has_lifetime_parameters {
1418 // complex trait bounds like A<'a, 'b>
1421 // simple trait bounds like A + B
1428 self.score += add_score;
1429 self.nest += sub_nest;
1431 self.nest -= sub_nest;
1433 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1434 NestedVisitorMap::None
1438 declare_clippy_lint! {
1439 /// **What it does:** Checks for expressions where a character literal is cast
1440 /// to `u8` and suggests using a byte literal instead.
1442 /// **Why is this bad?** In general, casting values to smaller types is
1443 /// error-prone and should be avoided where possible. In the particular case of
1444 /// converting a character literal to u8, it is easy to avoid by just using a
1445 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1446 /// than `'a' as u8`.
1448 /// **Known problems:** None.
1455 /// A better version, using the byte literal:
1462 "casting a character literal to u8"
1465 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1467 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1468 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1469 use syntax::ast::LitKind;
1471 if let ExprKind::Cast(ref e, _) = expr.node {
1472 if let ExprKind::Lit(ref l) = e.node {
1473 if let LitKind::Char(_) = l.node {
1474 if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
1475 let msg = "casting character literal to u8. `char`s \
1476 are 4 bytes wide in rust, so casting to u8 \
1479 "Consider using a byte literal instead:\nb{}",
1480 snippet(cx, e.span, "'x'")
1482 span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
1490 declare_clippy_lint! {
1491 /// **What it does:** Checks for comparisons where one side of the relation is
1492 /// either the minimum or maximum value for its type and warns if it involves a
1493 /// case that is always true or always false. Only integer and boolean types are
1496 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1497 /// that is is possible for `x` to be less than the minimum. Expressions like
1498 /// `max < x` are probably mistakes.
1500 /// **Known problems:** For `usize` the size of the current compile target will
1501 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1502 /// a comparison to detect target pointer width will trigger this lint. One can
1503 /// use `mem::sizeof` and compare its value or conditional compilation
1505 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1510 /// let vec: Vec<isize> = vec![];
1511 /// if vec.len() <= 0 {}
1512 /// if 100 > std::i32::MAX {}
1514 pub ABSURD_EXTREME_COMPARISONS,
1516 "a comparison with a maximum or minimum value that is always true or false"
1519 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1526 struct ExtremeExpr<'a> {
1531 enum AbsurdComparisonResult {
1534 InequalityImpossible,
1537 fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
1538 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1539 let precast_ty = cx.tables.expr_ty(cast_exp);
1540 let cast_ty = cx.tables.expr_ty(expr);
1542 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1548 fn detect_absurd_comparison<'a, 'tcx>(
1549 cx: &LateContext<'a, 'tcx>,
1553 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1554 use crate::types::AbsurdComparisonResult::*;
1555 use crate::types::ExtremeType::*;
1556 use crate::utils::comparisons::*;
1558 // absurd comparison only makes sense on primitive types
1559 // primitive types don't implement comparison operators with each other
1560 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1564 // comparisons between fix sized types and target sized types are considered unanalyzable
1565 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1569 let normalized = normalize_comparison(op, lhs, rhs);
1570 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1576 let lx = detect_extreme_expr(cx, normalized_lhs);
1577 let rx = detect_extreme_expr(cx, normalized_rhs);
1582 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1583 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1589 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1590 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1591 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1592 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1596 Rel::Ne | Rel::Eq => return None,
1600 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<ExtremeExpr<'tcx>> {
1601 use crate::types::ExtremeType::*;
1603 let ty = cx.tables.expr_ty(expr);
1605 let cv = constant(cx, cx.tables, expr)?.0;
1607 let which = match (&ty.sty, cv) {
1608 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1609 (&ty::Int(ity), Constant::Int(i))
1610 if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1615 (&ty::Bool, Constant::Bool(true)) => Maximum,
1616 (&ty::Int(ity), Constant::Int(i))
1617 if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1621 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1625 Some(ExtremeExpr { which, expr })
1628 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1629 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1630 use crate::types::AbsurdComparisonResult::*;
1631 use crate::types::ExtremeType::*;
1633 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1634 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1635 if !in_macro(expr.span) {
1636 let msg = "this comparison involving the minimum or maximum element for this \
1637 type contains a case that is always true or always false";
1639 let conclusion = match result {
1640 AlwaysFalse => "this comparison is always false".to_owned(),
1641 AlwaysTrue => "this comparison is always true".to_owned(),
1642 InequalityImpossible => format!(
1643 "the case where the two sides are not equal never occurs, consider using {} == {} \
1645 snippet(cx, lhs.span, "lhs"),
1646 snippet(cx, rhs.span, "rhs")
1651 "because {} is the {} value for this type, {}",
1652 snippet(cx, culprit.expr.span, "x"),
1653 match culprit.which {
1654 Minimum => "minimum",
1655 Maximum => "maximum",
1660 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1667 declare_clippy_lint! {
1668 /// **What it does:** Checks for comparisons where the relation is always either
1669 /// true or false, but where one side has been upcast so that the comparison is
1670 /// necessary. Only integer types are checked.
1672 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1673 /// will mistakenly imply that it is possible for `x` to be outside the range of
1676 /// **Known problems:**
1677 /// https://github.com/rust-lang/rust-clippy/issues/886
1681 /// let x : u8 = ...; (x as u32) > 300
1683 pub INVALID_UPCAST_COMPARISONS,
1685 "a comparison involving an upcast which is always true or false"
1688 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
1690 #[derive(Copy, Clone, Debug, Eq)]
1697 #[allow(clippy::cast_sign_loss)]
1698 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1701 } else if u > (i128::max_value() as u128) {
1709 impl PartialEq for FullInt {
1710 fn eq(&self, other: &Self) -> bool {
1711 self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
1715 impl PartialOrd for FullInt {
1716 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1717 Some(match (self, other) {
1718 (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
1719 (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
1720 (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
1721 (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
1725 impl Ord for FullInt {
1726 fn cmp(&self, other: &Self) -> Ordering {
1727 self.partial_cmp(other)
1728 .expect("partial_cmp for FullInt can never return None")
1732 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
1735 if let ExprKind::Cast(ref cast_exp, _) = expr.node {
1736 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1737 let cast_ty = cx.tables.expr_ty(expr);
1738 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1739 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1742 match pre_cast_ty.sty {
1743 ty::Int(int_ty) => Some(match int_ty {
1745 FullInt::S(i128::from(i8::min_value())),
1746 FullInt::S(i128::from(i8::max_value())),
1749 FullInt::S(i128::from(i16::min_value())),
1750 FullInt::S(i128::from(i16::max_value())),
1753 FullInt::S(i128::from(i32::min_value())),
1754 FullInt::S(i128::from(i32::max_value())),
1757 FullInt::S(i128::from(i64::min_value())),
1758 FullInt::S(i128::from(i64::max_value())),
1760 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
1762 FullInt::S(isize::min_value() as i128),
1763 FullInt::S(isize::max_value() as i128),
1766 ty::Uint(uint_ty) => Some(match uint_ty {
1768 FullInt::U(u128::from(u8::min_value())),
1769 FullInt::U(u128::from(u8::max_value())),
1772 FullInt::U(u128::from(u16::min_value())),
1773 FullInt::U(u128::from(u16::max_value())),
1776 FullInt::U(u128::from(u32::min_value())),
1777 FullInt::U(u128::from(u32::max_value())),
1780 FullInt::U(u128::from(u64::min_value())),
1781 FullInt::U(u128::from(u64::max_value())),
1783 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
1785 FullInt::U(usize::min_value() as u128),
1786 FullInt::U(usize::max_value() as u128),
1796 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<FullInt> {
1797 let val = constant(cx, cx.tables, expr)?.0;
1798 if let Constant::Int(const_int) = val {
1799 match cx.tables.expr_ty(expr).sty {
1800 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1801 ty::Uint(_) => Some(FullInt::U(const_int)),
1809 fn err_upcast_comparison(cx: &LateContext<'_, '_>, span: Span, expr: &Expr, always: bool) {
1810 if let ExprKind::Cast(ref cast_val, _) = expr.node {
1813 INVALID_UPCAST_COMPARISONS,
1816 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1817 snippet(cx, cast_val.span, "the expression"),
1818 if always { "true" } else { "false" },
1824 fn upcast_comparison_bounds_err<'a, 'tcx>(
1825 cx: &LateContext<'a, 'tcx>,
1827 rel: comparisons::Rel,
1828 lhs_bounds: Option<(FullInt, FullInt)>,
1833 use crate::utils::comparisons::*;
1835 if let Some((lb, ub)) = lhs_bounds {
1836 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1837 if rel == Rel::Eq || rel == Rel::Ne {
1838 if norm_rhs_val < lb || norm_rhs_val > ub {
1839 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1841 } else if match rel {
1856 Rel::Eq | Rel::Ne => unreachable!(),
1858 err_upcast_comparison(cx, span, lhs, true)
1859 } else if match rel {
1874 Rel::Eq | Rel::Ne => unreachable!(),
1876 err_upcast_comparison(cx, span, lhs, false)
1882 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1883 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
1884 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
1885 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1886 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1892 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
1893 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
1895 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
1896 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
1901 declare_clippy_lint! {
1902 /// **What it does:** Checks for public `impl` or `fn` missing generalization
1903 /// over different hashers and implicitly defaulting to the default hashing
1904 /// algorithm (SipHash).
1906 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
1909 /// **Known problems:** Suggestions for replacing constructors can contain
1910 /// false-positives. Also applying suggestions can require modification of other
1911 /// pieces of code, possibly including external crates.
1915 /// # use std::collections::HashMap;
1916 /// # use std::hash::Hash;
1917 /// # trait Serialize {};
1918 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
1920 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
1922 pub IMPLICIT_HASHER,
1924 "missing generalization over different hashers"
1927 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
1929 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
1930 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
1931 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
1932 use syntax_pos::BytePos;
1934 fn suggestion<'a, 'tcx>(
1935 cx: &LateContext<'a, 'tcx>,
1936 db: &mut DiagnosticBuilder<'_>,
1937 generics_span: Span,
1938 generics_suggestion_span: Span,
1939 target: &ImplicitHasherType<'_>,
1940 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
1942 let generics_snip = snippet(cx, generics_span, "");
1944 let generics_snip = if generics_snip.is_empty() {
1947 &generics_snip[1..generics_snip.len() - 1]
1952 "consider adding a type parameter".to_string(),
1955 generics_suggestion_span,
1957 "<{}{}S: ::std::hash::BuildHasher{}>",
1959 if generics_snip.is_empty() { "" } else { ", " },
1960 if vis.suggestions.is_empty() {
1963 // request users to add `Default` bound so that generic constructors can be used
1970 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
1975 if !vis.suggestions.is_empty() {
1976 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
1980 if !cx.access_levels.is_exported(item.hir_id) {
1985 ItemKind::Impl(_, _, _, ref generics, _, ref ty, ref items) => {
1986 let mut vis = ImplicitHasherTypeVisitor::new(cx);
1989 for target in &vis.found {
1990 if differing_macro_contexts(item.span, target.span()) {
1994 let generics_suggestion_span = generics.span.substitute_dummy({
1995 let pos = snippet_opt(cx, item.span.until(target.span()))
1996 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
1997 if let Some(pos) = pos {
1998 Span::new(pos, pos, item.span.data().ctxt)
2004 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2005 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2006 ctr_vis.visit_impl_item(item);
2014 "impl for `{}` should be generalized over different hashers",
2018 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2023 ItemKind::Fn(ref decl, .., ref generics, body_id) => {
2024 let body = cx.tcx.hir().body(body_id);
2026 for ty in &decl.inputs {
2027 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2030 for target in &vis.found {
2031 let generics_suggestion_span = generics.span.substitute_dummy({
2032 let pos = snippet_opt(cx, item.span.until(body.arguments[0].pat.span))
2034 let i = snip.find("fn")?;
2035 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2037 .expect("failed to create span for type parameters");
2038 Span::new(pos, pos, item.span.data().ctxt)
2041 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2042 ctr_vis.visit_body(body);
2049 "parameter of type `{}` should be generalized over different hashers",
2053 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2064 enum ImplicitHasherType<'tcx> {
2065 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2066 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2069 impl<'tcx> ImplicitHasherType<'tcx> {
2070 /// Checks that `ty` is a target type without a BuildHasher.
2071 fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty) -> Option<Self> {
2072 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.node {
2073 let params: Vec<_> = path
2081 .filter_map(|arg| match arg {
2082 GenericArg::Type(ty) => Some(ty),
2086 let params_len = params.len();
2088 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2090 if match_path(path, &paths::HASHMAP) && params_len == 2 {
2091 Some(ImplicitHasherType::HashMap(
2094 snippet(cx, params[0].span, "K"),
2095 snippet(cx, params[1].span, "V"),
2097 } else if match_path(path, &paths::HASHSET) && params_len == 1 {
2098 Some(ImplicitHasherType::HashSet(
2101 snippet(cx, params[0].span, "T"),
2111 fn type_name(&self) -> &'static str {
2113 ImplicitHasherType::HashMap(..) => "HashMap",
2114 ImplicitHasherType::HashSet(..) => "HashSet",
2118 fn type_arguments(&self) -> String {
2120 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2121 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2125 fn ty(&self) -> Ty<'tcx> {
2127 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2131 fn span(&self) -> Span {
2133 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2138 struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
2139 cx: &'a LateContext<'a, 'tcx>,
2140 found: Vec<ImplicitHasherType<'tcx>>,
2143 impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
2144 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
2145 Self { cx, found: vec![] }
2149 impl<'a, 'tcx: 'a> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2150 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
2151 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2152 self.found.push(target);
2158 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2159 NestedVisitorMap::None
2163 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2164 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx: 'a + 'b> {
2165 cx: &'a LateContext<'a, 'tcx>,
2166 body: &'a TypeckTables<'tcx>,
2167 target: &'b ImplicitHasherType<'tcx>,
2168 suggestions: BTreeMap<Span, String>,
2171 impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2172 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2177 suggestions: BTreeMap::new(),
2182 impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2183 fn visit_body(&mut self, body: &'tcx Body) {
2184 let prev_body = self.body;
2185 self.body = self.cx.tcx.body_tables(body.id());
2186 walk_body(self, body);
2187 self.body = prev_body;
2190 fn visit_expr(&mut self, e: &'tcx Expr) {
2192 if let ExprKind::Call(ref fun, ref args) = e.node;
2193 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.node;
2194 if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.node;
2196 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
2200 if match_path(ty_path, &paths::HASHMAP) {
2201 if method.ident.name == "new" {
2203 .insert(e.span, "HashMap::default()".to_string());
2204 } else if method.ident.name == "with_capacity" {
2205 self.suggestions.insert(
2208 "HashMap::with_capacity_and_hasher({}, Default::default())",
2209 snippet(self.cx, args[0].span, "capacity"),
2213 } else if match_path(ty_path, &paths::HASHSET) {
2214 if method.ident.name == "new" {
2216 .insert(e.span, "HashSet::default()".to_string());
2217 } else if method.ident.name == "with_capacity" {
2218 self.suggestions.insert(
2221 "HashSet::with_capacity_and_hasher({}, Default::default())",
2222 snippet(self.cx, args[0].span, "capacity"),
2233 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2234 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
2238 declare_clippy_lint! {
2239 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2241 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2242 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2245 /// **Known problems:** None.
2251 /// *(r as *const _ as *mut _) += 1;
2256 /// Instead consider using interior mutability types.
2259 /// use std::cell::UnsafeCell;
2261 /// fn x(r: &UnsafeCell<i32>) {
2267 pub CAST_REF_TO_MUT,
2269 "a cast of reference to a mutable pointer"
2272 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2274 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2275 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2277 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.node;
2278 if let ExprKind::Cast(e, t) = &e.node;
2279 if let TyKind::Ptr(MutTy { mutbl: Mutability::MutMutable, .. }) = t.node;
2280 if let ExprKind::Cast(e, t) = &e.node;
2281 if let TyKind::Ptr(MutTy { mutbl: Mutability::MutImmutable, .. }) = t.node;
2282 if let ty::Ref(..) = cx.tables.node_type(e.hir_id).sty;
2288 "casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell",