1 #![allow(rustc::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, impl_lint_pass};
15 use rustc_errors::Applicability;
16 use rustc_session::declare_tool_lint;
17 use rustc_span::hygiene::{ExpnKind, MacroKind};
18 use rustc_span::source_map::Span;
19 use rustc_span::symbol::{sym, Symbol};
20 use rustc_target::spec::abi::Abi;
21 use rustc_typeck::hir_ty_to_ty;
22 use syntax::ast::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy};
23 use syntax::errors::DiagnosticBuilder;
25 use crate::consts::{constant, Constant};
26 use crate::utils::paths;
28 clip, comparisons, differing_macro_contexts, higher, in_constant, int_bits, last_path_segment, match_def_path,
29 match_path, method_chain_args, multispan_sugg, qpath_res, same_tys, sext, snippet, snippet_opt,
30 snippet_with_applicability, snippet_with_macro_callsite, span_help_and_lint, span_lint, span_lint_and_sugg,
31 span_lint_and_then, unsext,
34 declare_clippy_lint! {
35 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
37 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
38 /// the heap. So if you `Box` it, you just add another level of indirection
39 /// without any benefit whatsoever.
41 /// **Known problems:** None.
46 /// values: Box<Vec<Foo>>,
59 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
65 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
66 /// the heap. So if you `Box` its contents, you just add another level of indirection.
68 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
74 /// values: Vec<Box<i32>>,
87 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
90 declare_clippy_lint! {
91 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
94 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
95 /// represents an optional optional value which is logically the same thing as an optional
96 /// value but has an unneeded extra level of wrapping.
98 /// **Known problems:** None.
102 /// fn x() -> Option<Option<u32>> {
108 "usage of `Option<Option<T>>`"
111 declare_clippy_lint! {
112 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
113 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
115 /// **Why is this bad?** Gankro says:
117 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
118 /// pointers and indirection.
119 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
121 /// > "only" amortized for push/pop, should be faster in the general case for
122 /// almost every possible
123 /// > workload, and isn't even amortized at all if you can predict the capacity
126 /// > `LinkedList`s are only really good if you're doing a lot of merging or
127 /// splitting of lists.
128 /// > This is because they can just mangle some pointers instead of actually
129 /// copying the data. Even
130 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
131 /// can still be better
132 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
134 /// **Known problems:** False positives – the instances where using a
135 /// `LinkedList` makes sense are few and far between, but they can still happen.
139 /// # use std::collections::LinkedList;
140 /// let x: LinkedList<usize> = LinkedList::new();
144 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a VecDeque"
147 declare_clippy_lint! {
148 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
150 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
153 /// **Known problems:** None.
157 /// fn foo(bar: &Box<T>) { ... }
163 /// fn foo(bar: &T) { ... }
167 "a borrow of a boxed type"
170 declare_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX]);
172 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types {
175 cx: &LateContext<'_, '_>,
182 // Skip trait implementations; see issue #605.
183 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
184 if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.kind {
189 check_fn_decl(cx, decl);
192 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) {
193 check_ty(cx, &field.ty, false);
196 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &TraitItem<'_>) {
198 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
199 TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
204 fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local<'_>) {
205 if let Some(ref ty) = local.ty {
206 check_ty(cx, ty, true);
211 fn check_fn_decl(cx: &LateContext<'_, '_>, decl: &FnDecl<'_>) {
212 for input in decl.inputs {
213 check_ty(cx, input, false);
216 if let FunctionRetTy::Return(ref ty) = decl.output {
217 check_ty(cx, ty, false);
221 /// Checks if `qpath` has last segment with type parameter matching `path`
222 fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&str]) -> bool {
223 let last = last_path_segment(qpath);
225 if let Some(ref params) = last.args;
226 if !params.parenthesized;
227 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
228 GenericArg::Type(ty) => Some(ty),
231 if let TyKind::Path(ref qpath) = ty.kind;
232 if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
233 if match_def_path(cx, did, path);
241 /// Recursively check for `TypePass` lints in the given type. Stop at the first
244 /// The parameter `is_local` distinguishes the context of the type; types from
245 /// local bindings should only be checked for the `BORROWED_BOX` lint.
246 #[allow(clippy::too_many_lines)]
247 fn check_ty(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
248 if hir_ty.span.from_expansion() {
252 TyKind::Path(ref qpath) if !is_local => {
253 let hir_id = hir_ty.hir_id;
254 let res = qpath_res(cx, qpath, hir_id);
255 if let Some(def_id) = res.opt_def_id() {
256 if Some(def_id) == cx.tcx.lang_items().owned_box() {
257 if match_type_parameter(cx, qpath, &paths::VEC) {
262 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
263 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
265 return; // don't recurse into the type
267 } else if cx.tcx.is_diagnostic_item(Symbol::intern("vec_type"), def_id) {
269 // Get the _ part of Vec<_>
270 if let Some(ref last) = last_path_segment(qpath).args;
271 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
272 GenericArg::Type(ty) => Some(ty),
275 // ty is now _ at this point
276 if let TyKind::Path(ref ty_qpath) = ty.kind;
277 let res = qpath_res(cx, ty_qpath, ty.hir_id);
278 if let Some(def_id) = res.opt_def_id();
279 if Some(def_id) == cx.tcx.lang_items().owned_box();
280 // At this point, we know ty is Box<T>, now get T
281 if let Some(ref last) = last_path_segment(ty_qpath).args;
282 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
283 GenericArg::Type(ty) => Some(ty),
287 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
288 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env) {
293 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
295 format!("Vec<{}>", ty_ty),
296 Applicability::MachineApplicable,
298 return; // don't recurse into the type
302 } else if match_def_path(cx, def_id, &paths::OPTION) {
303 if match_type_parameter(cx, qpath, &paths::OPTION) {
308 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
309 enum if you need to distinguish all 3 cases",
311 return; // don't recurse into the type
313 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
318 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
319 "a VecDeque might work",
321 return; // don't recurse into the type
325 QPath::Resolved(Some(ref ty), ref p) => {
326 check_ty(cx, ty, is_local);
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::Resolved(None, ref p) => {
340 for ty in p.segments.iter().flat_map(|seg| {
343 .map_or_else(|| [].iter(), |params| params.args.iter())
344 .filter_map(|arg| match arg {
345 GenericArg::Type(ty) => Some(ty),
349 check_ty(cx, ty, is_local);
352 QPath::TypeRelative(ref ty, ref seg) => {
353 check_ty(cx, ty, is_local);
354 if let Some(ref params) = seg.args {
355 for ty in params.args.iter().filter_map(|arg| match arg {
356 GenericArg::Type(ty) => Some(ty),
359 check_ty(cx, ty, is_local);
365 TyKind::Rptr(ref lt, ref mut_ty) => check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
367 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
368 check_ty(cx, ty, is_local)
370 TyKind::Tup(tys) => {
372 check_ty(cx, ty, is_local);
379 fn check_ty_rptr(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool, lt: &Lifetime, mut_ty: &MutTy<'_>) {
380 match mut_ty.ty.kind {
381 TyKind::Path(ref qpath) => {
382 let hir_id = mut_ty.ty.hir_id;
383 let def = qpath_res(cx, qpath, hir_id);
385 if let Some(def_id) = def.opt_def_id();
386 if Some(def_id) == cx.tcx.lang_items().owned_box();
387 if let QPath::Resolved(None, ref path) = *qpath;
388 if let [ref bx] = *path.segments;
389 if let Some(ref params) = bx.args;
390 if !params.parenthesized;
391 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
392 GenericArg::Type(ty) => Some(ty),
396 if is_any_trait(inner) {
397 // Ignore `Box<Any>` types; see issue #1884 for details.
401 let ltopt = if lt.is_elided() {
404 format!("{} ", lt.name.ident().as_str())
406 let mutopt = if mut_ty.mutbl == Mutability::Mut {
411 let mut applicability = Applicability::MachineApplicable;
416 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
422 &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
424 Applicability::Unspecified,
426 return; // don't recurse into the type
429 check_ty(cx, &mut_ty.ty, is_local);
431 _ => check_ty(cx, &mut_ty.ty, is_local),
435 // Returns true if given type is `Any` trait.
436 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
438 if let TyKind::TraitObject(ref traits, _) = t.kind;
439 if !traits.is_empty();
440 // Only Send/Sync can be used as additional traits, so it is enough to
441 // check only the first trait.
442 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
451 declare_clippy_lint! {
452 /// **What it does:** Checks for binding a unit value.
454 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
455 /// binding one is kind of pointless.
457 /// **Known problems:** None.
467 "creating a let binding to a value of unit type, which usually can't be used afterwards"
470 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
472 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue {
473 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) {
474 if let StmtKind::Local(ref local) = stmt.kind {
475 if is_unit(cx.tables.pat_ty(&local.pat)) {
476 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
479 if higher::is_from_for_desugar(local) {
482 span_lint_and_then(cx, LET_UNIT_VALUE, stmt.span, "this let-binding has unit value", |db| {
483 if let Some(expr) = &local.init {
484 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
487 "omit the `let` binding",
488 format!("{};", snip),
489 Applicability::MachineApplicable, // snippet
498 declare_clippy_lint! {
499 /// **What it does:** Checks for comparisons to unit. This includes all binary
500 /// comparisons (like `==` and `<`) and asserts.
502 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
503 /// clumsily written constant. Mostly this happens when someone accidentally
504 /// adds semicolons at the end of the operands.
506 /// **Known problems:** None.
537 /// assert_eq!({ foo(); }, { bar(); });
539 /// will always succeed
542 "comparing unit values"
545 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
547 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
548 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
549 if expr.span.from_expansion() {
550 if let Some(callee) = expr.span.source_callee() {
551 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
552 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
554 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
555 let result = match &*symbol.as_str() {
556 "assert_eq" | "debug_assert_eq" => "succeed",
557 "assert_ne" | "debug_assert_ne" => "fail",
565 "`{}` of unit values detected. This will always {}",
576 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
578 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
579 let result = match op {
580 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
588 "{}-comparison of unit values detected. This will always be {}",
598 declare_clippy_lint! {
599 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
600 /// unit literal (`()`).
602 /// **Why is this bad?** This is likely the result of an accidental semicolon.
604 /// **Known problems:** None.
615 "passing unit to a function"
618 declare_lint_pass!(UnitArg => [UNIT_ARG]);
620 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
621 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
622 if expr.span.from_expansion() {
626 // apparently stuff in the desugaring of `?` can trigger this
627 // so check for that here
628 // only the calls to `Try::from_error` is marked as desugared,
629 // so we need to check both the current Expr and its parent.
630 if is_questionmark_desugar_marked_call(expr) {
634 let map = &cx.tcx.hir();
635 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
636 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
637 if is_questionmark_desugar_marked_call(parent_expr);
644 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args) => {
646 if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
647 if let ExprKind::Match(.., match_source) = &arg.kind {
648 if *match_source == MatchSource::TryDesugar {
657 "passing a unit value to a function",
658 "if you intended to pass a unit value, use a unit literal instead",
660 Applicability::MachineApplicable,
670 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
671 use rustc_span::hygiene::DesugaringKind;
672 if let ExprKind::Call(ref callee, _) = expr.kind {
673 callee.span.is_desugaring(DesugaringKind::QuestionMark)
679 fn is_unit(ty: Ty<'_>) -> bool {
681 ty::Tuple(slice) if slice.is_empty() => true,
686 fn is_unit_literal(expr: &Expr<'_>) -> bool {
688 ExprKind::Tup(ref slice) if slice.is_empty() => true,
693 declare_clippy_lint! {
694 /// **What it does:** Checks for casts from any numerical to a float type where
695 /// the receiving type cannot store all values from the original type without
696 /// rounding errors. This possible rounding is to be expected, so this lint is
697 /// `Allow` by default.
699 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
700 /// or any 64-bit integer to `f64`.
702 /// **Why is this bad?** It's not bad at all. But in some applications it can be
703 /// helpful to know where precision loss can take place. This lint can help find
704 /// those places in the code.
706 /// **Known problems:** None.
710 /// let x = std::u64::MAX;
713 pub CAST_PRECISION_LOSS,
715 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
718 declare_clippy_lint! {
719 /// **What it does:** Checks for casts from a signed to an unsigned numerical
720 /// type. In this case, negative values wrap around to large positive values,
721 /// which can be quite surprising in practice. However, as the cast works as
722 /// defined, this lint is `Allow` by default.
724 /// **Why is this bad?** Possibly surprising results. You can activate this lint
725 /// as a one-time check to see where numerical wrapping can arise.
727 /// **Known problems:** None.
732 /// y as u128; // will return 18446744073709551615
736 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
739 declare_clippy_lint! {
740 /// **What it does:** Checks for casts between numerical types that may
741 /// truncate large values. This is expected behavior, so the cast is `Allow` by
744 /// **Why is this bad?** In some problem domains, it is good practice to avoid
745 /// truncation. This lint can be activated to help assess where additional
746 /// checks could be beneficial.
748 /// **Known problems:** None.
752 /// fn as_u8(x: u64) -> u8 {
756 pub CAST_POSSIBLE_TRUNCATION,
758 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
761 declare_clippy_lint! {
762 /// **What it does:** Checks for casts from an unsigned type to a signed type of
763 /// the same size. Performing such a cast is a 'no-op' for the compiler,
764 /// i.e., nothing is changed at the bit level, and the binary representation of
765 /// the value is reinterpreted. This can cause wrapping if the value is too big
766 /// for the target signed type. However, the cast works as defined, so this lint
767 /// is `Allow` by default.
769 /// **Why is this bad?** While such a cast is not bad in itself, the results can
770 /// be surprising when this is not the intended behavior, as demonstrated by the
773 /// **Known problems:** None.
777 /// std::u32::MAX as i32; // will yield a value of `-1`
779 pub CAST_POSSIBLE_WRAP,
781 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
784 declare_clippy_lint! {
785 /// **What it does:** Checks for casts between numerical types that may
786 /// be replaced by safe conversion functions.
788 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
789 /// conversions, including silently lossy conversions. Conversion functions such
790 /// as `i32::from` will only perform lossless conversions. Using the conversion
791 /// functions prevents conversions from turning into silent lossy conversions if
792 /// the types of the input expressions ever change, and make it easier for
793 /// people reading the code to know that the conversion is lossless.
795 /// **Known problems:** None.
799 /// fn as_u64(x: u8) -> u64 {
804 /// Using `::from` would look like this:
807 /// fn as_u64(x: u8) -> u64 {
813 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
816 declare_clippy_lint! {
817 /// **What it does:** Checks for casts to the same type.
819 /// **Why is this bad?** It's just unnecessary.
821 /// **Known problems:** None.
825 /// let _ = 2i32 as i32;
827 pub UNNECESSARY_CAST,
829 "cast to the same type, e.g., `x as i32` where `x: i32`"
832 declare_clippy_lint! {
833 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
834 /// more-strictly-aligned pointer
836 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
839 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
840 /// on the resulting pointer is fine.
844 /// let _ = (&1u8 as *const u8) as *const u16;
845 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
847 pub CAST_PTR_ALIGNMENT,
849 "cast from a pointer to a more-strictly-aligned pointer"
852 declare_clippy_lint! {
853 /// **What it does:** Checks for casts of function pointers to something other than usize
855 /// **Why is this bad?**
856 /// Casting a function pointer to anything other than usize/isize is not portable across
857 /// architectures, because you end up losing bits if the target type is too small or end up with a
858 /// bunch of extra bits that waste space and add more instructions to the final binary than
859 /// strictly necessary for the problem
861 /// Casting to isize also doesn't make sense since there are no signed addresses.
867 /// fn fun() -> i32 { 1 }
868 /// let a = fun as i64;
871 /// fn fun2() -> i32 { 1 }
872 /// let a = fun2 as usize;
874 pub FN_TO_NUMERIC_CAST,
876 "casting a function pointer to a numeric type other than usize"
879 declare_clippy_lint! {
880 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
883 /// **Why is this bad?**
884 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
885 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
886 /// a comment) to perform the truncation.
892 /// fn fn1() -> i16 {
895 /// let _ = fn1 as i32;
897 /// // Better: Cast to usize first, then comment with the reason for the truncation
898 /// fn fn2() -> i16 {
901 /// let fn_ptr = fn2 as usize;
902 /// let fn_ptr_truncated = fn_ptr as i32;
904 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
906 "casting a function pointer to a numeric type not wide enough to store the address"
909 /// Returns the size in bits of an integral type.
910 /// Will return 0 if the type is not an int or uint variant
911 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
913 ty::Int(i) => match i {
914 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
921 ty::Uint(i) => match i {
922 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
933 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
935 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => true,
940 fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
941 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
942 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
943 let arch_dependent_str = "on targets with 64-bit wide pointers ";
944 let from_nbits_str = if arch_dependent {
946 } else if is_isize_or_usize(cast_from) {
947 "32 or 64".to_owned()
949 int_ty_to_nbits(cast_from, cx.tcx).to_string()
956 "casting {0} to {1} causes a loss of precision {2}({0} is {3} bits wide, but {1}'s mantissa \
957 is only {4} bits wide)",
959 if cast_to_f64 { "f64" } else { "f32" },
960 if arch_dependent { arch_dependent_str } else { "" },
967 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
968 if let ExprKind::Binary(_, _, _) = op.kind {
969 if snip.starts_with('(') && snip.ends_with(')') {
976 fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
977 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
978 if in_constant(cx, expr.hir_id) {
981 // The suggestion is to use a function call, so if the original expression
982 // has parens on the outside, they are no longer needed.
983 let mut applicability = Applicability::MachineApplicable;
984 let opt = snippet_opt(cx, op.span);
985 let sugg = if let Some(ref snip) = opt {
986 if should_strip_parens(op, snip) {
987 &snip[1..snip.len() - 1]
992 applicability = Applicability::HasPlaceholders;
1001 "casting {} to {} may become silently lossy if you later change the type",
1005 format!("{}::from({})", cast_to, sugg),
1016 fn check_loss_of_sign(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1017 if !cast_from.is_signed() || cast_to.is_signed() {
1021 // don't lint for positive constants
1022 let const_val = constant(cx, &cx.tables, op);
1024 if let Some((const_val, _)) = const_val;
1025 if let Constant::Int(n) = const_val;
1026 if let ty::Int(ity) = cast_from.kind;
1027 if sext(cx.tcx, n, ity) >= 0;
1033 // don't lint for the result of methods that always return non-negative values
1034 if let ExprKind::MethodCall(ref path, _, _) = op.kind {
1035 let mut method_name = path.ident.name.as_str();
1036 let whitelisted_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1039 if method_name == "unwrap";
1040 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1041 if let ExprKind::MethodCall(ref inner_path, _, _) = &arglist[0][0].kind;
1043 method_name = inner_path.ident.name.as_str();
1047 if whitelisted_methods.iter().any(|&name| method_name == name) {
1056 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1060 fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1061 let arch_64_suffix = " on targets with 64-bit wide pointers";
1062 let arch_32_suffix = " on targets with 32-bit wide pointers";
1063 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1064 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1065 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1066 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1067 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1068 (true, true) | (false, false) => (
1069 to_nbits < from_nbits,
1071 to_nbits == from_nbits && cast_unsigned_to_signed,
1081 to_nbits <= 32 && cast_unsigned_to_signed,
1087 cast_unsigned_to_signed,
1088 if from_nbits == 64 {
1095 if span_truncation {
1098 CAST_POSSIBLE_TRUNCATION,
1101 "casting {} to {} may truncate the value{}",
1104 match suffix_truncation {
1105 ArchSuffix::_32 => arch_32_suffix,
1106 ArchSuffix::_64 => arch_64_suffix,
1107 ArchSuffix::None => "",
1118 "casting {} to {} may wrap around the value{}",
1122 ArchSuffix::_32 => arch_32_suffix,
1123 ArchSuffix::_64 => arch_64_suffix,
1124 ArchSuffix::None => "",
1131 fn check_lossless(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1132 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1133 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1134 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1135 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1137 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1141 declare_lint_pass!(Casts => [
1142 CAST_PRECISION_LOSS,
1144 CAST_POSSIBLE_TRUNCATION,
1150 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1153 // Check if the given type is either `core::ffi::c_void` or
1154 // one of the platform specific `libc::<platform>::c_void` of libc.
1155 fn is_c_void(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1156 if let ty::Adt(adt, _) = ty.kind {
1157 let names = cx.get_def_path(adt.did);
1159 if names.is_empty() {
1162 if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1169 /// Returns the mantissa bits wide of a fp type.
1170 /// Will return 0 if the type is not a fp
1171 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1173 ty::Float(FloatTy::F32) => 23,
1174 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1179 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
1180 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1181 if expr.span.from_expansion() {
1184 if let ExprKind::Cast(ref ex, _) = expr.kind {
1185 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
1186 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1187 if let ExprKind::Lit(ref lit) = ex.kind {
1188 if let LitKind::Int(n, _) = lit.node {
1189 if cast_to.is_floating_point() {
1190 let from_nbits = 128 - n.leading_zeros();
1191 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1192 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits {
1197 &format!("casting integer literal to {} is unnecessary", cast_to),
1199 format!("{}_{}", n, cast_to),
1200 Applicability::MachineApplicable,
1207 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1209 if cast_from.kind == cast_to.kind && !in_external_macro(cx.sess(), expr.span) {
1215 "casting to the same type is unnecessary (`{}` -> `{}`)",
1223 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1224 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1227 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1232 fn lint_numeric_casts<'tcx>(
1233 cx: &LateContext<'_, 'tcx>,
1235 cast_expr: &Expr<'_>,
1236 cast_from: Ty<'tcx>,
1239 match (cast_from.is_integral(), cast_to.is_integral()) {
1241 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1242 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind {
1247 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1248 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1250 if from_nbits < to_nbits {
1251 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1257 CAST_POSSIBLE_TRUNCATION,
1259 &format!("casting {} to {} may truncate the value", cast_from, cast_to),
1261 if !cast_to.is_signed() {
1266 &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
1271 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1272 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1273 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1276 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind, &cast_to.kind) {
1279 CAST_POSSIBLE_TRUNCATION,
1281 "casting f64 to f32 may truncate the value",
1284 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind, &cast_to.kind) {
1285 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1291 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1293 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind;
1294 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind;
1295 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1296 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1297 if from_layout.align.abi < to_layout.align.abi;
1298 // with c_void, we inherently need to trust the user
1299 if !is_c_void(cx, from_ptr_ty.ty);
1300 // when casting from a ZST, we don't know enough to properly lint
1301 if !from_layout.is_zst();
1308 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1311 from_layout.align.abi.bytes(),
1312 to_layout.align.abi.bytes(),
1319 fn lint_fn_to_numeric_cast(
1320 cx: &LateContext<'_, '_>,
1322 cast_expr: &Expr<'_>,
1326 // We only want to check casts to `ty::Uint` or `ty::Int`
1327 match cast_to.kind {
1328 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1331 match cast_from.kind {
1332 ty::FnDef(..) | ty::FnPtr(_) => {
1333 let mut applicability = Applicability::MaybeIncorrect;
1334 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1336 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1337 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1340 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1343 "casting function pointer `{}` to `{}`, which truncates the value",
1344 from_snippet, cast_to
1347 format!("{} as usize", from_snippet),
1350 } else if cast_to.kind != ty::Uint(UintTy::Usize) {
1355 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1357 format!("{} as usize", from_snippet),
1366 declare_clippy_lint! {
1367 /// **What it does:** Checks for types used in structs, parameters and `let`
1368 /// declarations above a certain complexity threshold.
1370 /// **Why is this bad?** Too complex types make the code less readable. Consider
1371 /// using a `type` definition to simplify them.
1373 /// **Known problems:** None.
1377 /// # use std::rc::Rc;
1379 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1382 pub TYPE_COMPLEXITY,
1384 "usage of very complex types that might be better factored into `type` definitions"
1387 pub struct TypeComplexity {
1391 impl TypeComplexity {
1393 pub fn new(threshold: u64) -> Self {
1398 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1400 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity {
1403 cx: &LateContext<'a, 'tcx>,
1405 decl: &'tcx FnDecl<'_>,
1410 self.check_fndecl(cx, decl);
1413 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField<'_>) {
1414 // enum variants are also struct fields now
1415 self.check_type(cx, &field.ty);
1418 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
1420 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1421 // functions, enums, structs, impls and traits are covered
1426 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
1428 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1429 TraitItemKind::Method(FnSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
1430 // methods with default impl are covered by check_fn
1435 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
1437 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1438 // methods are covered by check_fn
1443 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
1444 if let Some(ref ty) = local.ty {
1445 self.check_type(cx, ty);
1450 impl<'a, 'tcx> TypeComplexity {
1451 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl<'_>) {
1452 for arg in decl.inputs {
1453 self.check_type(cx, arg);
1455 if let Return(ref ty) = decl.output {
1456 self.check_type(cx, ty);
1460 fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty<'_>) {
1461 if ty.span.from_expansion() {
1465 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1466 visitor.visit_ty(ty);
1470 if score > self.threshold {
1475 "very complex type used. Consider factoring parts into `type` definitions",
1481 /// Walks a type and assigns a complexity score to it.
1482 struct TypeComplexityVisitor {
1483 /// total complexity score of the type
1485 /// current nesting level
1489 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1490 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1491 let (add_score, sub_nest) = match ty.kind {
1492 // _, &x and *x have only small overhead; don't mess with nesting level
1493 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1495 // the "normal" components of a type: named types, arrays/tuples
1496 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1498 // function types bring a lot of overhead
1499 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1501 TyKind::TraitObject(ref param_bounds, _) => {
1502 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1503 bound.bound_generic_params.iter().any(|gen| match gen.kind {
1504 GenericParamKind::Lifetime { .. } => true,
1508 if has_lifetime_parameters {
1509 // complex trait bounds like A<'a, 'b>
1512 // simple trait bounds like A + B
1519 self.score += add_score;
1520 self.nest += sub_nest;
1522 self.nest -= sub_nest;
1524 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1525 NestedVisitorMap::None
1529 declare_clippy_lint! {
1530 /// **What it does:** Checks for expressions where a character literal is cast
1531 /// to `u8` and suggests using a byte literal instead.
1533 /// **Why is this bad?** In general, casting values to smaller types is
1534 /// error-prone and should be avoided where possible. In the particular case of
1535 /// converting a character literal to u8, it is easy to avoid by just using a
1536 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1537 /// than `'a' as u8`.
1539 /// **Known problems:** None.
1546 /// A better version, using the byte literal:
1553 "casting a character literal to u8 truncates"
1556 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1558 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1559 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1561 if !expr.span.from_expansion();
1562 if let ExprKind::Cast(e, _) = &expr.kind;
1563 if let ExprKind::Lit(l) = &e.kind;
1564 if let LitKind::Char(c) = l.node;
1565 if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).kind;
1567 let mut applicability = Applicability::MachineApplicable;
1568 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
1574 "casting a character literal to `u8` truncates",
1576 db.note("`char` is four bytes wide, but `u8` is a single byte");
1581 "use a byte literal instead",
1582 format!("b{}", snippet),
1592 declare_clippy_lint! {
1593 /// **What it does:** Checks for comparisons where one side of the relation is
1594 /// either the minimum or maximum value for its type and warns if it involves a
1595 /// case that is always true or always false. Only integer and boolean types are
1598 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1599 /// that it is possible for `x` to be less than the minimum. Expressions like
1600 /// `max < x` are probably mistakes.
1602 /// **Known problems:** For `usize` the size of the current compile target will
1603 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1604 /// a comparison to detect target pointer width will trigger this lint. One can
1605 /// use `mem::sizeof` and compare its value or conditional compilation
1607 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1612 /// let vec: Vec<isize> = vec![];
1613 /// if vec.len() <= 0 {}
1614 /// if 100 > std::i32::MAX {}
1616 pub ABSURD_EXTREME_COMPARISONS,
1618 "a comparison with a maximum or minimum value that is always true or false"
1621 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1628 struct ExtremeExpr<'a> {
1633 enum AbsurdComparisonResult {
1636 InequalityImpossible,
1639 fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1640 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1641 let precast_ty = cx.tables.expr_ty(cast_exp);
1642 let cast_ty = cx.tables.expr_ty(expr);
1644 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1650 fn detect_absurd_comparison<'a, 'tcx>(
1651 cx: &LateContext<'a, 'tcx>,
1653 lhs: &'tcx Expr<'_>,
1654 rhs: &'tcx Expr<'_>,
1655 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1656 use crate::types::AbsurdComparisonResult::*;
1657 use crate::types::ExtremeType::*;
1658 use crate::utils::comparisons::*;
1660 // absurd comparison only makes sense on primitive types
1661 // primitive types don't implement comparison operators with each other
1662 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1666 // comparisons between fix sized types and target sized types are considered unanalyzable
1667 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1671 let normalized = normalize_comparison(op, lhs, rhs);
1672 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1678 let lx = detect_extreme_expr(cx, normalized_lhs);
1679 let rx = detect_extreme_expr(cx, normalized_rhs);
1684 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1685 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1691 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1692 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1693 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1694 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1698 Rel::Ne | Rel::Eq => return None,
1702 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
1703 use crate::types::ExtremeType::*;
1705 let ty = cx.tables.expr_ty(expr);
1707 let cv = constant(cx, cx.tables, expr)?.0;
1709 let which = match (&ty.kind, cv) {
1710 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1711 (&ty::Int(ity), Constant::Int(i))
1712 if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1717 (&ty::Bool, Constant::Bool(true)) => Maximum,
1718 (&ty::Int(ity), Constant::Int(i))
1719 if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1723 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1727 Some(ExtremeExpr { which, expr })
1730 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1731 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1732 use crate::types::AbsurdComparisonResult::*;
1733 use crate::types::ExtremeType::*;
1735 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
1736 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1737 if !expr.span.from_expansion() {
1738 let msg = "this comparison involving the minimum or maximum element for this \
1739 type contains a case that is always true or always false";
1741 let conclusion = match result {
1742 AlwaysFalse => "this comparison is always false".to_owned(),
1743 AlwaysTrue => "this comparison is always true".to_owned(),
1744 InequalityImpossible => format!(
1745 "the case where the two sides are not equal never occurs, consider using {} == {} \
1747 snippet(cx, lhs.span, "lhs"),
1748 snippet(cx, rhs.span, "rhs")
1753 "because {} is the {} value for this type, {}",
1754 snippet(cx, culprit.expr.span, "x"),
1755 match culprit.which {
1756 Minimum => "minimum",
1757 Maximum => "maximum",
1762 span_help_and_lint(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1769 declare_clippy_lint! {
1770 /// **What it does:** Checks for comparisons where the relation is always either
1771 /// true or false, but where one side has been upcast so that the comparison is
1772 /// necessary. Only integer types are checked.
1774 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1775 /// will mistakenly imply that it is possible for `x` to be outside the range of
1778 /// **Known problems:**
1779 /// https://github.com/rust-lang/rust-clippy/issues/886
1784 /// (x as u32) > 300;
1786 pub INVALID_UPCAST_COMPARISONS,
1788 "a comparison involving an upcast which is always true or false"
1791 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
1793 #[derive(Copy, Clone, Debug, Eq)]
1800 #[allow(clippy::cast_sign_loss)]
1802 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1805 } else if u > (i128::max_value() as u128) {
1813 impl PartialEq for FullInt {
1815 fn eq(&self, other: &Self) -> bool {
1816 self.partial_cmp(other).expect("partial_cmp only returns Some(_)") == Ordering::Equal
1820 impl PartialOrd for FullInt {
1822 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1823 Some(match (self, other) {
1824 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
1825 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
1826 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
1827 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
1831 impl Ord for FullInt {
1833 fn cmp(&self, other: &Self) -> Ordering {
1834 self.partial_cmp(other)
1835 .expect("partial_cmp for FullInt can never return None")
1839 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
1842 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1843 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1844 let cast_ty = cx.tables.expr_ty(expr);
1845 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1846 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1849 match pre_cast_ty.kind {
1850 ty::Int(int_ty) => Some(match int_ty {
1852 FullInt::S(i128::from(i8::min_value())),
1853 FullInt::S(i128::from(i8::max_value())),
1856 FullInt::S(i128::from(i16::min_value())),
1857 FullInt::S(i128::from(i16::max_value())),
1860 FullInt::S(i128::from(i32::min_value())),
1861 FullInt::S(i128::from(i32::max_value())),
1864 FullInt::S(i128::from(i64::min_value())),
1865 FullInt::S(i128::from(i64::max_value())),
1867 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
1869 FullInt::S(isize::min_value() as i128),
1870 FullInt::S(isize::max_value() as i128),
1873 ty::Uint(uint_ty) => Some(match uint_ty {
1875 FullInt::U(u128::from(u8::min_value())),
1876 FullInt::U(u128::from(u8::max_value())),
1879 FullInt::U(u128::from(u16::min_value())),
1880 FullInt::U(u128::from(u16::max_value())),
1883 FullInt::U(u128::from(u32::min_value())),
1884 FullInt::U(u128::from(u32::max_value())),
1887 FullInt::U(u128::from(u64::min_value())),
1888 FullInt::U(u128::from(u64::max_value())),
1890 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
1892 FullInt::U(usize::min_value() as u128),
1893 FullInt::U(usize::max_value() as u128),
1903 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
1904 let val = constant(cx, cx.tables, expr)?.0;
1905 if let Constant::Int(const_int) = val {
1906 match cx.tables.expr_ty(expr).kind {
1907 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
1908 ty::Uint(_) => Some(FullInt::U(const_int)),
1916 fn err_upcast_comparison(cx: &LateContext<'_, '_>, span: Span, expr: &Expr<'_>, always: bool) {
1917 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
1920 INVALID_UPCAST_COMPARISONS,
1923 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
1924 snippet(cx, cast_val.span, "the expression"),
1925 if always { "true" } else { "false" },
1931 fn upcast_comparison_bounds_err<'a, 'tcx>(
1932 cx: &LateContext<'a, 'tcx>,
1934 rel: comparisons::Rel,
1935 lhs_bounds: Option<(FullInt, FullInt)>,
1936 lhs: &'tcx Expr<'_>,
1937 rhs: &'tcx Expr<'_>,
1940 use crate::utils::comparisons::*;
1942 if let Some((lb, ub)) = lhs_bounds {
1943 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
1944 if rel == Rel::Eq || rel == Rel::Ne {
1945 if norm_rhs_val < lb || norm_rhs_val > ub {
1946 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
1948 } else if match rel {
1963 Rel::Eq | Rel::Ne => unreachable!(),
1965 err_upcast_comparison(cx, span, lhs, true)
1966 } else if match rel {
1981 Rel::Eq | Rel::Ne => unreachable!(),
1983 err_upcast_comparison(cx, span, lhs, false)
1989 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
1990 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1991 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
1992 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
1993 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
1999 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2000 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2002 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2003 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2008 declare_clippy_lint! {
2009 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2010 /// over different hashers and implicitly defaulting to the default hashing
2011 /// algorithm (`SipHash`).
2013 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2016 /// **Known problems:** Suggestions for replacing constructors can contain
2017 /// false-positives. Also applying suggestions can require modification of other
2018 /// pieces of code, possibly including external crates.
2022 /// # use std::collections::HashMap;
2023 /// # use std::hash::{Hash, BuildHasher};
2024 /// # trait Serialize {};
2025 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2027 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2029 /// could be rewritten as
2031 /// # use std::collections::HashMap;
2032 /// # use std::hash::{Hash, BuildHasher};
2033 /// # trait Serialize {};
2034 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2036 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2038 pub IMPLICIT_HASHER,
2040 "missing generalization over different hashers"
2043 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2045 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
2046 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2047 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
2048 use rustc_span::BytePos;
2050 fn suggestion<'a, 'tcx>(
2051 cx: &LateContext<'a, 'tcx>,
2052 db: &mut DiagnosticBuilder<'_>,
2053 generics_span: Span,
2054 generics_suggestion_span: Span,
2055 target: &ImplicitHasherType<'_>,
2056 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2058 let generics_snip = snippet(cx, generics_span, "");
2060 let generics_snip = if generics_snip.is_empty() {
2063 &generics_snip[1..generics_snip.len() - 1]
2068 "consider adding a type parameter".to_string(),
2071 generics_suggestion_span,
2073 "<{}{}S: ::std::hash::BuildHasher{}>",
2075 if generics_snip.is_empty() { "" } else { ", " },
2076 if vis.suggestions.is_empty() {
2079 // request users to add `Default` bound so that generic constructors can be used
2086 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2091 if !vis.suggestions.is_empty() {
2092 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
2096 if !cx.access_levels.is_exported(item.hir_id) {
2101 ItemKind::Impl(_, _, _, ref generics, _, ref ty, ref items) => {
2102 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2105 for target in &vis.found {
2106 if differing_macro_contexts(item.span, target.span()) {
2110 let generics_suggestion_span = generics.span.substitute_dummy({
2111 let pos = snippet_opt(cx, item.span.until(target.span()))
2112 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2113 if let Some(pos) = pos {
2114 Span::new(pos, pos, item.span.data().ctxt)
2120 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2121 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2122 ctr_vis.visit_impl_item(item);
2130 "impl for `{}` should be generalized over different hashers",
2134 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2139 ItemKind::Fn(ref sig, ref generics, body_id) => {
2140 let body = cx.tcx.hir().body(body_id);
2142 for ty in sig.decl.inputs {
2143 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2146 for target in &vis.found {
2147 if in_external_macro(cx.sess(), generics.span) {
2150 let generics_suggestion_span = generics.span.substitute_dummy({
2151 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2153 let i = snip.find("fn")?;
2154 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2156 .expect("failed to create span for type parameters");
2157 Span::new(pos, pos, item.span.data().ctxt)
2160 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2161 ctr_vis.visit_body(body);
2168 "parameter of type `{}` should be generalized over different hashers",
2172 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2183 enum ImplicitHasherType<'tcx> {
2184 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2185 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2188 impl<'tcx> ImplicitHasherType<'tcx> {
2189 /// Checks that `ty` is a target type without a `BuildHasher`.
2190 fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2191 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2192 let params: Vec<_> = path
2200 .filter_map(|arg| match arg {
2201 GenericArg::Type(ty) => Some(ty),
2205 let params_len = params.len();
2207 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2209 if match_path(path, &paths::HASHMAP) && params_len == 2 {
2210 Some(ImplicitHasherType::HashMap(
2213 snippet(cx, params[0].span, "K"),
2214 snippet(cx, params[1].span, "V"),
2216 } else if match_path(path, &paths::HASHSET) && params_len == 1 {
2217 Some(ImplicitHasherType::HashSet(
2220 snippet(cx, params[0].span, "T"),
2230 fn type_name(&self) -> &'static str {
2232 ImplicitHasherType::HashMap(..) => "HashMap",
2233 ImplicitHasherType::HashSet(..) => "HashSet",
2237 fn type_arguments(&self) -> String {
2239 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2240 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2244 fn ty(&self) -> Ty<'tcx> {
2246 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2250 fn span(&self) -> Span {
2252 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2257 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2258 cx: &'a LateContext<'a, 'tcx>,
2259 found: Vec<ImplicitHasherType<'tcx>>,
2262 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2263 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
2264 Self { cx, found: vec![] }
2268 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2269 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2270 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2271 self.found.push(target);
2277 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2278 NestedVisitorMap::None
2282 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2283 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2284 cx: &'a LateContext<'a, 'tcx>,
2285 body: &'a TypeckTables<'tcx>,
2286 target: &'b ImplicitHasherType<'tcx>,
2287 suggestions: BTreeMap<Span, String>,
2290 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2291 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2296 suggestions: BTreeMap::new(),
2301 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2302 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2303 let prev_body = self.body;
2304 self.body = self.cx.tcx.body_tables(body.id());
2305 walk_body(self, body);
2306 self.body = prev_body;
2309 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2311 if let ExprKind::Call(ref fun, ref args) = e.kind;
2312 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2313 if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.kind;
2315 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
2319 if match_path(ty_path, &paths::HASHMAP) {
2320 if method.ident.name == sym!(new) {
2322 .insert(e.span, "HashMap::default()".to_string());
2323 } else if method.ident.name == sym!(with_capacity) {
2324 self.suggestions.insert(
2327 "HashMap::with_capacity_and_hasher({}, Default::default())",
2328 snippet(self.cx, args[0].span, "capacity"),
2332 } else if match_path(ty_path, &paths::HASHSET) {
2333 if method.ident.name == sym!(new) {
2335 .insert(e.span, "HashSet::default()".to_string());
2336 } else if method.ident.name == sym!(with_capacity) {
2337 self.suggestions.insert(
2340 "HashSet::with_capacity_and_hasher({}, Default::default())",
2341 snippet(self.cx, args[0].span, "capacity"),
2352 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2353 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
2357 declare_clippy_lint! {
2358 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2360 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2361 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2364 /// **Known problems:** None.
2370 /// *(r as *const _ as *mut _) += 1;
2375 /// Instead consider using interior mutability types.
2378 /// use std::cell::UnsafeCell;
2380 /// fn x(r: &UnsafeCell<i32>) {
2386 pub CAST_REF_TO_MUT,
2388 "a cast of reference to a mutable pointer"
2391 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2393 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2394 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2396 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2397 if let ExprKind::Cast(e, t) = &e.kind;
2398 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2399 if let ExprKind::Cast(e, t) = &e.kind;
2400 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2401 if let ty::Ref(..) = cx.tables.node_type(e.hir_id).kind;
2407 "casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell",