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_ast::ast::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy};
9 use rustc_errors::{Applicability, DiagnosticBuilder};
11 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
13 BinOpKind, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem,
14 ImplItemKind, Item, ItemKind, Lifetime, Local, MatchSource, MutTy, Mutability, QPath, Stmt, StmtKind, TraitFn,
15 TraitItem, TraitItemKind, TyKind, UnOp,
17 use rustc_lint::{LateContext, LateLintPass, LintContext};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::lint::in_external_macro;
20 use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TypeckTables};
21 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
22 use rustc_span::hygiene::{ExpnKind, MacroKind};
23 use rustc_span::source_map::Span;
24 use rustc_span::symbol::sym;
25 use rustc_target::abi::LayoutOf;
26 use rustc_target::spec::abi::Abi;
27 use rustc_typeck::hir_ty_to_ty;
29 use crate::consts::{constant, Constant};
30 use crate::utils::paths;
32 clip, comparisons, differing_macro_contexts, higher, in_constant, int_bits, is_type_diagnostic_item,
33 last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral,
34 qpath_res, same_tys, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite,
35 span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
38 declare_clippy_lint! {
39 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
41 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
42 /// the heap. So if you `Box` it, you just add another level of indirection
43 /// without any benefit whatsoever.
45 /// **Known problems:** None.
50 /// values: Box<Vec<Foo>>,
63 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
66 declare_clippy_lint! {
67 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
69 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
70 /// the heap. So if you `Box` its contents, you just add another level of indirection.
72 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
78 /// values: Vec<Box<i32>>,
91 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
94 declare_clippy_lint! {
95 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
98 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
99 /// represents an optional optional value which is logically the same thing as an optional
100 /// value but has an unneeded extra level of wrapping.
102 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
103 /// consider a custom `enum` instead, with clear names for each case.
105 /// **Known problems:** None.
109 /// fn get_data() -> Option<Option<u32>> {
117 /// pub enum Contents {
118 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
119 /// NotYetFetched, // Was Some(None)
120 /// None, // Was None
123 /// fn get_data() -> Contents {
129 "usage of `Option<Option<T>>`"
132 declare_clippy_lint! {
133 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
134 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
136 /// **Why is this bad?** Gankro says:
138 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
139 /// pointers and indirection.
140 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
142 /// > "only" amortized for push/pop, should be faster in the general case for
143 /// almost every possible
144 /// > workload, and isn't even amortized at all if you can predict the capacity
147 /// > `LinkedList`s are only really good if you're doing a lot of merging or
148 /// splitting of lists.
149 /// > This is because they can just mangle some pointers instead of actually
150 /// copying the data. Even
151 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
152 /// can still be better
153 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
155 /// **Known problems:** False positives – the instances where using a
156 /// `LinkedList` makes sense are few and far between, but they can still happen.
160 /// # use std::collections::LinkedList;
161 /// let x: LinkedList<usize> = LinkedList::new();
165 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
168 declare_clippy_lint! {
169 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
171 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
174 /// **Known problems:** None.
178 /// fn foo(bar: &Box<T>) { ... }
184 /// fn foo(bar: &T) { ... }
188 "a borrow of a boxed type"
191 declare_clippy_lint! {
192 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
194 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
195 /// add an unnecessary level of indirection.
197 /// **Known problems:** None.
201 /// # use std::rc::Rc;
202 /// fn foo(bar: Rc<&usize>) {}
208 /// fn foo(bar: &usize) {}
210 pub REDUNDANT_ALLOCATION,
212 "redundant allocation"
216 vec_box_size_threshold: u64,
219 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION]);
221 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types {
224 cx: &LateContext<'_, '_>,
231 // Skip trait implementations; see issue #605.
232 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
233 if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
238 self.check_fn_decl(cx, decl);
241 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) {
242 self.check_ty(cx, &field.ty, false);
245 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &TraitItem<'_>) {
247 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
248 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
253 fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local<'_>) {
254 if let Some(ref ty) = local.ty {
255 self.check_ty(cx, ty, true);
260 /// Checks if `qpath` has last segment with type parameter matching `path`
261 fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&str]) -> Option<Span> {
262 let last = last_path_segment(qpath);
264 if let Some(ref params) = last.args;
265 if !params.parenthesized;
266 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
267 GenericArg::Type(ty) => Some(ty),
270 if let TyKind::Path(ref qpath) = ty.kind;
271 if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
272 if match_def_path(cx, did, path);
274 return Some(ty.span);
280 fn match_borrows_parameter(_cx: &LateContext<'_, '_>, qpath: &QPath<'_>) -> Option<Span> {
281 let last = last_path_segment(qpath);
283 if let Some(ref params) = last.args;
284 if !params.parenthesized;
285 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
286 GenericArg::Type(ty) => Some(ty),
289 if let TyKind::Rptr(..) = ty.kind;
291 return Some(ty.span);
298 pub fn new(vec_box_size_threshold: u64) -> Self {
299 Self { vec_box_size_threshold }
302 fn check_fn_decl(&mut self, cx: &LateContext<'_, '_>, decl: &FnDecl<'_>) {
303 for input in decl.inputs {
304 self.check_ty(cx, input, false);
307 if let FnRetTy::Return(ref ty) = decl.output {
308 self.check_ty(cx, ty, false);
312 /// Recursively check for `TypePass` lints in the given type. Stop at the first
315 /// The parameter `is_local` distinguishes the context of the type; types from
316 /// local bindings should only be checked for the `BORROWED_BOX` lint.
317 #[allow(clippy::too_many_lines)]
318 fn check_ty(&mut self, cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
319 if hir_ty.span.from_expansion() {
323 TyKind::Path(ref qpath) if !is_local => {
324 let hir_id = hir_ty.hir_id;
325 let res = qpath_res(cx, qpath, hir_id);
326 if let Some(def_id) = res.opt_def_id() {
327 if Some(def_id) == cx.tcx.lang_items().owned_box() {
328 if let Some(span) = match_borrows_parameter(cx, qpath) {
331 REDUNDANT_ALLOCATION,
333 "usage of `Box<&T>`",
335 snippet(cx, span, "..").to_string(),
336 Applicability::MachineApplicable,
338 return; // don't recurse into the type
340 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
345 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
347 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
349 return; // don't recurse into the type
351 } else if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
352 if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) {
355 REDUNDANT_ALLOCATION,
357 "usage of `Rc<Rc<T>>`",
359 snippet(cx, span, "..").to_string(),
360 Applicability::MachineApplicable,
362 return; // don't recurse into the type
364 if let Some(span) = match_type_parameter(cx, qpath, &paths::BOX) {
367 REDUNDANT_ALLOCATION,
369 "usage of `Rc<Box<T>>`",
371 snippet(cx, span, "..").to_string(),
372 Applicability::MachineApplicable,
374 return; // don't recurse into the type
376 if let Some(span) = match_borrows_parameter(cx, qpath) {
379 REDUNDANT_ALLOCATION,
383 snippet(cx, span, "..").to_string(),
384 Applicability::MachineApplicable,
386 return; // don't recurse into the type
388 } else if cx.tcx.is_diagnostic_item(sym!(vec_type), def_id) {
390 // Get the _ part of Vec<_>
391 if let Some(ref last) = last_path_segment(qpath).args;
392 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
393 GenericArg::Type(ty) => Some(ty),
396 // ty is now _ at this point
397 if let TyKind::Path(ref ty_qpath) = ty.kind;
398 let res = qpath_res(cx, ty_qpath, ty.hir_id);
399 if let Some(def_id) = res.opt_def_id();
400 if Some(def_id) == cx.tcx.lang_items().owned_box();
401 // At this point, we know ty is Box<T>, now get T
402 if let Some(ref last) = last_path_segment(ty_qpath).args;
403 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
404 GenericArg::Type(ty) => Some(ty),
407 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
408 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env);
409 if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes());
410 if ty_ty_size <= self.vec_box_size_threshold;
416 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
418 format!("Vec<{}>", ty_ty),
419 Applicability::MachineApplicable,
421 return; // don't recurse into the type
424 } else if cx.tcx.is_diagnostic_item(sym!(option_type), def_id) {
425 if match_type_parameter(cx, qpath, &paths::OPTION).is_some() {
430 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
431 enum if you need to distinguish all 3 cases",
433 return; // don't recurse into the type
435 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
440 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
442 "a `VecDeque` might work",
444 return; // don't recurse into the type
448 QPath::Resolved(Some(ref ty), ref p) => {
449 self.check_ty(cx, ty, is_local);
450 for ty in p.segments.iter().flat_map(|seg| {
453 .map_or_else(|| [].iter(), |params| params.args.iter())
454 .filter_map(|arg| match arg {
455 GenericArg::Type(ty) => Some(ty),
459 self.check_ty(cx, ty, is_local);
462 QPath::Resolved(None, ref p) => {
463 for ty in p.segments.iter().flat_map(|seg| {
466 .map_or_else(|| [].iter(), |params| params.args.iter())
467 .filter_map(|arg| match arg {
468 GenericArg::Type(ty) => Some(ty),
472 self.check_ty(cx, ty, is_local);
475 QPath::TypeRelative(ref ty, ref seg) => {
476 self.check_ty(cx, ty, is_local);
477 if let Some(ref params) = seg.args {
478 for ty in params.args.iter().filter_map(|arg| match arg {
479 GenericArg::Type(ty) => Some(ty),
482 self.check_ty(cx, ty, is_local);
488 TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
490 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
491 self.check_ty(cx, ty, is_local)
493 TyKind::Tup(tys) => {
495 self.check_ty(cx, ty, is_local);
504 cx: &LateContext<'_, '_>,
505 hir_ty: &hir::Ty<'_>,
510 match mut_ty.ty.kind {
511 TyKind::Path(ref qpath) => {
512 let hir_id = mut_ty.ty.hir_id;
513 let def = qpath_res(cx, qpath, hir_id);
515 if let Some(def_id) = def.opt_def_id();
516 if Some(def_id) == cx.tcx.lang_items().owned_box();
517 if let QPath::Resolved(None, ref path) = *qpath;
518 if let [ref bx] = *path.segments;
519 if let Some(ref params) = bx.args;
520 if !params.parenthesized;
521 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
522 GenericArg::Type(ty) => Some(ty),
526 if is_any_trait(inner) {
527 // Ignore `Box<Any>` types; see issue #1884 for details.
531 let ltopt = if lt.is_elided() {
534 format!("{} ", lt.name.ident().as_str())
537 if mut_ty.mutbl == Mutability::Mut {
538 // Ignore `&mut Box<T>` types; see issue #2907 for
542 let mut applicability = Applicability::MachineApplicable;
547 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
552 &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
554 Applicability::Unspecified,
556 return; // don't recurse into the type
559 self.check_ty(cx, &mut_ty.ty, is_local);
561 _ => self.check_ty(cx, &mut_ty.ty, is_local),
566 // Returns true if given type is `Any` trait.
567 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
569 if let TyKind::TraitObject(ref traits, _) = t.kind;
570 if !traits.is_empty();
571 // Only Send/Sync can be used as additional traits, so it is enough to
572 // check only the first trait.
573 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
582 declare_clippy_lint! {
583 /// **What it does:** Checks for binding a unit value.
585 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
586 /// binding one is kind of pointless.
588 /// **Known problems:** None.
598 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
601 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
603 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue {
604 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) {
605 if let StmtKind::Local(ref local) = stmt.kind {
606 if is_unit(cx.tables.pat_ty(&local.pat)) {
607 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
610 if higher::is_from_for_desugar(local) {
617 "this let-binding has unit value",
619 if let Some(expr) = &local.init {
620 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
621 diag.span_suggestion(
623 "omit the `let` binding",
624 format!("{};", snip),
625 Applicability::MachineApplicable, // snippet
635 declare_clippy_lint! {
636 /// **What it does:** Checks for comparisons to unit. This includes all binary
637 /// comparisons (like `==` and `<`) and asserts.
639 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
640 /// clumsily written constant. Mostly this happens when someone accidentally
641 /// adds semicolons at the end of the operands.
643 /// **Known problems:** None.
674 /// assert_eq!({ foo(); }, { bar(); });
676 /// will always succeed
679 "comparing unit values"
682 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
684 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
685 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
686 if expr.span.from_expansion() {
687 if let Some(callee) = expr.span.source_callee() {
688 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
689 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
691 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
692 let result = match &*symbol.as_str() {
693 "assert_eq" | "debug_assert_eq" => "succeed",
694 "assert_ne" | "debug_assert_ne" => "fail",
702 "`{}` of unit values detected. This will always {}",
713 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
715 if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
716 let result = match op {
717 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
725 "{}-comparison of unit values detected. This will always be {}",
735 declare_clippy_lint! {
736 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
737 /// unit literal (`()`).
739 /// **Why is this bad?** This is likely the result of an accidental semicolon.
741 /// **Known problems:** None.
752 "passing unit to a function"
755 declare_lint_pass!(UnitArg => [UNIT_ARG]);
757 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
758 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
759 if expr.span.from_expansion() {
763 // apparently stuff in the desugaring of `?` can trigger this
764 // so check for that here
765 // only the calls to `Try::from_error` is marked as desugared,
766 // so we need to check both the current Expr and its parent.
767 if is_questionmark_desugar_marked_call(expr) {
771 let map = &cx.tcx.hir();
772 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
773 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
774 if is_questionmark_desugar_marked_call(parent_expr);
781 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args) => {
783 if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
784 if let ExprKind::Match(.., match_source) = &arg.kind {
785 if *match_source == MatchSource::TryDesugar {
794 "passing a unit value to a function",
795 "if you intended to pass a unit value, use a unit literal instead",
797 Applicability::MaybeIncorrect,
807 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
808 use rustc_span::hygiene::DesugaringKind;
809 if let ExprKind::Call(ref callee, _) = expr.kind {
810 callee.span.is_desugaring(DesugaringKind::QuestionMark)
816 fn is_unit(ty: Ty<'_>) -> bool {
818 ty::Tuple(slice) if slice.is_empty() => true,
823 fn is_unit_literal(expr: &Expr<'_>) -> bool {
825 ExprKind::Tup(ref slice) if slice.is_empty() => true,
830 declare_clippy_lint! {
831 /// **What it does:** Checks for casts from any numerical to a float type where
832 /// the receiving type cannot store all values from the original type without
833 /// rounding errors. This possible rounding is to be expected, so this lint is
834 /// `Allow` by default.
836 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
837 /// or any 64-bit integer to `f64`.
839 /// **Why is this bad?** It's not bad at all. But in some applications it can be
840 /// helpful to know where precision loss can take place. This lint can help find
841 /// those places in the code.
843 /// **Known problems:** None.
847 /// let x = u64::MAX;
850 pub CAST_PRECISION_LOSS,
852 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
855 declare_clippy_lint! {
856 /// **What it does:** Checks for casts from a signed to an unsigned numerical
857 /// type. In this case, negative values wrap around to large positive values,
858 /// which can be quite surprising in practice. However, as the cast works as
859 /// defined, this lint is `Allow` by default.
861 /// **Why is this bad?** Possibly surprising results. You can activate this lint
862 /// as a one-time check to see where numerical wrapping can arise.
864 /// **Known problems:** None.
869 /// y as u128; // will return 18446744073709551615
873 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
876 declare_clippy_lint! {
877 /// **What it does:** Checks for casts between numerical types that may
878 /// truncate large values. This is expected behavior, so the cast is `Allow` by
881 /// **Why is this bad?** In some problem domains, it is good practice to avoid
882 /// truncation. This lint can be activated to help assess where additional
883 /// checks could be beneficial.
885 /// **Known problems:** None.
889 /// fn as_u8(x: u64) -> u8 {
893 pub CAST_POSSIBLE_TRUNCATION,
895 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
898 declare_clippy_lint! {
899 /// **What it does:** Checks for casts from an unsigned type to a signed type of
900 /// the same size. Performing such a cast is a 'no-op' for the compiler,
901 /// i.e., nothing is changed at the bit level, and the binary representation of
902 /// the value is reinterpreted. This can cause wrapping if the value is too big
903 /// for the target signed type. However, the cast works as defined, so this lint
904 /// is `Allow` by default.
906 /// **Why is this bad?** While such a cast is not bad in itself, the results can
907 /// be surprising when this is not the intended behavior, as demonstrated by the
910 /// **Known problems:** None.
914 /// u32::MAX as i32; // will yield a value of `-1`
916 pub CAST_POSSIBLE_WRAP,
918 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
921 declare_clippy_lint! {
922 /// **What it does:** Checks for casts between numerical types that may
923 /// be replaced by safe conversion functions.
925 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
926 /// conversions, including silently lossy conversions. Conversion functions such
927 /// as `i32::from` will only perform lossless conversions. Using the conversion
928 /// functions prevents conversions from turning into silent lossy conversions if
929 /// the types of the input expressions ever change, and make it easier for
930 /// people reading the code to know that the conversion is lossless.
932 /// **Known problems:** None.
936 /// fn as_u64(x: u8) -> u64 {
941 /// Using `::from` would look like this:
944 /// fn as_u64(x: u8) -> u64 {
950 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
953 declare_clippy_lint! {
954 /// **What it does:** Checks for casts to the same type.
956 /// **Why is this bad?** It's just unnecessary.
958 /// **Known problems:** None.
962 /// let _ = 2i32 as i32;
964 pub UNNECESSARY_CAST,
966 "cast to the same type, e.g., `x as i32` where `x: i32`"
969 declare_clippy_lint! {
970 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
971 /// more-strictly-aligned pointer
973 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
976 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
977 /// on the resulting pointer is fine.
981 /// let _ = (&1u8 as *const u8) as *const u16;
982 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
984 pub CAST_PTR_ALIGNMENT,
986 "cast from a pointer to a more-strictly-aligned pointer"
989 declare_clippy_lint! {
990 /// **What it does:** Checks for casts of function pointers to something other than usize
992 /// **Why is this bad?**
993 /// Casting a function pointer to anything other than usize/isize is not portable across
994 /// architectures, because you end up losing bits if the target type is too small or end up with a
995 /// bunch of extra bits that waste space and add more instructions to the final binary than
996 /// strictly necessary for the problem
998 /// Casting to isize also doesn't make sense since there are no signed addresses.
1004 /// fn fun() -> i32 { 1 }
1005 /// let a = fun as i64;
1008 /// fn fun2() -> i32 { 1 }
1009 /// let a = fun2 as usize;
1011 pub FN_TO_NUMERIC_CAST,
1013 "casting a function pointer to a numeric type other than usize"
1016 declare_clippy_lint! {
1017 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1020 /// **Why is this bad?**
1021 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1022 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1023 /// a comment) to perform the truncation.
1029 /// fn fn1() -> i16 {
1032 /// let _ = fn1 as i32;
1034 /// // Better: Cast to usize first, then comment with the reason for the truncation
1035 /// fn fn2() -> i16 {
1038 /// let fn_ptr = fn2 as usize;
1039 /// let fn_ptr_truncated = fn_ptr as i32;
1041 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1043 "casting a function pointer to a numeric type not wide enough to store the address"
1046 /// Returns the size in bits of an integral type.
1047 /// Will return 0 if the type is not an int or uint variant
1048 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1050 ty::Int(i) => match i {
1051 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1058 ty::Uint(i) => match i {
1059 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1064 UintTy::U128 => 128,
1070 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1072 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => true,
1077 fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1078 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1079 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1080 let arch_dependent_str = "on targets with 64-bit wide pointers ";
1081 let from_nbits_str = if arch_dependent {
1083 } else if is_isize_or_usize(cast_from) {
1084 "32 or 64".to_owned()
1086 int_ty_to_nbits(cast_from, cx.tcx).to_string()
1090 CAST_PRECISION_LOSS,
1093 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1094 but `{1}`'s mantissa is only {4} bits wide)",
1096 if cast_to_f64 { "f64" } else { "f32" },
1097 if arch_dependent { arch_dependent_str } else { "" },
1104 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1105 if let ExprKind::Binary(_, _, _) = op.kind {
1106 if snip.starts_with('(') && snip.ends_with(')') {
1113 fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1114 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1115 if in_constant(cx, expr.hir_id) {
1118 // The suggestion is to use a function call, so if the original expression
1119 // has parens on the outside, they are no longer needed.
1120 let mut applicability = Applicability::MachineApplicable;
1121 let opt = snippet_opt(cx, op.span);
1122 let sugg = if let Some(ref snip) = opt {
1123 if should_strip_parens(op, snip) {
1124 &snip[1..snip.len() - 1]
1129 applicability = Applicability::HasPlaceholders;
1138 "casting `{}` to `{}` may become silently lossy if you later change the type",
1142 format!("{}::from({})", cast_to, sugg),
1153 fn check_loss_of_sign(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1154 if !cast_from.is_signed() || cast_to.is_signed() {
1158 // don't lint for positive constants
1159 let const_val = constant(cx, &cx.tables, op);
1161 if let Some((const_val, _)) = const_val;
1162 if let Constant::Int(n) = const_val;
1163 if let ty::Int(ity) = cast_from.kind;
1164 if sext(cx.tcx, n, ity) >= 0;
1170 // don't lint for the result of methods that always return non-negative values
1171 if let ExprKind::MethodCall(ref path, _, _) = op.kind {
1172 let mut method_name = path.ident.name.as_str();
1173 let whitelisted_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1176 if method_name == "unwrap";
1177 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1178 if let ExprKind::MethodCall(ref inner_path, _, _) = &arglist[0][0].kind;
1180 method_name = inner_path.ident.name.as_str();
1184 if whitelisted_methods.iter().any(|&name| method_name == name) {
1194 "casting `{}` to `{}` may lose the sign of the value",
1200 fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1201 let arch_64_suffix = " on targets with 64-bit wide pointers";
1202 let arch_32_suffix = " on targets with 32-bit wide pointers";
1203 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1204 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1205 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1206 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1207 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1208 (true, true) | (false, false) => (
1209 to_nbits < from_nbits,
1211 to_nbits == from_nbits && cast_unsigned_to_signed,
1221 to_nbits <= 32 && cast_unsigned_to_signed,
1227 cast_unsigned_to_signed,
1228 if from_nbits == 64 {
1235 if span_truncation {
1238 CAST_POSSIBLE_TRUNCATION,
1241 "casting `{}` to `{}` may truncate the value{}",
1244 match suffix_truncation {
1245 ArchSuffix::_32 => arch_32_suffix,
1246 ArchSuffix::_64 => arch_64_suffix,
1247 ArchSuffix::None => "",
1258 "casting `{}` to `{}` may wrap around the value{}",
1262 ArchSuffix::_32 => arch_32_suffix,
1263 ArchSuffix::_64 => arch_64_suffix,
1264 ArchSuffix::None => "",
1271 fn check_lossless(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1272 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1273 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1274 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1275 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1277 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1281 declare_lint_pass!(Casts => [
1282 CAST_PRECISION_LOSS,
1284 CAST_POSSIBLE_TRUNCATION,
1290 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1293 // Check if the given type is either `core::ffi::c_void` or
1294 // one of the platform specific `libc::<platform>::c_void` of libc.
1295 fn is_c_void(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1296 if let ty::Adt(adt, _) = ty.kind {
1297 let names = cx.get_def_path(adt.did);
1299 if names.is_empty() {
1302 if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1309 /// Returns the mantissa bits wide of a fp type.
1310 /// Will return 0 if the type is not a fp
1311 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1313 ty::Float(FloatTy::F32) => 23,
1314 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1319 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
1320 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1321 if expr.span.from_expansion() {
1324 if let ExprKind::Cast(ref ex, _) = expr.kind {
1325 let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
1326 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1327 if let ExprKind::Lit(ref lit) = ex.kind {
1329 if let LitKind::Int(n, _) = lit.node;
1330 if let Some(src) = snippet_opt(cx, lit.span);
1331 if cast_to.is_floating_point();
1332 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1333 let from_nbits = 128 - n.leading_zeros();
1334 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1335 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1341 &format!("casting integer literal to `{}` is unnecessary", cast_to),
1343 format!("{}_{}", n, cast_to),
1344 Applicability::MachineApplicable,
1350 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1352 if cast_from.kind == cast_to.kind && !in_external_macro(cx.sess(), expr.span) {
1358 "casting to the same type is unnecessary (`{}` -> `{}`)",
1366 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1367 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1370 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1375 fn lint_numeric_casts<'tcx>(
1376 cx: &LateContext<'_, 'tcx>,
1378 cast_expr: &Expr<'_>,
1379 cast_from: Ty<'tcx>,
1382 match (cast_from.is_integral(), cast_to.is_integral()) {
1384 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1385 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind {
1390 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1391 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1393 if from_nbits < to_nbits {
1394 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1400 CAST_POSSIBLE_TRUNCATION,
1402 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1404 if !cast_to.is_signed() {
1410 "casting `{}` to `{}` may lose the sign of the value",
1417 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1418 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1419 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1422 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind, &cast_to.kind) {
1425 CAST_POSSIBLE_TRUNCATION,
1427 "casting `f64` to `f32` may truncate the value",
1430 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind, &cast_to.kind) {
1431 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1437 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1439 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind;
1440 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind;
1441 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1442 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1443 if from_layout.align.abi < to_layout.align.abi;
1444 // with c_void, we inherently need to trust the user
1445 if !is_c_void(cx, from_ptr_ty.ty);
1446 // when casting from a ZST, we don't know enough to properly lint
1447 if !from_layout.is_zst();
1454 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1457 from_layout.align.abi.bytes(),
1458 to_layout.align.abi.bytes(),
1465 fn lint_fn_to_numeric_cast(
1466 cx: &LateContext<'_, '_>,
1468 cast_expr: &Expr<'_>,
1472 // We only want to check casts to `ty::Uint` or `ty::Int`
1473 match cast_to.kind {
1474 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1477 match cast_from.kind {
1478 ty::FnDef(..) | ty::FnPtr(_) => {
1479 let mut applicability = Applicability::MaybeIncorrect;
1480 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1482 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1483 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1486 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1489 "casting function pointer `{}` to `{}`, which truncates the value",
1490 from_snippet, cast_to
1493 format!("{} as usize", from_snippet),
1496 } else if cast_to.kind != ty::Uint(UintTy::Usize) {
1501 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1503 format!("{} as usize", from_snippet),
1512 declare_clippy_lint! {
1513 /// **What it does:** Checks for types used in structs, parameters and `let`
1514 /// declarations above a certain complexity threshold.
1516 /// **Why is this bad?** Too complex types make the code less readable. Consider
1517 /// using a `type` definition to simplify them.
1519 /// **Known problems:** None.
1523 /// # use std::rc::Rc;
1525 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1528 pub TYPE_COMPLEXITY,
1530 "usage of very complex types that might be better factored into `type` definitions"
1533 pub struct TypeComplexity {
1537 impl TypeComplexity {
1539 pub fn new(threshold: u64) -> Self {
1544 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1546 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity {
1549 cx: &LateContext<'a, 'tcx>,
1551 decl: &'tcx FnDecl<'_>,
1556 self.check_fndecl(cx, decl);
1559 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField<'_>) {
1560 // enum variants are also struct fields now
1561 self.check_type(cx, &field.ty);
1564 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
1566 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1567 // functions, enums, structs, impls and traits are covered
1572 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
1574 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1575 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1576 // methods with default impl are covered by check_fn
1581 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
1583 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1584 // methods are covered by check_fn
1589 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
1590 if let Some(ref ty) = local.ty {
1591 self.check_type(cx, ty);
1596 impl<'a, 'tcx> TypeComplexity {
1597 fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl<'_>) {
1598 for arg in decl.inputs {
1599 self.check_type(cx, arg);
1601 if let FnRetTy::Return(ref ty) = decl.output {
1602 self.check_type(cx, ty);
1606 fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty<'_>) {
1607 if ty.span.from_expansion() {
1611 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1612 visitor.visit_ty(ty);
1616 if score > self.threshold {
1621 "very complex type used. Consider factoring parts into `type` definitions",
1627 /// Walks a type and assigns a complexity score to it.
1628 struct TypeComplexityVisitor {
1629 /// total complexity score of the type
1631 /// current nesting level
1635 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1636 type Map = Map<'tcx>;
1638 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1639 let (add_score, sub_nest) = match ty.kind {
1640 // _, &x and *x have only small overhead; don't mess with nesting level
1641 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1643 // the "normal" components of a type: named types, arrays/tuples
1644 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1646 // function types bring a lot of overhead
1647 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1649 TyKind::TraitObject(ref param_bounds, _) => {
1650 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1651 bound.bound_generic_params.iter().any(|gen| match gen.kind {
1652 GenericParamKind::Lifetime { .. } => true,
1656 if has_lifetime_parameters {
1657 // complex trait bounds like A<'a, 'b>
1660 // simple trait bounds like A + B
1667 self.score += add_score;
1668 self.nest += sub_nest;
1670 self.nest -= sub_nest;
1672 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1673 NestedVisitorMap::None
1677 declare_clippy_lint! {
1678 /// **What it does:** Checks for expressions where a character literal is cast
1679 /// to `u8` and suggests using a byte literal instead.
1681 /// **Why is this bad?** In general, casting values to smaller types is
1682 /// error-prone and should be avoided where possible. In the particular case of
1683 /// converting a character literal to u8, it is easy to avoid by just using a
1684 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1685 /// than `'a' as u8`.
1687 /// **Known problems:** None.
1694 /// A better version, using the byte literal:
1701 "casting a character literal to `u8` truncates"
1704 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1706 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1707 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1709 if !expr.span.from_expansion();
1710 if let ExprKind::Cast(e, _) = &expr.kind;
1711 if let ExprKind::Lit(l) = &e.kind;
1712 if let LitKind::Char(c) = l.node;
1713 if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).kind;
1715 let mut applicability = Applicability::MachineApplicable;
1716 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
1722 "casting a character literal to `u8` truncates",
1724 diag.note("`char` is four bytes wide, but `u8` is a single byte");
1727 diag.span_suggestion(
1729 "use a byte literal instead",
1730 format!("b{}", snippet),
1740 declare_clippy_lint! {
1741 /// **What it does:** Checks for comparisons where one side of the relation is
1742 /// either the minimum or maximum value for its type and warns if it involves a
1743 /// case that is always true or always false. Only integer and boolean types are
1746 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1747 /// that it is possible for `x` to be less than the minimum. Expressions like
1748 /// `max < x` are probably mistakes.
1750 /// **Known problems:** For `usize` the size of the current compile target will
1751 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1752 /// a comparison to detect target pointer width will trigger this lint. One can
1753 /// use `mem::sizeof` and compare its value or conditional compilation
1755 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1760 /// let vec: Vec<isize> = Vec::new();
1761 /// if vec.len() <= 0 {}
1762 /// if 100 > i32::MAX {}
1764 pub ABSURD_EXTREME_COMPARISONS,
1766 "a comparison with a maximum or minimum value that is always true or false"
1769 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1776 struct ExtremeExpr<'a> {
1781 enum AbsurdComparisonResult {
1784 InequalityImpossible,
1787 fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1788 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1789 let precast_ty = cx.tables.expr_ty(cast_exp);
1790 let cast_ty = cx.tables.expr_ty(expr);
1792 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1798 fn detect_absurd_comparison<'a, 'tcx>(
1799 cx: &LateContext<'a, 'tcx>,
1801 lhs: &'tcx Expr<'_>,
1802 rhs: &'tcx Expr<'_>,
1803 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1804 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
1805 use crate::types::ExtremeType::{Maximum, Minimum};
1806 use crate::utils::comparisons::{normalize_comparison, Rel};
1808 // absurd comparison only makes sense on primitive types
1809 // primitive types don't implement comparison operators with each other
1810 if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1814 // comparisons between fix sized types and target sized types are considered unanalyzable
1815 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1819 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
1821 let lx = detect_extreme_expr(cx, normalized_lhs);
1822 let rx = detect_extreme_expr(cx, normalized_rhs);
1827 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1828 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1834 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1835 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1836 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1837 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1841 Rel::Ne | Rel::Eq => return None,
1845 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
1846 use crate::types::ExtremeType::{Maximum, Minimum};
1848 let ty = cx.tables.expr_ty(expr);
1850 let cv = constant(cx, cx.tables, expr)?.0;
1852 let which = match (&ty.kind, cv) {
1853 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1854 (&ty::Int(ity), Constant::Int(i))
1855 if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1860 (&ty::Bool, Constant::Bool(true)) => Maximum,
1861 (&ty::Int(ity), Constant::Int(i))
1862 if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1866 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1870 Some(ExtremeExpr { which, expr })
1873 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1874 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1875 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
1876 use crate::types::ExtremeType::{Maximum, Minimum};
1878 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
1879 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1880 if !expr.span.from_expansion() {
1881 let msg = "this comparison involving the minimum or maximum element for this \
1882 type contains a case that is always true or always false";
1884 let conclusion = match result {
1885 AlwaysFalse => "this comparison is always false".to_owned(),
1886 AlwaysTrue => "this comparison is always true".to_owned(),
1887 InequalityImpossible => format!(
1888 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
1890 snippet(cx, lhs.span, "lhs"),
1891 snippet(cx, rhs.span, "rhs")
1896 "because `{}` is the {} value for this type, {}",
1897 snippet(cx, culprit.expr.span, "x"),
1898 match culprit.which {
1899 Minimum => "minimum",
1900 Maximum => "maximum",
1905 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
1912 declare_clippy_lint! {
1913 /// **What it does:** Checks for comparisons where the relation is always either
1914 /// true or false, but where one side has been upcast so that the comparison is
1915 /// necessary. Only integer types are checked.
1917 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1918 /// will mistakenly imply that it is possible for `x` to be outside the range of
1921 /// **Known problems:**
1922 /// https://github.com/rust-lang/rust-clippy/issues/886
1927 /// (x as u32) > 300;
1929 pub INVALID_UPCAST_COMPARISONS,
1931 "a comparison involving an upcast which is always true or false"
1934 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
1936 #[derive(Copy, Clone, Debug, Eq)]
1943 #[allow(clippy::cast_sign_loss)]
1945 fn cmp_s_u(s: i128, u: u128) -> Ordering {
1948 } else if u > (i128::max_value() as u128) {
1956 impl PartialEq for FullInt {
1958 fn eq(&self, other: &Self) -> bool {
1959 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
1963 impl PartialOrd for FullInt {
1965 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1966 Some(match (self, other) {
1967 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
1968 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
1969 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
1970 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
1974 impl Ord for FullInt {
1976 fn cmp(&self, other: &Self) -> Ordering {
1977 self.partial_cmp(other)
1978 .expect("`partial_cmp` for FullInt can never return `None`")
1982 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
1983 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1984 let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1985 let cast_ty = cx.tables.expr_ty(expr);
1986 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1987 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1990 match pre_cast_ty.kind {
1991 ty::Int(int_ty) => Some(match int_ty {
1993 FullInt::S(i128::from(i8::min_value())),
1994 FullInt::S(i128::from(i8::max_value())),
1997 FullInt::S(i128::from(i16::min_value())),
1998 FullInt::S(i128::from(i16::max_value())),
2001 FullInt::S(i128::from(i32::min_value())),
2002 FullInt::S(i128::from(i32::max_value())),
2005 FullInt::S(i128::from(i64::min_value())),
2006 FullInt::S(i128::from(i64::max_value())),
2008 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
2010 FullInt::S(isize::min_value() as i128),
2011 FullInt::S(isize::max_value() as i128),
2014 ty::Uint(uint_ty) => Some(match uint_ty {
2016 FullInt::U(u128::from(u8::min_value())),
2017 FullInt::U(u128::from(u8::max_value())),
2020 FullInt::U(u128::from(u16::min_value())),
2021 FullInt::U(u128::from(u16::max_value())),
2024 FullInt::U(u128::from(u32::min_value())),
2025 FullInt::U(u128::from(u32::max_value())),
2028 FullInt::U(u128::from(u64::min_value())),
2029 FullInt::U(u128::from(u64::max_value())),
2031 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
2033 FullInt::U(usize::min_value() as u128),
2034 FullInt::U(usize::max_value() as u128),
2044 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2045 let val = constant(cx, cx.tables, expr)?.0;
2046 if let Constant::Int(const_int) = val {
2047 match cx.tables.expr_ty(expr).kind {
2048 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2049 ty::Uint(_) => Some(FullInt::U(const_int)),
2057 fn err_upcast_comparison(cx: &LateContext<'_, '_>, span: Span, expr: &Expr<'_>, always: bool) {
2058 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2061 INVALID_UPCAST_COMPARISONS,
2064 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2065 snippet(cx, cast_val.span, "the expression"),
2066 if always { "true" } else { "false" },
2072 fn upcast_comparison_bounds_err<'a, 'tcx>(
2073 cx: &LateContext<'a, 'tcx>,
2075 rel: comparisons::Rel,
2076 lhs_bounds: Option<(FullInt, FullInt)>,
2077 lhs: &'tcx Expr<'_>,
2078 rhs: &'tcx Expr<'_>,
2081 use crate::utils::comparisons::Rel;
2083 if let Some((lb, ub)) = lhs_bounds {
2084 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2085 if rel == Rel::Eq || rel == Rel::Ne {
2086 if norm_rhs_val < lb || norm_rhs_val > ub {
2087 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2089 } else if match rel {
2104 Rel::Eq | Rel::Ne => unreachable!(),
2106 err_upcast_comparison(cx, span, lhs, true)
2107 } else if match rel {
2122 Rel::Eq | Rel::Ne => unreachable!(),
2124 err_upcast_comparison(cx, span, lhs, false)
2130 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
2131 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2132 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2133 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2134 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2140 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2141 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2143 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2144 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2149 declare_clippy_lint! {
2150 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2151 /// over different hashers and implicitly defaulting to the default hashing
2152 /// algorithm (`SipHash`).
2154 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2157 /// **Known problems:** Suggestions for replacing constructors can contain
2158 /// false-positives. Also applying suggestions can require modification of other
2159 /// pieces of code, possibly including external crates.
2163 /// # use std::collections::HashMap;
2164 /// # use std::hash::{Hash, BuildHasher};
2165 /// # trait Serialize {};
2166 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2168 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2170 /// could be rewritten as
2172 /// # use std::collections::HashMap;
2173 /// # use std::hash::{Hash, BuildHasher};
2174 /// # trait Serialize {};
2175 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2177 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2179 pub IMPLICIT_HASHER,
2181 "missing generalization over different hashers"
2184 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2186 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
2187 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2188 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
2189 use rustc_span::BytePos;
2191 fn suggestion<'a, 'tcx>(
2192 cx: &LateContext<'a, 'tcx>,
2193 diag: &mut DiagnosticBuilder<'_>,
2194 generics_span: Span,
2195 generics_suggestion_span: Span,
2196 target: &ImplicitHasherType<'_>,
2197 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2199 let generics_snip = snippet(cx, generics_span, "");
2201 let generics_snip = if generics_snip.is_empty() {
2204 &generics_snip[1..generics_snip.len() - 1]
2209 "consider adding a type parameter".to_string(),
2212 generics_suggestion_span,
2214 "<{}{}S: ::std::hash::BuildHasher{}>",
2216 if generics_snip.is_empty() { "" } else { ", " },
2217 if vis.suggestions.is_empty() {
2220 // request users to add `Default` bound so that generic constructors can be used
2227 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2232 if !vis.suggestions.is_empty() {
2233 multispan_sugg(diag, "...and use generic constructor".into(), vis.suggestions);
2237 if !cx.access_levels.is_exported(item.hir_id) {
2248 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2251 for target in &vis.found {
2252 if differing_macro_contexts(item.span, target.span()) {
2256 let generics_suggestion_span = generics.span.substitute_dummy({
2257 let pos = snippet_opt(cx, item.span.until(target.span()))
2258 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2259 if let Some(pos) = pos {
2260 Span::new(pos, pos, item.span.data().ctxt)
2266 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2267 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2268 ctr_vis.visit_impl_item(item);
2276 "impl for `{}` should be generalized over different hashers",
2280 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2285 ItemKind::Fn(ref sig, ref generics, body_id) => {
2286 let body = cx.tcx.hir().body(body_id);
2288 for ty in sig.decl.inputs {
2289 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2292 for target in &vis.found {
2293 if in_external_macro(cx.sess(), generics.span) {
2296 let generics_suggestion_span = generics.span.substitute_dummy({
2297 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2299 let i = snip.find("fn")?;
2300 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2302 .expect("failed to create span for type parameters");
2303 Span::new(pos, pos, item.span.data().ctxt)
2306 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2307 ctr_vis.visit_body(body);
2314 "parameter of type `{}` should be generalized over different hashers",
2318 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2329 enum ImplicitHasherType<'tcx> {
2330 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2331 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2334 impl<'tcx> ImplicitHasherType<'tcx> {
2335 /// Checks that `ty` is a target type without a `BuildHasher`.
2336 fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2337 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2338 let params: Vec<_> = path
2346 .filter_map(|arg| match arg {
2347 GenericArg::Type(ty) => Some(ty),
2351 let params_len = params.len();
2353 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2355 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2356 Some(ImplicitHasherType::HashMap(
2359 snippet(cx, params[0].span, "K"),
2360 snippet(cx, params[1].span, "V"),
2362 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2363 Some(ImplicitHasherType::HashSet(
2366 snippet(cx, params[0].span, "T"),
2376 fn type_name(&self) -> &'static str {
2378 ImplicitHasherType::HashMap(..) => "HashMap",
2379 ImplicitHasherType::HashSet(..) => "HashSet",
2383 fn type_arguments(&self) -> String {
2385 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2386 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2390 fn ty(&self) -> Ty<'tcx> {
2392 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2396 fn span(&self) -> Span {
2398 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2403 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2404 cx: &'a LateContext<'a, 'tcx>,
2405 found: Vec<ImplicitHasherType<'tcx>>,
2408 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2409 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
2410 Self { cx, found: vec![] }
2414 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2415 type Map = Map<'tcx>;
2417 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2418 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2419 self.found.push(target);
2425 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2426 NestedVisitorMap::None
2430 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2431 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2432 cx: &'a LateContext<'a, 'tcx>,
2433 body: &'a TypeckTables<'tcx>,
2434 target: &'b ImplicitHasherType<'tcx>,
2435 suggestions: BTreeMap<Span, String>,
2438 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2439 fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2444 suggestions: BTreeMap::new(),
2449 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2450 type Map = Map<'tcx>;
2452 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2453 let prev_body = self.body;
2454 self.body = self.cx.tcx.body_tables(body.id());
2455 walk_body(self, body);
2456 self.body = prev_body;
2459 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2461 if let ExprKind::Call(ref fun, ref args) = e.kind;
2462 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2463 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2465 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
2469 if match_path(ty_path, &paths::HASHMAP) {
2470 if method.ident.name == sym!(new) {
2472 .insert(e.span, "HashMap::default()".to_string());
2473 } else if method.ident.name == sym!(with_capacity) {
2474 self.suggestions.insert(
2477 "HashMap::with_capacity_and_hasher({}, Default::default())",
2478 snippet(self.cx, args[0].span, "capacity"),
2482 } else if match_path(ty_path, &paths::HASHSET) {
2483 if method.ident.name == sym!(new) {
2485 .insert(e.span, "HashSet::default()".to_string());
2486 } else if method.ident.name == sym!(with_capacity) {
2487 self.suggestions.insert(
2490 "HashSet::with_capacity_and_hasher({}, Default::default())",
2491 snippet(self.cx, args[0].span, "capacity"),
2502 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2503 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2507 declare_clippy_lint! {
2508 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2510 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2511 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2514 /// **Known problems:** None.
2520 /// *(r as *const _ as *mut _) += 1;
2525 /// Instead consider using interior mutability types.
2528 /// use std::cell::UnsafeCell;
2530 /// fn x(r: &UnsafeCell<i32>) {
2536 pub CAST_REF_TO_MUT,
2538 "a cast of reference to a mutable pointer"
2541 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2543 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2544 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2546 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2547 if let ExprKind::Cast(e, t) = &e.kind;
2548 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2549 if let ExprKind::Cast(e, t) = &e.kind;
2550 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2551 if let ty::Ref(..) = cx.tables.node_type(e.hir_id).kind;
2557 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",