1 #![allow(rustc::default_hash_types)]
4 use std::cmp::Ordering;
5 use std::collections::BTreeMap;
7 use if_chain::if_chain;
8 use rustc::hir::map::Map;
9 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
10 use rustc::ty::layout::LayoutOf;
11 use rustc::ty::{self, InferTy, Ty, TyCtxt, TypeckTables};
12 use rustc::{declare_lint_pass, impl_lint_pass};
13 use rustc_errors::Applicability;
15 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
17 use rustc_session::declare_tool_lint;
18 use rustc_span::hygiene::{ExpnKind, MacroKind};
19 use rustc_span::source_map::Span;
20 use rustc_span::symbol::{sym, Symbol};
21 use rustc_target::spec::abi::Abi;
22 use rustc_typeck::hir_ty_to_ty;
23 use syntax::ast::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy};
24 use syntax::errors::DiagnosticBuilder;
26 use crate::consts::{constant, Constant};
27 use crate::utils::paths;
29 clip, comparisons, differing_macro_contexts, higher, in_constant, int_bits, last_path_segment, match_def_path,
30 match_path, method_chain_args, multispan_sugg, qpath_res, same_tys, sext, snippet, snippet_opt,
31 snippet_with_applicability, snippet_with_macro_callsite, span_help_and_lint, span_lint, span_lint_and_sugg,
32 span_lint_and_then, unsext,
35 declare_clippy_lint! {
36 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
38 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
39 /// the heap. So if you `Box` it, you just add another level of indirection
40 /// without any benefit whatsoever.
42 /// **Known problems:** None.
47 /// values: Box<Vec<Foo>>,
60 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
63 declare_clippy_lint! {
64 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
66 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
67 /// the heap. So if you `Box` its contents, you just add another level of indirection.
69 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
75 /// values: Vec<Box<i32>>,
88 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
91 declare_clippy_lint! {
92 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
95 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
96 /// represents an optional optional value which is logically the same thing as an optional
97 /// value but has an unneeded extra level of wrapping.
99 /// **Known problems:** None.
103 /// fn x() -> Option<Option<u32>> {
109 "usage of `Option<Option<T>>`"
112 declare_clippy_lint! {
113 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
114 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
116 /// **Why is this bad?** Gankro says:
118 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
119 /// pointers and indirection.
120 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
122 /// > "only" amortized for push/pop, should be faster in the general case for
123 /// almost every possible
124 /// > workload, and isn't even amortized at all if you can predict the capacity
127 /// > `LinkedList`s are only really good if you're doing a lot of merging or
128 /// splitting of lists.
129 /// > This is because they can just mangle some pointers instead of actually
130 /// copying the data. Even
131 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
132 /// can still be better
133 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
135 /// **Known problems:** False positives – the instances where using a
136 /// `LinkedList` makes sense are few and far between, but they can still happen.
140 /// # use std::collections::LinkedList;
141 /// let x: LinkedList<usize> = LinkedList::new();
145 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
148 declare_clippy_lint! {
149 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
151 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
154 /// **Known problems:** None.
158 /// fn foo(bar: &Box<T>) { ... }
164 /// fn foo(bar: &T) { ... }
168 "a borrow of a boxed type"
171 declare_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX]);
173 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types {
176 cx: &LateContext<'_, '_>,
183 // Skip trait implementations; see issue #605.
184 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
185 if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.kind {
190 check_fn_decl(cx, decl);
193 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) {
194 check_ty(cx, &field.ty, false);
197 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &TraitItem<'_>) {
199 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
200 TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
205 fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local<'_>) {
206 if let Some(ref ty) = local.ty {
207 check_ty(cx, ty, true);
212 fn check_fn_decl(cx: &LateContext<'_, '_>, decl: &FnDecl<'_>) {
213 for input in decl.inputs {
214 check_ty(cx, input, false);
217 if let FunctionRetTy::Return(ref ty) = decl.output {
218 check_ty(cx, ty, false);
222 /// Checks if `qpath` has last segment with type parameter matching `path`
223 fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&str]) -> bool {
224 let last = last_path_segment(qpath);
226 if let Some(ref params) = last.args;
227 if !params.parenthesized;
228 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
229 GenericArg::Type(ty) => Some(ty),
232 if let TyKind::Path(ref qpath) = ty.kind;
233 if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
234 if match_def_path(cx, did, path);
242 /// Recursively check for `TypePass` lints in the given type. Stop at the first
245 /// The parameter `is_local` distinguishes the context of the type; types from
246 /// local bindings should only be checked for the `BORROWED_BOX` lint.
247 #[allow(clippy::too_many_lines)]
248 fn check_ty(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
249 if hir_ty.span.from_expansion() {
253 TyKind::Path(ref qpath) if !is_local => {
254 let hir_id = hir_ty.hir_id;
255 let res = qpath_res(cx, qpath, hir_id);
256 if let Some(def_id) = res.opt_def_id() {
257 if Some(def_id) == cx.tcx.lang_items().owned_box() {
258 if match_type_parameter(cx, qpath, &paths::VEC) {
263 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
264 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
266 return; // don't recurse into the type
268 } else if cx.tcx.is_diagnostic_item(Symbol::intern("vec_type"), def_id) {
270 // Get the _ part of Vec<_>
271 if let Some(ref last) = last_path_segment(qpath).args;
272 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
273 GenericArg::Type(ty) => Some(ty),
276 // ty is now _ at this point
277 if let TyKind::Path(ref ty_qpath) = ty.kind;
278 let res = qpath_res(cx, ty_qpath, ty.hir_id);
279 if let Some(def_id) = res.opt_def_id();
280 if Some(def_id) == cx.tcx.lang_items().owned_box();
281 // At this point, we know ty is Box<T>, now get T
282 if let Some(ref last) = last_path_segment(ty_qpath).args;
283 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
284 GenericArg::Type(ty) => Some(ty),
288 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
289 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env) {
294 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
296 format!("Vec<{}>", ty_ty),
297 Applicability::MachineApplicable,
299 return; // don't recurse into the type
303 } else if match_def_path(cx, def_id, &paths::OPTION) {
304 if match_type_parameter(cx, qpath, &paths::OPTION) {
309 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
310 enum if you need to distinguish all 3 cases",
312 return; // don't recurse into the type
314 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
319 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
320 "a `VecDeque` might work",
322 return; // don't recurse into the type
326 QPath::Resolved(Some(ref ty), ref p) => {
327 check_ty(cx, ty, is_local);
328 for ty in p.segments.iter().flat_map(|seg| {
331 .map_or_else(|| [].iter(), |params| params.args.iter())
332 .filter_map(|arg| match arg {
333 GenericArg::Type(ty) => Some(ty),
337 check_ty(cx, ty, is_local);
340 QPath::Resolved(None, ref p) => {
341 for ty in p.segments.iter().flat_map(|seg| {
344 .map_or_else(|| [].iter(), |params| params.args.iter())
345 .filter_map(|arg| match arg {
346 GenericArg::Type(ty) => Some(ty),
350 check_ty(cx, ty, is_local);
353 QPath::TypeRelative(ref ty, ref seg) => {
354 check_ty(cx, ty, is_local);
355 if let Some(ref params) = seg.args {
356 for ty in params.args.iter().filter_map(|arg| match arg {
357 GenericArg::Type(ty) => Some(ty),
360 check_ty(cx, ty, is_local);
366 TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
368 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
369 check_ty(cx, ty, is_local)
371 TyKind::Tup(tys) => {
373 check_ty(cx, ty, is_local);
380 fn check_ty_rptr(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool, lt: &Lifetime, mut_ty: &MutTy<'_>) {
381 match mut_ty.ty.kind {
382 TyKind::Path(ref qpath) => {
383 let hir_id = mut_ty.ty.hir_id;
384 let def = qpath_res(cx, qpath, hir_id);
386 if let Some(def_id) = def.opt_def_id();
387 if Some(def_id) == cx.tcx.lang_items().owned_box();
388 if let QPath::Resolved(None, ref path) = *qpath;
389 if let [ref bx] = *path.segments;
390 if let Some(ref params) = bx.args;
391 if !params.parenthesized;
392 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
393 GenericArg::Type(ty) => Some(ty),
397 if is_any_trait(inner) {
398 // Ignore `Box<Any>` types; see issue #1884 for details.
402 let ltopt = if lt.is_elided() {
405 format!("{} ", lt.name.ident().as_str())
407 let mutopt = if mut_ty.mutbl == Mutability::Mut {
412 let mut applicability = Applicability::MachineApplicable;
417 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
423 &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
425 Applicability::Unspecified,
427 return; // don't recurse into the type
430 check_ty(cx, &mut_ty.ty, is_local);
432 _ => check_ty(cx, &mut_ty.ty, is_local),
436 // Returns true if given type is `Any` trait.
437 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
439 if let TyKind::TraitObject(ref traits, _) = t.kind;
440 if !traits.is_empty();
441 // Only Send/Sync can be used as additional traits, so it is enough to
442 // check only the first trait.
443 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
452 declare_clippy_lint! {
453 /// **What it does:** Checks for binding a unit value.
455 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
456 /// binding one is kind of pointless.
458 /// **Known problems:** None.
468 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
471 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
473 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue {
474 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) {
475 if let StmtKind::Local(ref local) = stmt.kind {
476 if is_unit(cx.tables.pat_ty(&local.pat)) {
477 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
480 if higher::is_from_for_desugar(local) {
483 span_lint_and_then(cx, LET_UNIT_VALUE, stmt.span, "this let-binding has unit value", |db| {
484 if let Some(expr) = &local.init {
485 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
488 "omit the `let` binding",
489 format!("{};", snip),
490 Applicability::MachineApplicable, // snippet
499 declare_clippy_lint! {
500 /// **What it does:** Checks for comparisons to unit. This includes all binary
501 /// comparisons (like `==` and `<`) and asserts.
503 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
504 /// clumsily written constant. Mostly this happens when someone accidentally
505 /// adds semicolons at the end of the operands.
507 /// **Known problems:** None.
538 /// assert_eq!({ foo(); }, { bar(); });
540 /// will always succeed
543 "comparing unit values"
546 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
548 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
549 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
550 if expr.span.from_expansion() {
551 if let Some(callee) = expr.span.source_callee() {
552 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
553 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
555 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
556 let result = match &*symbol.as_str() {
557 "assert_eq" | "debug_assert_eq" => "succeed",
558 "assert_ne" | "debug_assert_ne" => "fail",
566 "`{}` of unit values detected. This will always {}",
577 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
579 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
580 let result = match op {
581 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
589 "{}-comparison of unit values detected. This will always be {}",
599 declare_clippy_lint! {
600 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
601 /// unit literal (`()`).
603 /// **Why is this bad?** This is likely the result of an accidental semicolon.
605 /// **Known problems:** None.
616 "passing unit to a function"
619 declare_lint_pass!(UnitArg => [UNIT_ARG]);
621 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
622 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
623 if expr.span.from_expansion() {
627 // apparently stuff in the desugaring of `?` can trigger this
628 // so check for that here
629 // only the calls to `Try::from_error` is marked as desugared,
630 // so we need to check both the current Expr and its parent.
631 if is_questionmark_desugar_marked_call(expr) {
635 let map = &cx.tcx.hir();
636 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
637 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
638 if is_questionmark_desugar_marked_call(parent_expr);
645 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args) => {
647 if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
648 if let ExprKind::Match(.., match_source) = &arg.kind {
649 if *match_source == MatchSource::TryDesugar {
658 "passing a unit value to a function",
659 "if you intended to pass a unit value, use a unit literal instead",
661 Applicability::MachineApplicable,
671 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
672 use rustc_span::hygiene::DesugaringKind;
673 if let ExprKind::Call(ref callee, _) = expr.kind {
674 callee.span.is_desugaring(DesugaringKind::QuestionMark)
680 fn is_unit(ty: Ty<'_>) -> bool {
682 ty::Tuple(slice) if slice.is_empty() => true,
687 fn is_unit_literal(expr: &Expr<'_>) -> bool {
689 ExprKind::Tup(ref slice) if slice.is_empty() => true,
694 declare_clippy_lint! {
695 /// **What it does:** Checks for casts from any numerical to a float type where
696 /// the receiving type cannot store all values from the original type without
697 /// rounding errors. This possible rounding is to be expected, so this lint is
698 /// `Allow` by default.
700 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
701 /// or any 64-bit integer to `f64`.
703 /// **Why is this bad?** It's not bad at all. But in some applications it can be
704 /// helpful to know where precision loss can take place. This lint can help find
705 /// those places in the code.
707 /// **Known problems:** None.
711 /// let x = std::u64::MAX;
714 pub CAST_PRECISION_LOSS,
716 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
719 declare_clippy_lint! {
720 /// **What it does:** Checks for casts from a signed to an unsigned numerical
721 /// type. In this case, negative values wrap around to large positive values,
722 /// which can be quite surprising in practice. However, as the cast works as
723 /// defined, this lint is `Allow` by default.
725 /// **Why is this bad?** Possibly surprising results. You can activate this lint
726 /// as a one-time check to see where numerical wrapping can arise.
728 /// **Known problems:** None.
733 /// y as u128; // will return 18446744073709551615
737 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
740 declare_clippy_lint! {
741 /// **What it does:** Checks for casts between numerical types that may
742 /// truncate large values. This is expected behavior, so the cast is `Allow` by
745 /// **Why is this bad?** In some problem domains, it is good practice to avoid
746 /// truncation. This lint can be activated to help assess where additional
747 /// checks could be beneficial.
749 /// **Known problems:** None.
753 /// fn as_u8(x: u64) -> u8 {
757 pub CAST_POSSIBLE_TRUNCATION,
759 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
762 declare_clippy_lint! {
763 /// **What it does:** Checks for casts from an unsigned type to a signed type of
764 /// the same size. Performing such a cast is a 'no-op' for the compiler,
765 /// i.e., nothing is changed at the bit level, and the binary representation of
766 /// the value is reinterpreted. This can cause wrapping if the value is too big
767 /// for the target signed type. However, the cast works as defined, so this lint
768 /// is `Allow` by default.
770 /// **Why is this bad?** While such a cast is not bad in itself, the results can
771 /// be surprising when this is not the intended behavior, as demonstrated by the
774 /// **Known problems:** None.
778 /// std::u32::MAX as i32; // will yield a value of `-1`
780 pub CAST_POSSIBLE_WRAP,
782 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
785 declare_clippy_lint! {
786 /// **What it does:** Checks for casts between numerical types that may
787 /// be replaced by safe conversion functions.
789 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
790 /// conversions, including silently lossy conversions. Conversion functions such
791 /// as `i32::from` will only perform lossless conversions. Using the conversion
792 /// functions prevents conversions from turning into silent lossy conversions if
793 /// the types of the input expressions ever change, and make it easier for
794 /// people reading the code to know that the conversion is lossless.
796 /// **Known problems:** None.
800 /// fn as_u64(x: u8) -> u64 {
805 /// Using `::from` would look like this:
808 /// fn as_u64(x: u8) -> u64 {
814 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
817 declare_clippy_lint! {
818 /// **What it does:** Checks for casts to the same type.
820 /// **Why is this bad?** It's just unnecessary.
822 /// **Known problems:** None.
826 /// let _ = 2i32 as i32;
828 pub UNNECESSARY_CAST,
830 "cast to the same type, e.g., `x as i32` where `x: i32`"
833 declare_clippy_lint! {
834 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
835 /// more-strictly-aligned pointer
837 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
840 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
841 /// on the resulting pointer is fine.
845 /// let _ = (&1u8 as *const u8) as *const u16;
846 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
848 pub CAST_PTR_ALIGNMENT,
850 "cast from a pointer to a more-strictly-aligned pointer"
853 declare_clippy_lint! {
854 /// **What it does:** Checks for casts of function pointers to something other than usize
856 /// **Why is this bad?**
857 /// Casting a function pointer to anything other than usize/isize is not portable across
858 /// architectures, because you end up losing bits if the target type is too small or end up with a
859 /// bunch of extra bits that waste space and add more instructions to the final binary than
860 /// strictly necessary for the problem
862 /// Casting to isize also doesn't make sense since there are no signed addresses.
868 /// fn fun() -> i32 { 1 }
869 /// let a = fun as i64;
872 /// fn fun2() -> i32 { 1 }
873 /// let a = fun2 as usize;
875 pub FN_TO_NUMERIC_CAST,
877 "casting a function pointer to a numeric type other than usize"
880 declare_clippy_lint! {
881 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
884 /// **Why is this bad?**
885 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
886 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
887 /// a comment) to perform the truncation.
893 /// fn fn1() -> i16 {
896 /// let _ = fn1 as i32;
898 /// // Better: Cast to usize first, then comment with the reason for the truncation
899 /// fn fn2() -> i16 {
902 /// let fn_ptr = fn2 as usize;
903 /// let fn_ptr_truncated = fn_ptr as i32;
905 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
907 "casting a function pointer to a numeric type not wide enough to store the address"
910 /// Returns the size in bits of an integral type.
911 /// Will return 0 if the type is not an int or uint variant
912 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
914 ty::Int(i) => match i {
915 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
922 ty::Uint(i) => match i {
923 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
934 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
936 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => true,
941 fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
942 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
943 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
944 let arch_dependent_str = "on targets with 64-bit wide pointers ";
945 let from_nbits_str = if arch_dependent {
947 } else if is_isize_or_usize(cast_from) {
948 "32 or 64".to_owned()
950 int_ty_to_nbits(cast_from, cx.tcx).to_string()
957 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
958 but `{1}`'s mantissa is only {4} bits wide)",
960 if cast_to_f64 { "f64" } else { "f32" },
961 if arch_dependent { arch_dependent_str } else { "" },
968 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
969 if let ExprKind::Binary(_, _, _) = op.kind {
970 if snip.starts_with('(') && snip.ends_with(')') {
977 fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
978 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
979 if in_constant(cx, expr.hir_id) {
982 // The suggestion is to use a function call, so if the original expression
983 // has parens on the outside, they are no longer needed.
984 let mut applicability = Applicability::MachineApplicable;
985 let opt = snippet_opt(cx, op.span);
986 let sugg = if let Some(ref snip) = opt {
987 if should_strip_parens(op, snip) {
988 &snip[1..snip.len() - 1]
993 applicability = Applicability::HasPlaceholders;
1002 "casting `{}` to `{}` may become silently lossy if you later change the type",
1006 format!("{}::from({})", cast_to, sugg),
1017 fn check_loss_of_sign(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1018 if !cast_from.is_signed() || cast_to.is_signed() {
1022 // don't lint for positive constants
1023 let const_val = constant(cx, &cx.tables, op);
1025 if let Some((const_val, _)) = const_val;
1026 if let Constant::Int(n) = const_val;
1027 if let ty::Int(ity) = cast_from.kind;
1028 if sext(cx.tcx, n, ity) >= 0;
1034 // don't lint for the result of methods that always return non-negative values
1035 if let ExprKind::MethodCall(ref path, _, _) = op.kind {
1036 let mut method_name = path.ident.name.as_str();
1037 let whitelisted_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1040 if method_name == "unwrap";
1041 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1042 if let ExprKind::MethodCall(ref inner_path, _, _) = &arglist[0][0].kind;
1044 method_name = inner_path.ident.name.as_str();
1048 if whitelisted_methods.iter().any(|&name| method_name == name) {
1058 "casting `{}` to `{}` may lose the sign of the value",
1064 fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1065 let arch_64_suffix = " on targets with 64-bit wide pointers";
1066 let arch_32_suffix = " on targets with 32-bit wide pointers";
1067 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1068 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1069 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1070 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1071 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1072 (true, true) | (false, false) => (
1073 to_nbits < from_nbits,
1075 to_nbits == from_nbits && cast_unsigned_to_signed,
1085 to_nbits <= 32 && cast_unsigned_to_signed,
1091 cast_unsigned_to_signed,
1092 if from_nbits == 64 {
1099 if span_truncation {
1102 CAST_POSSIBLE_TRUNCATION,
1105 "casting `{}` to `{}` may truncate the value{}",
1108 match suffix_truncation {
1109 ArchSuffix::_32 => arch_32_suffix,
1110 ArchSuffix::_64 => arch_64_suffix,
1111 ArchSuffix::None => "",
1122 "casting `{}` to `{}` may wrap around the value{}",
1126 ArchSuffix::_32 => arch_32_suffix,
1127 ArchSuffix::_64 => arch_64_suffix,
1128 ArchSuffix::None => "",
1135 fn check_lossless(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1136 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1137 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1138 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1139 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1141 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1145 declare_lint_pass!(Casts => [
1146 CAST_PRECISION_LOSS,
1148 CAST_POSSIBLE_TRUNCATION,
1154 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1157 // Check if the given type is either `core::ffi::c_void` or
1158 // one of the platform specific `libc::<platform>::c_void` of libc.
1159 fn is_c_void(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1160 if let ty::Adt(adt, _) = ty.kind {
1161 let names = cx.get_def_path(adt.did);
1163 if names.is_empty() {
1166 if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1173 /// Returns the mantissa bits wide of a fp type.
1174 /// Will return 0 if the type is not a fp
1175 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1177 ty::Float(FloatTy::F32) => 23,
1178 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1183 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
1184 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1185 if expr.span.from_expansion() {
1188 if let ExprKind::Cast(ref ex, _) = expr.kind {
1189 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
1190 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1191 if let ExprKind::Lit(ref lit) = ex.kind {
1192 if let LitKind::Int(n, _) = lit.node {
1193 if cast_to.is_floating_point() {
1194 let from_nbits = 128 - n.leading_zeros();
1195 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1196 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits {
1201 &format!("casting integer literal to `{}` is unnecessary", cast_to),
1203 format!("{}_{}", n, cast_to),
1204 Applicability::MachineApplicable,
1211 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1213 if cast_from.kind == cast_to.kind && !in_external_macro(cx.sess(), expr.span) {
1219 "casting to the same type is unnecessary (`{}` -> `{}`)",
1227 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1228 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1231 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1236 fn lint_numeric_casts<'tcx>(
1237 cx: &LateContext<'_, 'tcx>,
1239 cast_expr: &Expr<'_>,
1240 cast_from: Ty<'tcx>,
1243 match (cast_from.is_integral(), cast_to.is_integral()) {
1245 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1246 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind {
1251 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1252 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1254 if from_nbits < to_nbits {
1255 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1261 CAST_POSSIBLE_TRUNCATION,
1263 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1265 if !cast_to.is_signed() {
1271 "casting `{}` to `{}` may lose the sign of the value",
1278 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1279 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1280 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1283 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind, &cast_to.kind) {
1286 CAST_POSSIBLE_TRUNCATION,
1288 "casting `f64` to `f32` may truncate the value",
1291 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind, &cast_to.kind) {
1292 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1298 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1300 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind;
1301 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind;
1302 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1303 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1304 if from_layout.align.abi < to_layout.align.abi;
1305 // with c_void, we inherently need to trust the user
1306 if !is_c_void(cx, from_ptr_ty.ty);
1307 // when casting from a ZST, we don't know enough to properly lint
1308 if !from_layout.is_zst();
1315 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1318 from_layout.align.abi.bytes(),
1319 to_layout.align.abi.bytes(),
1326 fn lint_fn_to_numeric_cast(
1327 cx: &LateContext<'_, '_>,
1329 cast_expr: &Expr<'_>,
1333 // We only want to check casts to `ty::Uint` or `ty::Int`
1334 match cast_to.kind {
1335 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1338 match cast_from.kind {
1339 ty::FnDef(..) | ty::FnPtr(_) => {
1340 let mut applicability = Applicability::MaybeIncorrect;
1341 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1343 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1344 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1347 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1350 "casting function pointer `{}` to `{}`, which truncates the value",
1351 from_snippet, cast_to
1354 format!("{} as usize", from_snippet),
1357 } else if cast_to.kind != ty::Uint(UintTy::Usize) {
1362 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1364 format!("{} as usize", from_snippet),
1373 declare_clippy_lint! {
1374 /// **What it does:** Checks for types used in structs, parameters and `let`
1375 /// declarations above a certain complexity threshold.
1377 /// **Why is this bad?** Too complex types make the code less readable. Consider
1378 /// using a `type` definition to simplify them.
1380 /// **Known problems:** None.
1384 /// # use std::rc::Rc;
1386 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1389 pub TYPE_COMPLEXITY,
1391 "usage of very complex types that might be better factored into `type` definitions"
1394 pub struct TypeComplexity {
1398 impl TypeComplexity {
1400 pub fn new(threshold: u64) -> Self {
1405 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1407 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity {
1410 cx: &LateContext<'a, 'tcx>,
1412 decl: &'tcx FnDecl<'_>,
1417 self.check_fndecl(cx, decl);
1420 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField<'_>) {
1421 // enum variants are also struct fields now
1422 self.check_type(cx, &field.ty);
1425 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
1427 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1428 // functions, enums, structs, impls and traits are covered
1433 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
1435 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1436 TraitItemKind::Method(FnSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1437 // methods with default impl are covered by check_fn
1442 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
1444 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1445 // methods are covered by check_fn
1450 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
1451 if let Some(ref ty) = local.ty {
1452 self.check_type(cx, ty);
1457 impl<'a, 'tcx> TypeComplexity {
1458 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl<'_>) {
1459 for arg in decl.inputs {
1460 self.check_type(cx, arg);
1462 if let FunctionRetTy::Return(ref ty) = decl.output {
1463 self.check_type(cx, ty);
1467 fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty<'_>) {
1468 if ty.span.from_expansion() {
1472 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1473 visitor.visit_ty(ty);
1477 if score > self.threshold {
1482 "very complex type used. Consider factoring parts into `type` definitions",
1488 /// Walks a type and assigns a complexity score to it.
1489 struct TypeComplexityVisitor {
1490 /// total complexity score of the type
1492 /// current nesting level
1496 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1497 type Map = Map<'tcx>;
1499 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1500 let (add_score, sub_nest) = match ty.kind {
1501 // _, &x and *x have only small overhead; don't mess with nesting level
1502 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1504 // the "normal" components of a type: named types, arrays/tuples
1505 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1507 // function types bring a lot of overhead
1508 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1510 TyKind::TraitObject(ref param_bounds, _) => {
1511 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1512 bound.bound_generic_params.iter().any(|gen| match gen.kind {
1513 GenericParamKind::Lifetime { .. } => true,
1517 if has_lifetime_parameters {
1518 // complex trait bounds like A<'a, 'b>
1521 // simple trait bounds like A + B
1528 self.score += add_score;
1529 self.nest += sub_nest;
1531 self.nest -= sub_nest;
1533 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1534 NestedVisitorMap::None
1538 declare_clippy_lint! {
1539 /// **What it does:** Checks for expressions where a character literal is cast
1540 /// to `u8` and suggests using a byte literal instead.
1542 /// **Why is this bad?** In general, casting values to smaller types is
1543 /// error-prone and should be avoided where possible. In the particular case of
1544 /// converting a character literal to u8, it is easy to avoid by just using a
1545 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1546 /// than `'a' as u8`.
1548 /// **Known problems:** None.
1555 /// A better version, using the byte literal:
1562 "casting a character literal to `u8` truncates"
1565 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1567 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1568 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1570 if !expr.span.from_expansion();
1571 if let ExprKind::Cast(e, _) = &expr.kind;
1572 if let ExprKind::Lit(l) = &e.kind;
1573 if let LitKind::Char(c) = l.node;
1574 if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).kind;
1576 let mut applicability = Applicability::MachineApplicable;
1577 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
1583 "casting a character literal to `u8` truncates",
1585 db.note("`char` is four bytes wide, but `u8` is a single byte");
1590 "use a byte literal instead",
1591 format!("b{}", snippet),
1601 declare_clippy_lint! {
1602 /// **What it does:** Checks for comparisons where one side of the relation is
1603 /// either the minimum or maximum value for its type and warns if it involves a
1604 /// case that is always true or always false. Only integer and boolean types are
1607 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1608 /// that it is possible for `x` to be less than the minimum. Expressions like
1609 /// `max < x` are probably mistakes.
1611 /// **Known problems:** For `usize` the size of the current compile target will
1612 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1613 /// a comparison to detect target pointer width will trigger this lint. One can
1614 /// use `mem::sizeof` and compare its value or conditional compilation
1616 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1621 /// let vec: Vec<isize> = vec![];
1622 /// if vec.len() <= 0 {}
1623 /// if 100 > std::i32::MAX {}
1625 pub ABSURD_EXTREME_COMPARISONS,
1627 "a comparison with a maximum or minimum value that is always true or false"
1630 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1637 struct ExtremeExpr<'a> {
1642 enum AbsurdComparisonResult {
1645 InequalityImpossible,
1648 fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1649 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1650 let precast_ty = cx.tables.expr_ty(cast_exp);
1651 let cast_ty = cx.tables.expr_ty(expr);
1653 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1659 fn detect_absurd_comparison<'a, 'tcx>(
1660 cx: &LateContext<'a, 'tcx>,
1662 lhs: &'tcx Expr<'_>,
1663 rhs: &'tcx Expr<'_>,
1664 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1665 use crate::types::AbsurdComparisonResult::*;
1666 use crate::types::ExtremeType::*;
1667 use crate::utils::comparisons::*;
1669 // absurd comparison only makes sense on primitive types
1670 // primitive types don't implement comparison operators with each other
1671 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1675 // comparisons between fix sized types and target sized types are considered unanalyzable
1676 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1680 let normalized = normalize_comparison(op, lhs, rhs);
1681 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1687 let lx = detect_extreme_expr(cx, normalized_lhs);
1688 let rx = detect_extreme_expr(cx, normalized_rhs);
1693 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1694 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1700 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1701 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1702 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1703 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1707 Rel::Ne | Rel::Eq => return None,
1711 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
1712 use crate::types::ExtremeType::*;
1714 let ty = cx.tables.expr_ty(expr);
1716 let cv = constant(cx, cx.tables, expr)?.0;
1718 let which = match (&ty.kind, cv) {
1719 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1720 (&ty::Int(ity), Constant::Int(i))
1721 if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1726 (&ty::Bool, Constant::Bool(true)) => Maximum,
1727 (&ty::Int(ity), Constant::Int(i))
1728 if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1732 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1736 Some(ExtremeExpr { which, expr })
1739 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1740 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1741 use crate::types::AbsurdComparisonResult::*;
1742 use crate::types::ExtremeType::*;
1744 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
1745 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1746 if !expr.span.from_expansion() {
1747 let msg = "this comparison involving the minimum or maximum element for this \
1748 type contains a case that is always true or always false";
1750 let conclusion = match result {
1751 AlwaysFalse => "this comparison is always false".to_owned(),
1752 AlwaysTrue => "this comparison is always true".to_owned(),
1753 InequalityImpossible => format!(
1754 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
1756 snippet(cx, lhs.span, "lhs"),
1757 snippet(cx, rhs.span, "rhs")
1762 "because `{}` is the {} value for this type, {}",
1763 snippet(cx, culprit.expr.span, "x"),
1764 match culprit.which {
1765 Minimum => "minimum",
1766 Maximum => "maximum",
1771 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1778 declare_clippy_lint! {
1779 /// **What it does:** Checks for comparisons where the relation is always either
1780 /// true or false, but where one side has been upcast so that the comparison is
1781 /// necessary. Only integer types are checked.
1783 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1784 /// will mistakenly imply that it is possible for `x` to be outside the range of
1787 /// **Known problems:**
1788 /// https://github.com/rust-lang/rust-clippy/issues/886
1793 /// (x as u32) > 300;
1795 pub INVALID_UPCAST_COMPARISONS,
1797 "a comparison involving an upcast which is always true or false"
1800 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
1802 #[derive(Copy, Clone, Debug, Eq)]
1809 #[allow(clippy::cast_sign_loss)]
1811 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1814 } else if u > (i128::max_value() as u128) {
1822 impl PartialEq for FullInt {
1824 fn eq(&self, other: &Self) -> bool {
1825 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
1829 impl PartialOrd for FullInt {
1831 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1832 Some(match (self, other) {
1833 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
1834 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
1835 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
1836 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
1840 impl Ord for FullInt {
1842 fn cmp(&self, other: &Self) -> Ordering {
1843 self.partial_cmp(other)
1844 .expect("`partial_cmp` for FullInt can never return `None`")
1848 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
1851 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1852 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1853 let cast_ty = cx.tables.expr_ty(expr);
1854 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1855 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1858 match pre_cast_ty.kind {
1859 ty::Int(int_ty) => Some(match int_ty {
1861 FullInt::S(i128::from(i8::min_value())),
1862 FullInt::S(i128::from(i8::max_value())),
1865 FullInt::S(i128::from(i16::min_value())),
1866 FullInt::S(i128::from(i16::max_value())),
1869 FullInt::S(i128::from(i32::min_value())),
1870 FullInt::S(i128::from(i32::max_value())),
1873 FullInt::S(i128::from(i64::min_value())),
1874 FullInt::S(i128::from(i64::max_value())),
1876 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
1878 FullInt::S(isize::min_value() as i128),
1879 FullInt::S(isize::max_value() as i128),
1882 ty::Uint(uint_ty) => Some(match uint_ty {
1884 FullInt::U(u128::from(u8::min_value())),
1885 FullInt::U(u128::from(u8::max_value())),
1888 FullInt::U(u128::from(u16::min_value())),
1889 FullInt::U(u128::from(u16::max_value())),
1892 FullInt::U(u128::from(u32::min_value())),
1893 FullInt::U(u128::from(u32::max_value())),
1896 FullInt::U(u128::from(u64::min_value())),
1897 FullInt::U(u128::from(u64::max_value())),
1899 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
1901 FullInt::U(usize::min_value() as u128),
1902 FullInt::U(usize::max_value() as u128),
1912 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
1913 let val = constant(cx, cx.tables, expr)?.0;
1914 if let Constant::Int(const_int) = val {
1915 match cx.tables.expr_ty(expr).kind {
1916 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1917 ty::Uint(_) => Some(FullInt::U(const_int)),
1925 fn err_upcast_comparison(cx: &LateContext<'_, '_>, span: Span, expr: &Expr<'_>, always: bool) {
1926 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
1929 INVALID_UPCAST_COMPARISONS,
1932 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1933 snippet(cx, cast_val.span, "the expression"),
1934 if always { "true" } else { "false" },
1940 fn upcast_comparison_bounds_err<'a, 'tcx>(
1941 cx: &LateContext<'a, 'tcx>,
1943 rel: comparisons::Rel,
1944 lhs_bounds: Option<(FullInt, FullInt)>,
1945 lhs: &'tcx Expr<'_>,
1946 rhs: &'tcx Expr<'_>,
1949 use crate::utils::comparisons::*;
1951 if let Some((lb, ub)) = lhs_bounds {
1952 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1953 if rel == Rel::Eq || rel == Rel::Ne {
1954 if norm_rhs_val < lb || norm_rhs_val > ub {
1955 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1957 } else if match rel {
1972 Rel::Eq | Rel::Ne => unreachable!(),
1974 err_upcast_comparison(cx, span, lhs, true)
1975 } else if match rel {
1990 Rel::Eq | Rel::Ne => unreachable!(),
1992 err_upcast_comparison(cx, span, lhs, false)
1998 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1999 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2000 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2001 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2002 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2008 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2009 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2011 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2012 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2017 declare_clippy_lint! {
2018 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2019 /// over different hashers and implicitly defaulting to the default hashing
2020 /// algorithm (`SipHash`).
2022 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2025 /// **Known problems:** Suggestions for replacing constructors can contain
2026 /// false-positives. Also applying suggestions can require modification of other
2027 /// pieces of code, possibly including external crates.
2031 /// # use std::collections::HashMap;
2032 /// # use std::hash::{Hash, BuildHasher};
2033 /// # trait Serialize {};
2034 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2036 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2038 /// could be rewritten as
2040 /// # use std::collections::HashMap;
2041 /// # use std::hash::{Hash, BuildHasher};
2042 /// # trait Serialize {};
2043 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2045 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2047 pub IMPLICIT_HASHER,
2049 "missing generalization over different hashers"
2052 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2054 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
2055 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2056 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
2057 use rustc_span::BytePos;
2059 fn suggestion<'a, 'tcx>(
2060 cx: &LateContext<'a, 'tcx>,
2061 db: &mut DiagnosticBuilder<'_>,
2062 generics_span: Span,
2063 generics_suggestion_span: Span,
2064 target: &ImplicitHasherType<'_>,
2065 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2067 let generics_snip = snippet(cx, generics_span, "");
2069 let generics_snip = if generics_snip.is_empty() {
2072 &generics_snip[1..generics_snip.len() - 1]
2077 "consider adding a type parameter".to_string(),
2080 generics_suggestion_span,
2082 "<{}{}S: ::std::hash::BuildHasher{}>",
2084 if generics_snip.is_empty() { "" } else { ", " },
2085 if vis.suggestions.is_empty() {
2088 // request users to add `Default` bound so that generic constructors can be used
2095 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2100 if !vis.suggestions.is_empty() {
2101 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
2105 if !cx.access_levels.is_exported(item.hir_id) {
2110 ItemKind::Impl(_, _, _, ref generics, _, ref ty, ref items) => {
2111 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2114 for target in &vis.found {
2115 if differing_macro_contexts(item.span, target.span()) {
2119 let generics_suggestion_span = generics.span.substitute_dummy({
2120 let pos = snippet_opt(cx, item.span.until(target.span()))
2121 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2122 if let Some(pos) = pos {
2123 Span::new(pos, pos, item.span.data().ctxt)
2129 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2130 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2131 ctr_vis.visit_impl_item(item);
2139 "impl for `{}` should be generalized over different hashers",
2143 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2148 ItemKind::Fn(ref sig, ref generics, body_id) => {
2149 let body = cx.tcx.hir().body(body_id);
2151 for ty in sig.decl.inputs {
2152 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2155 for target in &vis.found {
2156 if in_external_macro(cx.sess(), generics.span) {
2159 let generics_suggestion_span = generics.span.substitute_dummy({
2160 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2162 let i = snip.find("fn")?;
2163 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2165 .expect("failed to create span for type parameters");
2166 Span::new(pos, pos, item.span.data().ctxt)
2169 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2170 ctr_vis.visit_body(body);
2177 "parameter of type `{}` should be generalized over different hashers",
2181 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2192 enum ImplicitHasherType<'tcx> {
2193 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2194 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2197 impl<'tcx> ImplicitHasherType<'tcx> {
2198 /// Checks that `ty` is a target type without a `BuildHasher`.
2199 fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2200 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2201 let params: Vec<_> = path
2209 .filter_map(|arg| match arg {
2210 GenericArg::Type(ty) => Some(ty),
2214 let params_len = params.len();
2216 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2218 if match_path(path, &paths::HASHMAP) && params_len == 2 {
2219 Some(ImplicitHasherType::HashMap(
2222 snippet(cx, params[0].span, "K"),
2223 snippet(cx, params[1].span, "V"),
2225 } else if match_path(path, &paths::HASHSET) && params_len == 1 {
2226 Some(ImplicitHasherType::HashSet(
2229 snippet(cx, params[0].span, "T"),
2239 fn type_name(&self) -> &'static str {
2241 ImplicitHasherType::HashMap(..) => "HashMap",
2242 ImplicitHasherType::HashSet(..) => "HashSet",
2246 fn type_arguments(&self) -> String {
2248 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2249 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2253 fn ty(&self) -> Ty<'tcx> {
2255 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2259 fn span(&self) -> Span {
2261 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2266 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2267 cx: &'a LateContext<'a, 'tcx>,
2268 found: Vec<ImplicitHasherType<'tcx>>,
2271 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2272 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
2273 Self { cx, found: vec![] }
2277 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2278 type Map = Map<'tcx>;
2280 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2281 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2282 self.found.push(target);
2288 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
2289 NestedVisitorMap::None
2293 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2294 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2295 cx: &'a LateContext<'a, 'tcx>,
2296 body: &'a TypeckTables<'tcx>,
2297 target: &'b ImplicitHasherType<'tcx>,
2298 suggestions: BTreeMap<Span, String>,
2301 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2302 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2307 suggestions: BTreeMap::new(),
2312 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2313 type Map = Map<'tcx>;
2315 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2316 let prev_body = self.body;
2317 self.body = self.cx.tcx.body_tables(body.id());
2318 walk_body(self, body);
2319 self.body = prev_body;
2322 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2324 if let ExprKind::Call(ref fun, ref args) = e.kind;
2325 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2326 if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.kind;
2328 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
2332 if match_path(ty_path, &paths::HASHMAP) {
2333 if method.ident.name == sym!(new) {
2335 .insert(e.span, "HashMap::default()".to_string());
2336 } else if method.ident.name == sym!(with_capacity) {
2337 self.suggestions.insert(
2340 "HashMap::with_capacity_and_hasher({}, Default::default())",
2341 snippet(self.cx, args[0].span, "capacity"),
2345 } else if match_path(ty_path, &paths::HASHSET) {
2346 if method.ident.name == sym!(new) {
2348 .insert(e.span, "HashSet::default()".to_string());
2349 } else if method.ident.name == sym!(with_capacity) {
2350 self.suggestions.insert(
2353 "HashSet::with_capacity_and_hasher({}, Default::default())",
2354 snippet(self.cx, args[0].span, "capacity"),
2365 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
2366 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
2370 declare_clippy_lint! {
2371 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2373 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2374 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2377 /// **Known problems:** None.
2383 /// *(r as *const _ as *mut _) += 1;
2388 /// Instead consider using interior mutability types.
2391 /// use std::cell::UnsafeCell;
2393 /// fn x(r: &UnsafeCell<i32>) {
2399 pub CAST_REF_TO_MUT,
2401 "a cast of reference to a mutable pointer"
2404 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2406 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2407 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2409 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2410 if let ExprKind::Cast(e, t) = &e.kind;
2411 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2412 if let ExprKind::Cast(e, t) = &e.kind;
2413 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2414 if let ty::Ref(..) = cx.tables.node_type(e.hir_id).kind;
2420 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",