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::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy};
9 use rustc_errors::{Applicability, DiagnosticBuilder};
11 use rustc_hir::def::Res;
12 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
14 BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericBounds, GenericParamKind, HirId,
15 ImplItem, ImplItemKind, Item, ItemKind, Lifetime, Lit, Local, MatchSource, MutTy, Mutability, Node, QPath, Stmt,
16 StmtKind, SyntheticTyParamKind, TraitFn, TraitItem, TraitItemKind, TyKind, UnOp,
18 use rustc_lint::{LateContext, LateLintPass, LintContext};
19 use rustc_middle::hir::map::Map;
20 use rustc_middle::lint::in_external_macro;
21 use rustc_middle::ty::TypeFoldable;
22 use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeAndMut, TypeckResults};
23 use rustc_semver::RustcVersion;
24 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
25 use rustc_span::hygiene::{ExpnKind, MacroKind};
26 use rustc_span::source_map::Span;
27 use rustc_span::symbol::sym;
28 use rustc_target::abi::LayoutOf;
29 use rustc_target::spec::abi::Abi;
30 use rustc_typeck::hir_ty_to_ty;
32 use crate::consts::{constant, Constant};
33 use crate::utils::paths;
34 use crate::utils::sugg::Sugg;
36 clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item,
37 last_path_segment, match_def_path, match_path, meets_msrv, method_chain_args, multispan_sugg,
38 numeric_literal::NumericLiteral, qpath_res, reindent_multiline, sext, snippet, snippet_opt,
39 snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg,
40 span_lint_and_then, unsext,
43 declare_clippy_lint! {
44 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
45 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
47 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
48 /// the heap. So if you `Box` it, you just add another level of indirection
49 /// without any benefit whatsoever.
51 /// **Known problems:** None.
56 /// values: Box<Vec<Foo>>,
69 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
72 declare_clippy_lint! {
73 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
74 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
76 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
77 /// the heap. So if you `Box` its contents, you just add another level of indirection.
79 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
85 /// values: Vec<Box<i32>>,
98 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
101 declare_clippy_lint! {
102 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
105 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
106 /// represents an optional optional value which is logically the same thing as an optional
107 /// value but has an unneeded extra level of wrapping.
109 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
110 /// consider a custom `enum` instead, with clear names for each case.
112 /// **Known problems:** None.
116 /// fn get_data() -> Option<Option<u32>> {
124 /// pub enum Contents {
125 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
126 /// NotYetFetched, // Was Some(None)
127 /// None, // Was None
130 /// fn get_data() -> Contents {
136 "usage of `Option<Option<T>>`"
139 declare_clippy_lint! {
140 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
141 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
143 /// **Why is this bad?** Gankro says:
145 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
146 /// pointers and indirection.
147 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
149 /// > "only" amortized for push/pop, should be faster in the general case for
150 /// almost every possible
151 /// > workload, and isn't even amortized at all if you can predict the capacity
154 /// > `LinkedList`s are only really good if you're doing a lot of merging or
155 /// splitting of lists.
156 /// > This is because they can just mangle some pointers instead of actually
157 /// copying the data. Even
158 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
159 /// can still be better
160 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
162 /// **Known problems:** False positives – the instances where using a
163 /// `LinkedList` makes sense are few and far between, but they can still happen.
167 /// # use std::collections::LinkedList;
168 /// let x: LinkedList<usize> = LinkedList::new();
172 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
175 declare_clippy_lint! {
176 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
177 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
179 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
182 /// **Known problems:** None.
186 /// fn foo(bar: &Box<T>) { ... }
192 /// fn foo(bar: &T) { ... }
196 "a borrow of a boxed type"
199 declare_clippy_lint! {
200 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
202 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
203 /// add an unnecessary level of indirection.
205 /// **Known problems:** None.
209 /// # use std::rc::Rc;
210 /// fn foo(bar: Rc<&usize>) {}
216 /// fn foo(bar: &usize) {}
218 pub REDUNDANT_ALLOCATION,
220 "redundant allocation"
223 declare_clippy_lint! {
224 /// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
226 /// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
227 /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
229 /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
230 /// works if there are no additional references yet, which usually defeats the purpose of
231 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
232 /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
235 /// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
236 /// cases where mutation only happens before there are any additional references.
240 /// # use std::rc::Rc;
241 /// fn foo(interned: Rc<String>) { ... }
247 /// fn foo(interned: Rc<str>) { ... }
251 "shared ownership of a buffer type"
255 vec_box_size_threshold: u64,
258 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
260 impl<'tcx> LateLintPass<'tcx> for Types {
261 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
262 // Skip trait implementations; see issue #605.
263 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
264 if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
269 self.check_fn_decl(cx, decl);
272 fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) {
273 self.check_ty(cx, &field.ty, false);
276 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
278 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
279 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
284 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
285 if let Some(ref ty) = local.ty {
286 self.check_ty(cx, ty, true);
291 /// Checks if `qpath` has last segment with type parameter matching `path`
292 fn match_type_parameter(cx: &LateContext<'_>, qpath: &QPath<'_>, path: &[&str]) -> Option<Span> {
293 let last = last_path_segment(qpath);
295 if let Some(ref params) = last.args;
296 if !params.parenthesized;
297 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
298 GenericArg::Type(ty) => Some(ty),
301 if let TyKind::Path(ref qpath) = ty.kind;
302 if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
303 if match_def_path(cx, did, path);
305 return Some(ty.span);
311 fn match_buffer_type(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<&'static str> {
312 if match_type_parameter(cx, qpath, &paths::STRING).is_some() {
315 if match_type_parameter(cx, qpath, &paths::OS_STRING).is_some() {
316 return Some("std::ffi::OsStr");
318 if match_type_parameter(cx, qpath, &paths::PATH_BUF).is_some() {
319 return Some("std::path::Path");
324 fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<Span> {
325 let last = last_path_segment(qpath);
327 if let Some(ref params) = last.args;
328 if !params.parenthesized;
329 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
330 GenericArg::Type(ty) => Some(ty),
333 if let TyKind::Rptr(..) = ty.kind;
335 return Some(ty.span);
342 pub fn new(vec_box_size_threshold: u64) -> Self {
343 Self { vec_box_size_threshold }
346 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
347 for input in decl.inputs {
348 self.check_ty(cx, input, false);
351 if let FnRetTy::Return(ref ty) = decl.output {
352 self.check_ty(cx, ty, false);
356 /// Recursively check for `TypePass` lints in the given type. Stop at the first
359 /// The parameter `is_local` distinguishes the context of the type; types from
360 /// local bindings should only be checked for the `BORROWED_BOX` lint.
361 #[allow(clippy::too_many_lines)]
362 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
363 if hir_ty.span.from_expansion() {
367 TyKind::Path(ref qpath) if !is_local => {
368 let hir_id = hir_ty.hir_id;
369 let res = qpath_res(cx, qpath, hir_id);
370 if let Some(def_id) = res.opt_def_id() {
371 if Some(def_id) == cx.tcx.lang_items().owned_box() {
372 if let Some(span) = match_borrows_parameter(cx, qpath) {
373 let mut applicability = Applicability::MachineApplicable;
376 REDUNDANT_ALLOCATION,
378 "usage of `Box<&T>`",
380 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
383 return; // don't recurse into the type
385 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
390 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
392 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
394 return; // don't recurse into the type
396 } else if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
397 if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) {
398 let mut applicability = Applicability::MachineApplicable;
401 REDUNDANT_ALLOCATION,
403 "usage of `Rc<Rc<T>>`",
405 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
408 return; // don't recurse into the type
410 if match_type_parameter(cx, qpath, &paths::BOX).is_some() {
411 let box_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
412 GenericArg::Type(ty) => match &ty.kind {
413 TyKind::Path(qpath) => qpath,
418 let inner_span = match &last_path_segment(&box_ty).args.unwrap().args[0] {
419 GenericArg::Type(ty) => ty.span,
422 let mut applicability = Applicability::MachineApplicable;
425 REDUNDANT_ALLOCATION,
427 "usage of `Rc<Box<T>>`",
431 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
435 return; // don't recurse into the type
437 if let Some(alternate) = match_buffer_type(cx, qpath) {
442 "usage of `Rc<T>` when T is a buffer type",
444 format!("Rc<{}>", alternate),
445 Applicability::MachineApplicable,
447 return; // don't recurse into the type
449 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
450 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
451 GenericArg::Type(ty) => match &ty.kind {
452 TyKind::Path(qpath) => qpath,
457 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
458 GenericArg::Type(ty) => ty.span,
461 let mut applicability = Applicability::MachineApplicable;
466 "usage of `Rc<T>` when T is a buffer type",
470 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
472 Applicability::MachineApplicable,
474 return; // don't recurse into the type
476 if let Some(span) = match_borrows_parameter(cx, qpath) {
477 let mut applicability = Applicability::MachineApplicable;
480 REDUNDANT_ALLOCATION,
484 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
487 return; // don't recurse into the type
489 } else if cx.tcx.is_diagnostic_item(sym::Arc, def_id) {
490 if let Some(alternate) = match_buffer_type(cx, qpath) {
495 "usage of `Arc<T>` when T is a buffer type",
497 format!("Arc<{}>", alternate),
498 Applicability::MachineApplicable,
500 return; // don't recurse into the type
502 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
503 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
504 GenericArg::Type(ty) => match &ty.kind {
505 TyKind::Path(qpath) => qpath,
510 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
511 GenericArg::Type(ty) => ty.span,
514 let mut applicability = Applicability::MachineApplicable;
519 "usage of `Arc<T>` when T is a buffer type",
523 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
525 Applicability::MachineApplicable,
527 return; // don't recurse into the type
529 } else if cx.tcx.is_diagnostic_item(sym::vec_type, def_id) {
531 // Get the _ part of Vec<_>
532 if let Some(ref last) = last_path_segment(qpath).args;
533 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
534 GenericArg::Type(ty) => Some(ty),
537 // ty is now _ at this point
538 if let TyKind::Path(ref ty_qpath) = ty.kind;
539 let res = qpath_res(cx, ty_qpath, ty.hir_id);
540 if let Some(def_id) = res.opt_def_id();
541 if Some(def_id) == cx.tcx.lang_items().owned_box();
542 // At this point, we know ty is Box<T>, now get T
543 if let Some(ref last) = last_path_segment(ty_qpath).args;
544 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
545 GenericArg::Type(ty) => Some(ty),
548 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
549 if !ty_ty.has_escaping_bound_vars();
550 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env);
551 if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes());
552 if ty_ty_size <= self.vec_box_size_threshold;
558 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
560 format!("Vec<{}>", snippet(cx, boxed_ty.span, "..")),
561 Applicability::MachineApplicable,
563 return; // don't recurse into the type
566 } else if cx.tcx.is_diagnostic_item(sym::option_type, def_id) {
567 if match_type_parameter(cx, qpath, &paths::OPTION).is_some() {
572 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
573 enum if you need to distinguish all 3 cases",
575 return; // don't recurse into the type
577 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
582 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
584 "a `VecDeque` might work",
586 return; // don't recurse into the type
590 QPath::Resolved(Some(ref ty), ref p) => {
591 self.check_ty(cx, ty, is_local);
592 for ty in p.segments.iter().flat_map(|seg| {
595 .map_or_else(|| [].iter(), |params| params.args.iter())
596 .filter_map(|arg| match arg {
597 GenericArg::Type(ty) => Some(ty),
601 self.check_ty(cx, ty, is_local);
604 QPath::Resolved(None, ref p) => {
605 for ty in p.segments.iter().flat_map(|seg| {
608 .map_or_else(|| [].iter(), |params| params.args.iter())
609 .filter_map(|arg| match arg {
610 GenericArg::Type(ty) => Some(ty),
614 self.check_ty(cx, ty, is_local);
617 QPath::TypeRelative(ref ty, ref seg) => {
618 self.check_ty(cx, ty, is_local);
619 if let Some(ref params) = seg.args {
620 for ty in params.args.iter().filter_map(|arg| match arg {
621 GenericArg::Type(ty) => Some(ty),
624 self.check_ty(cx, ty, is_local);
628 QPath::LangItem(..) => {},
631 TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
633 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
634 self.check_ty(cx, ty, is_local)
636 TyKind::Tup(tys) => {
638 self.check_ty(cx, ty, is_local);
647 cx: &LateContext<'_>,
648 hir_ty: &hir::Ty<'_>,
653 match mut_ty.ty.kind {
654 TyKind::Path(ref qpath) => {
655 let hir_id = mut_ty.ty.hir_id;
656 let def = qpath_res(cx, qpath, hir_id);
658 if let Some(def_id) = def.opt_def_id();
659 if Some(def_id) == cx.tcx.lang_items().owned_box();
660 if let QPath::Resolved(None, ref path) = *qpath;
661 if let [ref bx] = *path.segments;
662 if let Some(ref params) = bx.args;
663 if !params.parenthesized;
664 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
665 GenericArg::Type(ty) => Some(ty),
669 if is_any_trait(inner) {
670 // Ignore `Box<Any>` types; see issue #1884 for details.
674 let ltopt = if lt.is_elided() {
677 format!("{} ", lt.name.ident().as_str())
680 if mut_ty.mutbl == Mutability::Mut {
681 // Ignore `&mut Box<T>` types; see issue #2907 for
686 // When trait objects or opaque types have lifetime or auto-trait bounds,
687 // we need to add parentheses to avoid a syntax error due to its ambiguity.
688 // Originally reported as the issue #3128.
689 let inner_snippet = snippet(cx, inner.span, "..");
690 let suggestion = match &inner.kind {
691 TyKind::TraitObject(bounds, lt_bound) if bounds.len() > 1 || !lt_bound.is_elided() => {
692 format!("&{}({})", ltopt, &inner_snippet)
695 if get_bounds_if_impl_trait(cx, qpath, inner.hir_id)
696 .map_or(false, |bounds| bounds.len() > 1) =>
698 format!("&{}({})", ltopt, &inner_snippet)
700 _ => format!("&{}{}", ltopt, &inner_snippet),
706 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
709 // To make this `MachineApplicable`, at least one needs to check if it isn't a trait item
710 // because the trait impls of it will break otherwise;
711 // and there may be other cases that result in invalid code.
712 // For example, type coercion doesn't work nicely.
713 Applicability::Unspecified,
715 return; // don't recurse into the type
718 self.check_ty(cx, &mut_ty.ty, is_local);
720 _ => self.check_ty(cx, &mut_ty.ty, is_local),
725 // Returns true if given type is `Any` trait.
726 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
728 if let TyKind::TraitObject(ref traits, _) = t.kind;
729 if !traits.is_empty();
730 // Only Send/Sync can be used as additional traits, so it is enough to
731 // check only the first trait.
732 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
741 fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: HirId) -> Option<GenericBounds<'tcx>> {
743 if let Some(did) = qpath_res(cx, qpath, id).opt_def_id();
744 if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did);
745 if let GenericParamKind::Type { synthetic, .. } = generic_param.kind;
746 if synthetic == Some(SyntheticTyParamKind::ImplTrait);
748 Some(generic_param.bounds)
755 declare_clippy_lint! {
756 /// **What it does:** Checks for binding a unit value.
758 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
759 /// binding one is kind of pointless.
761 /// **Known problems:** None.
771 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
774 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
776 impl<'tcx> LateLintPass<'tcx> for LetUnitValue {
777 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
778 if let StmtKind::Local(ref local) = stmt.kind {
779 if is_unit(cx.typeck_results().pat_ty(&local.pat)) {
780 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
783 if higher::is_from_for_desugar(local) {
790 "this let-binding has unit value",
792 if let Some(expr) = &local.init {
793 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
794 diag.span_suggestion(
796 "omit the `let` binding",
797 format!("{};", snip),
798 Applicability::MachineApplicable, // snippet
808 declare_clippy_lint! {
809 /// **What it does:** Checks for comparisons to unit. This includes all binary
810 /// comparisons (like `==` and `<`) and asserts.
812 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
813 /// clumsily written constant. Mostly this happens when someone accidentally
814 /// adds semicolons at the end of the operands.
816 /// **Known problems:** None.
847 /// assert_eq!({ foo(); }, { bar(); });
849 /// will always succeed
852 "comparing unit values"
855 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
857 impl<'tcx> LateLintPass<'tcx> for UnitCmp {
858 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
859 if expr.span.from_expansion() {
860 if let Some(callee) = expr.span.source_callee() {
861 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
862 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
864 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
865 let result = match &*symbol.as_str() {
866 "assert_eq" | "debug_assert_eq" => "succeed",
867 "assert_ne" | "debug_assert_ne" => "fail",
875 "`{}` of unit values detected. This will always {}",
886 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
888 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
889 let result = match op {
890 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
898 "{}-comparison of unit values detected. This will always be {}",
908 declare_clippy_lint! {
909 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
910 /// unit literal (`()`).
912 /// **Why is this bad?** This is likely the result of an accidental semicolon.
914 /// **Known problems:** None.
925 "passing unit to a function"
928 declare_lint_pass!(UnitArg => [UNIT_ARG]);
930 impl<'tcx> LateLintPass<'tcx> for UnitArg {
931 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
932 if expr.span.from_expansion() {
936 // apparently stuff in the desugaring of `?` can trigger this
937 // so check for that here
938 // only the calls to `Try::from_error` is marked as desugared,
939 // so we need to check both the current Expr and its parent.
940 if is_questionmark_desugar_marked_call(expr) {
944 let map = &cx.tcx.hir();
945 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
946 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
947 if is_questionmark_desugar_marked_call(parent_expr);
954 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => {
955 let args_to_recover = args
958 if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) {
959 !matches!(&arg.kind, ExprKind::Match(.., MatchSource::TryDesugar))
964 .collect::<Vec<_>>();
965 if !args_to_recover.is_empty() {
966 lint_unit_args(cx, expr, &args_to_recover);
974 fn fmt_stmts_and_call(
975 cx: &LateContext<'_>,
976 call_expr: &Expr<'_>,
978 args_snippets: &[impl AsRef<str>],
979 non_empty_block_args_snippets: &[impl AsRef<str>],
981 let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
982 let call_snippet_with_replacements = args_snippets
984 .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
986 let mut stmts_and_call = non_empty_block_args_snippets
988 .map(|it| it.as_ref().to_owned())
989 .collect::<Vec<_>>();
990 stmts_and_call.push(call_snippet_with_replacements);
991 stmts_and_call = stmts_and_call
993 .map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
996 let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
997 // expr is not in a block statement or result expression position, wrap in a block
998 let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
999 if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
1000 let block_indent = call_expr_indent + 4;
1001 stmts_and_call_snippet =
1002 reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
1003 stmts_and_call_snippet = format!(
1005 " ".repeat(block_indent),
1006 &stmts_and_call_snippet,
1007 " ".repeat(call_expr_indent)
1010 stmts_and_call_snippet
1013 fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
1014 let mut applicability = Applicability::MachineApplicable;
1015 let (singular, plural) = if args_to_recover.len() > 1 {
1024 &format!("passing {}unit value{} to a function", singular, plural),
1031 if let ExprKind::Block(block, _) = arg.kind;
1032 if block.expr.is_none();
1033 if let Some(last_stmt) = block.stmts.iter().last();
1034 if let StmtKind::Semi(last_expr) = last_stmt.kind;
1035 if let Some(snip) = snippet_opt(cx, last_expr.span);
1047 .for_each(|(span, sugg)| {
1050 "remove the semicolon from the last statement in the block",
1052 Applicability::MaybeIncorrect,
1055 applicability = Applicability::MaybeIncorrect;
1058 let arg_snippets: Vec<String> = args_to_recover
1060 .filter_map(|arg| snippet_opt(cx, arg.span))
1062 let arg_snippets_without_empty_blocks: Vec<String> = args_to_recover
1064 .filter(|arg| !is_empty_block(arg))
1065 .filter_map(|arg| snippet_opt(cx, arg.span))
1068 if let Some(call_snippet) = snippet_opt(cx, expr.span) {
1069 let sugg = fmt_stmts_and_call(
1074 &arg_snippets_without_empty_blocks,
1077 if arg_snippets_without_empty_blocks.is_empty() {
1078 db.multipart_suggestion(
1079 &format!("use {}unit literal{} instead", singular, plural),
1082 .map(|arg| (arg.span, "()".to_string()))
1083 .collect::<Vec<_>>(),
1087 let plural = arg_snippets_without_empty_blocks.len() > 1;
1088 let empty_or_s = if plural { "s" } else { "" };
1089 let it_or_them = if plural { "them" } else { "it" };
1093 "{}move the expression{} in front of the call and replace {} with the unit literal `()`",
1094 or, empty_or_s, it_or_them
1105 fn is_empty_block(expr: &Expr<'_>) -> bool {
1119 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
1120 use rustc_span::hygiene::DesugaringKind;
1121 if let ExprKind::Call(ref callee, _) = expr.kind {
1122 callee.span.is_desugaring(DesugaringKind::QuestionMark)
1128 fn is_unit(ty: Ty<'_>) -> bool {
1129 matches!(ty.kind(), ty::Tuple(slice) if slice.is_empty())
1132 fn is_unit_literal(expr: &Expr<'_>) -> bool {
1133 matches!(expr.kind, ExprKind::Tup(ref slice) if slice.is_empty())
1136 declare_clippy_lint! {
1137 /// **What it does:** Checks for casts from any numerical to a float type where
1138 /// the receiving type cannot store all values from the original type without
1139 /// rounding errors. This possible rounding is to be expected, so this lint is
1140 /// `Allow` by default.
1142 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
1143 /// or any 64-bit integer to `f64`.
1145 /// **Why is this bad?** It's not bad at all. But in some applications it can be
1146 /// helpful to know where precision loss can take place. This lint can help find
1147 /// those places in the code.
1149 /// **Known problems:** None.
1153 /// let x = u64::MAX;
1156 pub CAST_PRECISION_LOSS,
1158 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
1161 declare_clippy_lint! {
1162 /// **What it does:** Checks for casts from a signed to an unsigned numerical
1163 /// type. In this case, negative values wrap around to large positive values,
1164 /// which can be quite surprising in practice. However, as the cast works as
1165 /// defined, this lint is `Allow` by default.
1167 /// **Why is this bad?** Possibly surprising results. You can activate this lint
1168 /// as a one-time check to see where numerical wrapping can arise.
1170 /// **Known problems:** None.
1175 /// y as u128; // will return 18446744073709551615
1179 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
1182 declare_clippy_lint! {
1183 /// **What it does:** Checks for casts between numerical types that may
1184 /// truncate large values. This is expected behavior, so the cast is `Allow` by
1187 /// **Why is this bad?** In some problem domains, it is good practice to avoid
1188 /// truncation. This lint can be activated to help assess where additional
1189 /// checks could be beneficial.
1191 /// **Known problems:** None.
1195 /// fn as_u8(x: u64) -> u8 {
1199 pub CAST_POSSIBLE_TRUNCATION,
1201 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
1204 declare_clippy_lint! {
1205 /// **What it does:** Checks for casts from an unsigned type to a signed type of
1206 /// the same size. Performing such a cast is a 'no-op' for the compiler,
1207 /// i.e., nothing is changed at the bit level, and the binary representation of
1208 /// the value is reinterpreted. This can cause wrapping if the value is too big
1209 /// for the target signed type. However, the cast works as defined, so this lint
1210 /// is `Allow` by default.
1212 /// **Why is this bad?** While such a cast is not bad in itself, the results can
1213 /// be surprising when this is not the intended behavior, as demonstrated by the
1216 /// **Known problems:** None.
1220 /// u32::MAX as i32; // will yield a value of `-1`
1222 pub CAST_POSSIBLE_WRAP,
1224 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
1227 declare_clippy_lint! {
1228 /// **What it does:** Checks for casts between numerical types that may
1229 /// be replaced by safe conversion functions.
1231 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
1232 /// conversions, including silently lossy conversions. Conversion functions such
1233 /// as `i32::from` will only perform lossless conversions. Using the conversion
1234 /// functions prevents conversions from turning into silent lossy conversions if
1235 /// the types of the input expressions ever change, and make it easier for
1236 /// people reading the code to know that the conversion is lossless.
1238 /// **Known problems:** None.
1242 /// fn as_u64(x: u8) -> u64 {
1247 /// Using `::from` would look like this:
1250 /// fn as_u64(x: u8) -> u64 {
1256 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
1259 declare_clippy_lint! {
1260 /// **What it does:** Checks for casts to the same type, casts of int literals to integer types
1261 /// and casts of float literals to float types.
1263 /// **Why is this bad?** It's just unnecessary.
1265 /// **Known problems:** None.
1269 /// let _ = 2i32 as i32;
1270 /// let _ = 0.5 as f32;
1277 /// let _ = 0.5_f32;
1279 pub UNNECESSARY_CAST,
1281 "cast to the same type, e.g., `x as i32` where `x: i32`"
1284 declare_clippy_lint! {
1285 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
1286 /// more-strictly-aligned pointer
1288 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
1291 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
1292 /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
1293 /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
1297 /// let _ = (&1u8 as *const u8) as *const u16;
1298 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
1300 pub CAST_PTR_ALIGNMENT,
1302 "cast from a pointer to a more-strictly-aligned pointer"
1305 declare_clippy_lint! {
1306 /// **What it does:** Checks for casts of function pointers to something other than usize
1308 /// **Why is this bad?**
1309 /// Casting a function pointer to anything other than usize/isize is not portable across
1310 /// architectures, because you end up losing bits if the target type is too small or end up with a
1311 /// bunch of extra bits that waste space and add more instructions to the final binary than
1312 /// strictly necessary for the problem
1314 /// Casting to isize also doesn't make sense since there are no signed addresses.
1320 /// fn fun() -> i32 { 1 }
1321 /// let a = fun as i64;
1324 /// fn fun2() -> i32 { 1 }
1325 /// let a = fun2 as usize;
1327 pub FN_TO_NUMERIC_CAST,
1329 "casting a function pointer to a numeric type other than usize"
1332 declare_clippy_lint! {
1333 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1336 /// **Why is this bad?**
1337 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1338 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1339 /// a comment) to perform the truncation.
1345 /// fn fn1() -> i16 {
1348 /// let _ = fn1 as i32;
1350 /// // Better: Cast to usize first, then comment with the reason for the truncation
1351 /// fn fn2() -> i16 {
1354 /// let fn_ptr = fn2 as usize;
1355 /// let fn_ptr_truncated = fn_ptr as i32;
1357 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1359 "casting a function pointer to a numeric type not wide enough to store the address"
1362 /// Returns the size in bits of an integral type.
1363 /// Will return 0 if the type is not an int or uint variant
1364 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1366 ty::Int(i) => match i {
1367 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1374 ty::Uint(i) => match i {
1375 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1380 UintTy::U128 => 128,
1386 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1387 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
1390 fn span_precision_loss_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1391 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1392 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1393 let arch_dependent_str = "on targets with 64-bit wide pointers ";
1394 let from_nbits_str = if arch_dependent {
1396 } else if is_isize_or_usize(cast_from) {
1397 "32 or 64".to_owned()
1399 int_ty_to_nbits(cast_from, cx.tcx).to_string()
1403 CAST_PRECISION_LOSS,
1406 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1407 but `{1}`'s mantissa is only {4} bits wide)",
1409 if cast_to_f64 { "f64" } else { "f32" },
1410 if arch_dependent { arch_dependent_str } else { "" },
1417 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1418 if let ExprKind::Binary(_, _, _) = op.kind {
1419 if snip.starts_with('(') && snip.ends_with(')') {
1426 fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1427 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1428 if in_constant(cx, expr.hir_id) {
1431 // The suggestion is to use a function call, so if the original expression
1432 // has parens on the outside, they are no longer needed.
1433 let mut applicability = Applicability::MachineApplicable;
1434 let opt = snippet_opt(cx, op.span);
1435 let sugg = opt.as_ref().map_or_else(
1437 applicability = Applicability::HasPlaceholders;
1441 if should_strip_parens(op, snip) {
1442 &snip[1..snip.len() - 1]
1454 "casting `{}` to `{}` may become silently lossy if you later change the type",
1458 format!("{}::from({})", cast_to, sugg),
1469 fn check_loss_of_sign(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1470 if !cast_from.is_signed() || cast_to.is_signed() {
1474 // don't lint for positive constants
1475 let const_val = constant(cx, &cx.typeck_results(), op);
1477 if let Some((Constant::Int(n), _)) = const_val;
1478 if let ty::Int(ity) = *cast_from.kind();
1479 if sext(cx.tcx, n, ity) >= 0;
1485 // don't lint for the result of methods that always return non-negative values
1486 if let ExprKind::MethodCall(ref path, _, _, _) = op.kind {
1487 let mut method_name = path.ident.name.as_str();
1488 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1491 if method_name == "unwrap";
1492 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1493 if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
1495 method_name = inner_path.ident.name.as_str();
1499 if allowed_methods.iter().any(|&name| method_name == name) {
1509 "casting `{}` to `{}` may lose the sign of the value",
1515 fn check_truncation_and_wrapping(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1516 let arch_64_suffix = " on targets with 64-bit wide pointers";
1517 let arch_32_suffix = " on targets with 32-bit wide pointers";
1518 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1519 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1520 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1521 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1522 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1523 (true, true) | (false, false) => (
1524 to_nbits < from_nbits,
1526 to_nbits == from_nbits && cast_unsigned_to_signed,
1536 to_nbits <= 32 && cast_unsigned_to_signed,
1542 cast_unsigned_to_signed,
1543 if from_nbits == 64 {
1550 if span_truncation {
1553 CAST_POSSIBLE_TRUNCATION,
1556 "casting `{}` to `{}` may truncate the value{}",
1559 match suffix_truncation {
1560 ArchSuffix::_32 => arch_32_suffix,
1561 ArchSuffix::_64 => arch_64_suffix,
1562 ArchSuffix::None => "",
1573 "casting `{}` to `{}` may wrap around the value{}",
1577 ArchSuffix::_32 => arch_32_suffix,
1578 ArchSuffix::_64 => arch_64_suffix,
1579 ArchSuffix::None => "",
1586 fn check_lossless(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1587 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1588 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1589 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1590 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1592 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1596 declare_lint_pass!(Casts => [
1597 CAST_PRECISION_LOSS,
1599 CAST_POSSIBLE_TRUNCATION,
1605 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1608 // Check if the given type is either `core::ffi::c_void` or
1609 // one of the platform specific `libc::<platform>::c_void` of libc.
1610 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
1611 if let ty::Adt(adt, _) = ty.kind() {
1612 let names = cx.get_def_path(adt.did);
1614 if names.is_empty() {
1617 if names[0] == sym::libc || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1624 /// Returns the mantissa bits wide of a fp type.
1625 /// Will return 0 if the type is not a fp
1626 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1628 ty::Float(FloatTy::F32) => 23,
1629 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1634 impl<'tcx> LateLintPass<'tcx> for Casts {
1635 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1636 if expr.span.from_expansion() {
1639 if let ExprKind::Cast(ref ex, cast_to) = expr.kind {
1640 if is_hir_ty_cfg_dependant(cx, cast_to) {
1643 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
1644 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1645 if let Some(lit) = get_numeric_literal(ex) {
1646 let literal_str = snippet_opt(cx, ex.span).unwrap_or_default();
1649 if let LitKind::Int(n, _) = lit.node;
1650 if let Some(src) = snippet_opt(cx, lit.span);
1651 if cast_to.is_floating_point();
1652 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1653 let from_nbits = 128 - n.leading_zeros();
1654 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1655 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1657 let literal_str = if is_unary_neg(ex) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
1658 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1664 LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
1665 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1667 LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
1668 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1670 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1672 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
1678 "casting to the same type is unnecessary (`{}` -> `{}`)",
1686 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1687 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1690 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1691 } else if let ExprKind::MethodCall(method_path, _, args, _) = expr.kind {
1692 if method_path.ident.name != sym!(cast) {
1696 if let Some(generic_args) = method_path.args;
1697 if let [GenericArg::Type(cast_to)] = generic_args.args;
1698 // There probably is no obvious reason to do this, just to be consistent with `as` cases.
1699 if is_hir_ty_cfg_dependant(cx, cast_to);
1704 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(&args[0]), cx.typeck_results().expr_ty(expr));
1705 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1710 fn is_unary_neg(expr: &Expr<'_>) -> bool {
1711 matches!(expr.kind, ExprKind::Unary(UnOp::UnNeg, _))
1714 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
1716 ExprKind::Lit(ref lit) => Some(lit),
1717 ExprKind::Unary(UnOp::UnNeg, e) => {
1718 if let ExprKind::Lit(ref lit) = e.kind {
1728 fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
1730 if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
1731 if let Res::Def(_, def_id) = path.res;
1733 cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr)
1740 fn show_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1741 let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
1746 &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
1748 format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
1749 Applicability::MachineApplicable,
1753 fn lint_numeric_casts<'tcx>(
1754 cx: &LateContext<'tcx>,
1756 cast_expr: &Expr<'_>,
1757 cast_from: Ty<'tcx>,
1760 match (cast_from.is_integral(), cast_to.is_integral()) {
1762 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1763 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
1768 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1769 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1771 if from_nbits < to_nbits {
1772 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1778 CAST_POSSIBLE_TRUNCATION,
1780 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1782 if !cast_to.is_signed() {
1788 "casting `{}` to `{}` may lose the sign of the value",
1795 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1796 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1797 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1800 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
1803 CAST_POSSIBLE_TRUNCATION,
1805 "casting `f64` to `f32` may truncate the value",
1808 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
1809 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1815 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1817 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
1818 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
1819 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1820 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1821 if from_layout.align.abi < to_layout.align.abi;
1822 // with c_void, we inherently need to trust the user
1823 if !is_c_void(cx, from_ptr_ty.ty);
1824 // when casting from a ZST, we don't know enough to properly lint
1825 if !from_layout.is_zst();
1832 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1835 from_layout.align.abi.bytes(),
1836 to_layout.align.abi.bytes(),
1843 fn lint_fn_to_numeric_cast(
1844 cx: &LateContext<'_>,
1846 cast_expr: &Expr<'_>,
1850 // We only want to check casts to `ty::Uint` or `ty::Int`
1851 match cast_to.kind() {
1852 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1855 match cast_from.kind() {
1856 ty::FnDef(..) | ty::FnPtr(_) => {
1857 let mut applicability = Applicability::MaybeIncorrect;
1858 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1860 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1861 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1864 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1867 "casting function pointer `{}` to `{}`, which truncates the value",
1868 from_snippet, cast_to
1871 format!("{} as usize", from_snippet),
1874 } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
1879 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1881 format!("{} as usize", from_snippet),
1890 declare_clippy_lint! {
1891 /// **What it does:** Checks for types used in structs, parameters and `let`
1892 /// declarations above a certain complexity threshold.
1894 /// **Why is this bad?** Too complex types make the code less readable. Consider
1895 /// using a `type` definition to simplify them.
1897 /// **Known problems:** None.
1901 /// # use std::rc::Rc;
1903 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1906 pub TYPE_COMPLEXITY,
1908 "usage of very complex types that might be better factored into `type` definitions"
1911 pub struct TypeComplexity {
1915 impl TypeComplexity {
1917 pub fn new(threshold: u64) -> Self {
1922 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1924 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
1927 cx: &LateContext<'tcx>,
1929 decl: &'tcx FnDecl<'_>,
1934 self.check_fndecl(cx, decl);
1937 fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
1938 // enum variants are also struct fields now
1939 self.check_type(cx, &field.ty);
1942 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1944 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1945 // functions, enums, structs, impls and traits are covered
1950 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1952 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1953 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1954 // methods with default impl are covered by check_fn
1959 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
1961 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1962 // methods are covered by check_fn
1967 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
1968 if let Some(ref ty) = local.ty {
1969 self.check_type(cx, ty);
1974 impl<'tcx> TypeComplexity {
1975 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
1976 for arg in decl.inputs {
1977 self.check_type(cx, arg);
1979 if let FnRetTy::Return(ref ty) = decl.output {
1980 self.check_type(cx, ty);
1984 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
1985 if ty.span.from_expansion() {
1989 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1990 visitor.visit_ty(ty);
1994 if score > self.threshold {
1999 "very complex type used. Consider factoring parts into `type` definitions",
2005 /// Walks a type and assigns a complexity score to it.
2006 struct TypeComplexityVisitor {
2007 /// total complexity score of the type
2009 /// current nesting level
2013 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
2014 type Map = Map<'tcx>;
2016 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
2017 let (add_score, sub_nest) = match ty.kind {
2018 // _, &x and *x have only small overhead; don't mess with nesting level
2019 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
2021 // the "normal" components of a type: named types, arrays/tuples
2022 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
2024 // function types bring a lot of overhead
2025 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
2027 TyKind::TraitObject(ref param_bounds, _) => {
2028 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
2030 .bound_generic_params
2032 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
2034 if has_lifetime_parameters {
2035 // complex trait bounds like A<'a, 'b>
2038 // simple trait bounds like A + B
2045 self.score += add_score;
2046 self.nest += sub_nest;
2048 self.nest -= sub_nest;
2050 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2051 NestedVisitorMap::None
2055 declare_clippy_lint! {
2056 /// **What it does:** Checks for expressions where a character literal is cast
2057 /// to `u8` and suggests using a byte literal instead.
2059 /// **Why is this bad?** In general, casting values to smaller types is
2060 /// error-prone and should be avoided where possible. In the particular case of
2061 /// converting a character literal to u8, it is easy to avoid by just using a
2062 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
2063 /// than `'a' as u8`.
2065 /// **Known problems:** None.
2072 /// A better version, using the byte literal:
2079 "casting a character literal to `u8` truncates"
2082 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
2084 impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
2085 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2087 if !expr.span.from_expansion();
2088 if let ExprKind::Cast(e, _) = &expr.kind;
2089 if let ExprKind::Lit(l) = &e.kind;
2090 if let LitKind::Char(c) = l.node;
2091 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
2093 let mut applicability = Applicability::MachineApplicable;
2094 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
2100 "casting a character literal to `u8` truncates",
2102 diag.note("`char` is four bytes wide, but `u8` is a single byte");
2105 diag.span_suggestion(
2107 "use a byte literal instead",
2108 format!("b{}", snippet),
2118 declare_clippy_lint! {
2119 /// **What it does:** Checks for comparisons where one side of the relation is
2120 /// either the minimum or maximum value for its type and warns if it involves a
2121 /// case that is always true or always false. Only integer and boolean types are
2124 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
2125 /// that it is possible for `x` to be less than the minimum. Expressions like
2126 /// `max < x` are probably mistakes.
2128 /// **Known problems:** For `usize` the size of the current compile target will
2129 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
2130 /// a comparison to detect target pointer width will trigger this lint. One can
2131 /// use `mem::sizeof` and compare its value or conditional compilation
2133 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
2138 /// let vec: Vec<isize> = Vec::new();
2139 /// if vec.len() <= 0 {}
2140 /// if 100 > i32::MAX {}
2142 pub ABSURD_EXTREME_COMPARISONS,
2144 "a comparison with a maximum or minimum value that is always true or false"
2147 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
2154 struct ExtremeExpr<'a> {
2159 enum AbsurdComparisonResult {
2162 InequalityImpossible,
2165 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
2166 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2167 let precast_ty = cx.typeck_results().expr_ty(cast_exp);
2168 let cast_ty = cx.typeck_results().expr_ty(expr);
2170 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
2176 fn detect_absurd_comparison<'tcx>(
2177 cx: &LateContext<'tcx>,
2179 lhs: &'tcx Expr<'_>,
2180 rhs: &'tcx Expr<'_>,
2181 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
2182 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2183 use crate::types::ExtremeType::{Maximum, Minimum};
2184 use crate::utils::comparisons::{normalize_comparison, Rel};
2186 // absurd comparison only makes sense on primitive types
2187 // primitive types don't implement comparison operators with each other
2188 if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
2192 // comparisons between fix sized types and target sized types are considered unanalyzable
2193 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
2197 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
2199 let lx = detect_extreme_expr(cx, normalized_lhs);
2200 let rx = detect_extreme_expr(cx, normalized_rhs);
2205 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
2206 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
2212 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
2213 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
2214 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
2215 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
2219 Rel::Ne | Rel::Eq => return None,
2223 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
2224 use crate::types::ExtremeType::{Maximum, Minimum};
2226 let ty = cx.typeck_results().expr_ty(expr);
2228 let cv = constant(cx, cx.typeck_results(), expr)?.0;
2230 let which = match (ty.kind(), cv) {
2231 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
2232 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
2236 (&ty::Bool, Constant::Bool(true)) => Maximum,
2237 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
2240 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
2244 Some(ExtremeExpr { which, expr })
2247 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
2248 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2249 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2250 use crate::types::ExtremeType::{Maximum, Minimum};
2252 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2253 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
2254 if !expr.span.from_expansion() {
2255 let msg = "this comparison involving the minimum or maximum element for this \
2256 type contains a case that is always true or always false";
2258 let conclusion = match result {
2259 AlwaysFalse => "this comparison is always false".to_owned(),
2260 AlwaysTrue => "this comparison is always true".to_owned(),
2261 InequalityImpossible => format!(
2262 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
2264 snippet(cx, lhs.span, "lhs"),
2265 snippet(cx, rhs.span, "rhs")
2270 "because `{}` is the {} value for this type, {}",
2271 snippet(cx, culprit.expr.span, "x"),
2272 match culprit.which {
2273 Minimum => "minimum",
2274 Maximum => "maximum",
2279 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
2286 declare_clippy_lint! {
2287 /// **What it does:** Checks for comparisons where the relation is always either
2288 /// true or false, but where one side has been upcast so that the comparison is
2289 /// necessary. Only integer types are checked.
2291 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
2292 /// will mistakenly imply that it is possible for `x` to be outside the range of
2295 /// **Known problems:**
2296 /// https://github.com/rust-lang/rust-clippy/issues/886
2301 /// (x as u32) > 300;
2303 pub INVALID_UPCAST_COMPARISONS,
2305 "a comparison involving an upcast which is always true or false"
2308 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
2310 #[derive(Copy, Clone, Debug, Eq)]
2317 #[allow(clippy::cast_sign_loss)]
2319 fn cmp_s_u(s: i128, u: u128) -> Ordering {
2322 } else if u > (i128::MAX as u128) {
2330 impl PartialEq for FullInt {
2332 fn eq(&self, other: &Self) -> bool {
2333 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
2337 impl PartialOrd for FullInt {
2339 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2340 Some(match (self, other) {
2341 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
2342 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
2343 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
2344 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
2349 impl Ord for FullInt {
2351 fn cmp(&self, other: &Self) -> Ordering {
2352 self.partial_cmp(other)
2353 .expect("`partial_cmp` for FullInt can never return `None`")
2357 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
2358 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2359 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
2360 let cast_ty = cx.typeck_results().expr_ty(expr);
2361 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
2362 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
2365 match pre_cast_ty.kind() {
2366 ty::Int(int_ty) => Some(match int_ty {
2367 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
2368 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
2369 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
2370 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
2371 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
2372 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
2374 ty::Uint(uint_ty) => Some(match uint_ty {
2375 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
2376 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
2377 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
2378 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
2379 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
2380 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
2389 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2390 let val = constant(cx, cx.typeck_results(), expr)?.0;
2391 if let Constant::Int(const_int) = val {
2392 match *cx.typeck_results().expr_ty(expr).kind() {
2393 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2394 ty::Uint(_) => Some(FullInt::U(const_int)),
2402 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
2403 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2406 INVALID_UPCAST_COMPARISONS,
2409 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2410 snippet(cx, cast_val.span, "the expression"),
2411 if always { "true" } else { "false" },
2417 fn upcast_comparison_bounds_err<'tcx>(
2418 cx: &LateContext<'tcx>,
2420 rel: comparisons::Rel,
2421 lhs_bounds: Option<(FullInt, FullInt)>,
2422 lhs: &'tcx Expr<'_>,
2423 rhs: &'tcx Expr<'_>,
2426 use crate::utils::comparisons::Rel;
2428 if let Some((lb, ub)) = lhs_bounds {
2429 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2430 if rel == Rel::Eq || rel == Rel::Ne {
2431 if norm_rhs_val < lb || norm_rhs_val > ub {
2432 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2434 } else if match rel {
2449 Rel::Eq | Rel::Ne => unreachable!(),
2451 err_upcast_comparison(cx, span, lhs, true)
2452 } else if match rel {
2467 Rel::Eq | Rel::Ne => unreachable!(),
2469 err_upcast_comparison(cx, span, lhs, false)
2475 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
2476 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2477 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2478 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2479 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2485 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2486 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2488 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2489 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2494 declare_clippy_lint! {
2495 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2496 /// over different hashers and implicitly defaulting to the default hashing
2497 /// algorithm (`SipHash`).
2499 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2502 /// **Known problems:** Suggestions for replacing constructors can contain
2503 /// false-positives. Also applying suggestions can require modification of other
2504 /// pieces of code, possibly including external crates.
2508 /// # use std::collections::HashMap;
2509 /// # use std::hash::{Hash, BuildHasher};
2510 /// # trait Serialize {};
2511 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2513 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2515 /// could be rewritten as
2517 /// # use std::collections::HashMap;
2518 /// # use std::hash::{Hash, BuildHasher};
2519 /// # trait Serialize {};
2520 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2522 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2524 pub IMPLICIT_HASHER,
2526 "missing generalization over different hashers"
2529 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2531 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
2532 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2533 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
2534 use rustc_span::BytePos;
2536 fn suggestion<'tcx>(
2537 cx: &LateContext<'tcx>,
2538 diag: &mut DiagnosticBuilder<'_>,
2539 generics_span: Span,
2540 generics_suggestion_span: Span,
2541 target: &ImplicitHasherType<'_>,
2542 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2544 let generics_snip = snippet(cx, generics_span, "");
2546 let generics_snip = if generics_snip.is_empty() {
2549 &generics_snip[1..generics_snip.len() - 1]
2554 "consider adding a type parameter",
2557 generics_suggestion_span,
2559 "<{}{}S: ::std::hash::BuildHasher{}>",
2561 if generics_snip.is_empty() { "" } else { ", " },
2562 if vis.suggestions.is_empty() {
2565 // request users to add `Default` bound so that generic constructors can be used
2572 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2577 if !vis.suggestions.is_empty() {
2578 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
2582 if !cx.access_levels.is_exported(item.hir_id) {
2593 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2596 for target in &vis.found {
2597 if differing_macro_contexts(item.span, target.span()) {
2601 let generics_suggestion_span = generics.span.substitute_dummy({
2602 let pos = snippet_opt(cx, item.span.until(target.span()))
2603 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2604 if let Some(pos) = pos {
2605 Span::new(pos, pos, item.span.data().ctxt)
2611 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2612 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2613 ctr_vis.visit_impl_item(item);
2621 "impl for `{}` should be generalized over different hashers",
2625 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2630 ItemKind::Fn(ref sig, ref generics, body_id) => {
2631 let body = cx.tcx.hir().body(body_id);
2633 for ty in sig.decl.inputs {
2634 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2637 for target in &vis.found {
2638 if in_external_macro(cx.sess(), generics.span) {
2641 let generics_suggestion_span = generics.span.substitute_dummy({
2642 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2644 let i = snip.find("fn")?;
2645 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2647 .expect("failed to create span for type parameters");
2648 Span::new(pos, pos, item.span.data().ctxt)
2651 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2652 ctr_vis.visit_body(body);
2659 "parameter of type `{}` should be generalized over different hashers",
2663 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2674 enum ImplicitHasherType<'tcx> {
2675 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2676 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2679 impl<'tcx> ImplicitHasherType<'tcx> {
2680 /// Checks that `ty` is a target type without a `BuildHasher`.
2681 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2682 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2683 let params: Vec<_> = path
2691 .filter_map(|arg| match arg {
2692 GenericArg::Type(ty) => Some(ty),
2696 let params_len = params.len();
2698 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2700 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2701 Some(ImplicitHasherType::HashMap(
2704 snippet(cx, params[0].span, "K"),
2705 snippet(cx, params[1].span, "V"),
2707 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2708 Some(ImplicitHasherType::HashSet(
2711 snippet(cx, params[0].span, "T"),
2721 fn type_name(&self) -> &'static str {
2723 ImplicitHasherType::HashMap(..) => "HashMap",
2724 ImplicitHasherType::HashSet(..) => "HashSet",
2728 fn type_arguments(&self) -> String {
2730 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2731 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2735 fn ty(&self) -> Ty<'tcx> {
2737 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2741 fn span(&self) -> Span {
2743 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2748 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2749 cx: &'a LateContext<'tcx>,
2750 found: Vec<ImplicitHasherType<'tcx>>,
2753 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2754 fn new(cx: &'a LateContext<'tcx>) -> Self {
2755 Self { cx, found: vec![] }
2759 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2760 type Map = Map<'tcx>;
2762 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2763 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2764 self.found.push(target);
2770 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2771 NestedVisitorMap::None
2775 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2776 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2777 cx: &'a LateContext<'tcx>,
2778 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
2779 target: &'b ImplicitHasherType<'tcx>,
2780 suggestions: BTreeMap<Span, String>,
2783 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2784 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2787 maybe_typeck_results: cx.maybe_typeck_results(),
2789 suggestions: BTreeMap::new(),
2794 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2795 type Map = Map<'tcx>;
2797 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2798 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
2799 walk_body(self, body);
2800 self.maybe_typeck_results = old_maybe_typeck_results;
2803 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2805 if let ExprKind::Call(ref fun, ref args) = e.kind;
2806 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2807 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2809 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
2813 if match_path(ty_path, &paths::HASHMAP) {
2814 if method.ident.name == sym::new {
2816 .insert(e.span, "HashMap::default()".to_string());
2817 } else if method.ident.name == sym!(with_capacity) {
2818 self.suggestions.insert(
2821 "HashMap::with_capacity_and_hasher({}, Default::default())",
2822 snippet(self.cx, args[0].span, "capacity"),
2826 } else if match_path(ty_path, &paths::HASHSET) {
2827 if method.ident.name == sym::new {
2829 .insert(e.span, "HashSet::default()".to_string());
2830 } else if method.ident.name == sym!(with_capacity) {
2831 self.suggestions.insert(
2834 "HashSet::with_capacity_and_hasher({}, Default::default())",
2835 snippet(self.cx, args[0].span, "capacity"),
2846 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2847 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2851 declare_clippy_lint! {
2852 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2854 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2855 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2858 /// **Known problems:** None.
2864 /// *(r as *const _ as *mut _) += 1;
2869 /// Instead consider using interior mutability types.
2872 /// use std::cell::UnsafeCell;
2874 /// fn x(r: &UnsafeCell<i32>) {
2880 pub CAST_REF_TO_MUT,
2882 "a cast of reference to a mutable pointer"
2885 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2887 impl<'tcx> LateLintPass<'tcx> for RefToMut {
2888 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2890 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2891 if let ExprKind::Cast(e, t) = &e.kind;
2892 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2893 if let ExprKind::Cast(e, t) = &e.kind;
2894 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2895 if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
2901 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",
2908 const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0);
2910 declare_clippy_lint! {
2911 /// **What it does:**
2912 /// Checks for `as` casts between raw pointers without changing its mutability,
2913 /// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
2915 /// **Why is this bad?**
2916 /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
2917 /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
2919 /// **Known problems:** None.
2924 /// let ptr: *const u32 = &42_u32;
2925 /// let mut_ptr: *mut u32 = &mut 42_u32;
2926 /// let _ = ptr as *const i32;
2927 /// let _ = mut_ptr as *mut i32;
2931 /// let ptr: *const u32 = &42_u32;
2932 /// let mut_ptr: *mut u32 = &mut 42_u32;
2933 /// let _ = ptr.cast::<i32>();
2934 /// let _ = mut_ptr.cast::<i32>();
2938 "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
2941 pub struct PtrAsPtr {
2942 msrv: Option<RustcVersion>,
2947 pub fn new(msrv: Option<RustcVersion>) -> Self {
2952 impl_lint_pass!(PtrAsPtr => [PTR_AS_PTR]);
2954 impl<'tcx> LateLintPass<'tcx> for PtrAsPtr {
2955 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2956 if !meets_msrv(self.msrv.as_ref(), &PTR_AS_PTR_MSRV) {
2960 if expr.span.from_expansion() {
2965 if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind;
2966 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr));
2967 if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind();
2968 if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind();
2969 if matches!((from_mutbl, to_mutbl),
2970 (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut));
2971 // The `U` in `pointer::cast` have to be `Sized`
2972 // as explained here: https://github.com/rust-lang/rust/issues/60602.
2973 if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env);
2975 let mut applicability = Applicability::MachineApplicable;
2976 let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability);
2977 let turbofish = match &cast_to_hir_ty.kind {
2978 TyKind::Infer => Cow::Borrowed(""),
2979 TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
2980 _ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
2986 "`as` casting between raw pointers without changing its mutability",
2987 "try `pointer::cast`, a safer alternative",
2988 format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
2995 extract_msrv_attr!(LateContext);