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 let TyKind::Path(QPath::Resolved(_, path)) = cast_to.kind {
1641 if let Res::Def(_, def_id) = path.res {
1642 if cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr) {
1647 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
1648 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1649 if let Some(lit) = get_numeric_literal(ex) {
1650 let literal_str = snippet_opt(cx, ex.span).unwrap_or_default();
1653 if let LitKind::Int(n, _) = lit.node;
1654 if let Some(src) = snippet_opt(cx, lit.span);
1655 if cast_to.is_floating_point();
1656 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1657 let from_nbits = 128 - n.leading_zeros();
1658 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1659 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1661 let literal_str = if is_unary_neg(ex) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
1662 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1668 LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
1669 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1671 LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
1672 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1674 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1676 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
1682 "casting to the same type is unnecessary (`{}` -> `{}`)",
1690 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1691 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1694 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1699 fn is_unary_neg(expr: &Expr<'_>) -> bool {
1700 matches!(expr.kind, ExprKind::Unary(UnOp::UnNeg, _))
1703 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
1705 ExprKind::Lit(ref lit) => Some(lit),
1706 ExprKind::Unary(UnOp::UnNeg, e) => {
1707 if let ExprKind::Lit(ref lit) = e.kind {
1717 fn show_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1718 let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
1723 &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
1725 format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
1726 Applicability::MachineApplicable,
1730 fn lint_numeric_casts<'tcx>(
1731 cx: &LateContext<'tcx>,
1733 cast_expr: &Expr<'_>,
1734 cast_from: Ty<'tcx>,
1737 match (cast_from.is_integral(), cast_to.is_integral()) {
1739 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1740 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
1745 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1746 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1748 if from_nbits < to_nbits {
1749 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1755 CAST_POSSIBLE_TRUNCATION,
1757 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1759 if !cast_to.is_signed() {
1765 "casting `{}` to `{}` may lose the sign of the value",
1772 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1773 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1774 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1777 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
1780 CAST_POSSIBLE_TRUNCATION,
1782 "casting `f64` to `f32` may truncate the value",
1785 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
1786 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1792 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1794 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
1795 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
1796 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1797 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1798 if from_layout.align.abi < to_layout.align.abi;
1799 // with c_void, we inherently need to trust the user
1800 if !is_c_void(cx, from_ptr_ty.ty);
1801 // when casting from a ZST, we don't know enough to properly lint
1802 if !from_layout.is_zst();
1809 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1812 from_layout.align.abi.bytes(),
1813 to_layout.align.abi.bytes(),
1820 fn lint_fn_to_numeric_cast(
1821 cx: &LateContext<'_>,
1823 cast_expr: &Expr<'_>,
1827 // We only want to check casts to `ty::Uint` or `ty::Int`
1828 match cast_to.kind() {
1829 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1832 match cast_from.kind() {
1833 ty::FnDef(..) | ty::FnPtr(_) => {
1834 let mut applicability = Applicability::MaybeIncorrect;
1835 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1837 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1838 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1841 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1844 "casting function pointer `{}` to `{}`, which truncates the value",
1845 from_snippet, cast_to
1848 format!("{} as usize", from_snippet),
1851 } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
1856 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1858 format!("{} as usize", from_snippet),
1867 declare_clippy_lint! {
1868 /// **What it does:** Checks for types used in structs, parameters and `let`
1869 /// declarations above a certain complexity threshold.
1871 /// **Why is this bad?** Too complex types make the code less readable. Consider
1872 /// using a `type` definition to simplify them.
1874 /// **Known problems:** None.
1878 /// # use std::rc::Rc;
1880 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1883 pub TYPE_COMPLEXITY,
1885 "usage of very complex types that might be better factored into `type` definitions"
1888 pub struct TypeComplexity {
1892 impl TypeComplexity {
1894 pub fn new(threshold: u64) -> Self {
1899 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1901 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
1904 cx: &LateContext<'tcx>,
1906 decl: &'tcx FnDecl<'_>,
1911 self.check_fndecl(cx, decl);
1914 fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
1915 // enum variants are also struct fields now
1916 self.check_type(cx, &field.ty);
1919 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1921 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1922 // functions, enums, structs, impls and traits are covered
1927 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1929 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1930 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1931 // methods with default impl are covered by check_fn
1936 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
1938 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1939 // methods are covered by check_fn
1944 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
1945 if let Some(ref ty) = local.ty {
1946 self.check_type(cx, ty);
1951 impl<'tcx> TypeComplexity {
1952 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
1953 for arg in decl.inputs {
1954 self.check_type(cx, arg);
1956 if let FnRetTy::Return(ref ty) = decl.output {
1957 self.check_type(cx, ty);
1961 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
1962 if ty.span.from_expansion() {
1966 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1967 visitor.visit_ty(ty);
1971 if score > self.threshold {
1976 "very complex type used. Consider factoring parts into `type` definitions",
1982 /// Walks a type and assigns a complexity score to it.
1983 struct TypeComplexityVisitor {
1984 /// total complexity score of the type
1986 /// current nesting level
1990 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1991 type Map = Map<'tcx>;
1993 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1994 let (add_score, sub_nest) = match ty.kind {
1995 // _, &x and *x have only small overhead; don't mess with nesting level
1996 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1998 // the "normal" components of a type: named types, arrays/tuples
1999 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
2001 // function types bring a lot of overhead
2002 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
2004 TyKind::TraitObject(ref param_bounds, _) => {
2005 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
2007 .bound_generic_params
2009 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
2011 if has_lifetime_parameters {
2012 // complex trait bounds like A<'a, 'b>
2015 // simple trait bounds like A + B
2022 self.score += add_score;
2023 self.nest += sub_nest;
2025 self.nest -= sub_nest;
2027 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2028 NestedVisitorMap::None
2032 declare_clippy_lint! {
2033 /// **What it does:** Checks for expressions where a character literal is cast
2034 /// to `u8` and suggests using a byte literal instead.
2036 /// **Why is this bad?** In general, casting values to smaller types is
2037 /// error-prone and should be avoided where possible. In the particular case of
2038 /// converting a character literal to u8, it is easy to avoid by just using a
2039 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
2040 /// than `'a' as u8`.
2042 /// **Known problems:** None.
2049 /// A better version, using the byte literal:
2056 "casting a character literal to `u8` truncates"
2059 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
2061 impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
2062 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2064 if !expr.span.from_expansion();
2065 if let ExprKind::Cast(e, _) = &expr.kind;
2066 if let ExprKind::Lit(l) = &e.kind;
2067 if let LitKind::Char(c) = l.node;
2068 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
2070 let mut applicability = Applicability::MachineApplicable;
2071 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
2077 "casting a character literal to `u8` truncates",
2079 diag.note("`char` is four bytes wide, but `u8` is a single byte");
2082 diag.span_suggestion(
2084 "use a byte literal instead",
2085 format!("b{}", snippet),
2095 declare_clippy_lint! {
2096 /// **What it does:** Checks for comparisons where one side of the relation is
2097 /// either the minimum or maximum value for its type and warns if it involves a
2098 /// case that is always true or always false. Only integer and boolean types are
2101 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
2102 /// that it is possible for `x` to be less than the minimum. Expressions like
2103 /// `max < x` are probably mistakes.
2105 /// **Known problems:** For `usize` the size of the current compile target will
2106 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
2107 /// a comparison to detect target pointer width will trigger this lint. One can
2108 /// use `mem::sizeof` and compare its value or conditional compilation
2110 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
2115 /// let vec: Vec<isize> = Vec::new();
2116 /// if vec.len() <= 0 {}
2117 /// if 100 > i32::MAX {}
2119 pub ABSURD_EXTREME_COMPARISONS,
2121 "a comparison with a maximum or minimum value that is always true or false"
2124 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
2131 struct ExtremeExpr<'a> {
2136 enum AbsurdComparisonResult {
2139 InequalityImpossible,
2142 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
2143 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2144 let precast_ty = cx.typeck_results().expr_ty(cast_exp);
2145 let cast_ty = cx.typeck_results().expr_ty(expr);
2147 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
2153 fn detect_absurd_comparison<'tcx>(
2154 cx: &LateContext<'tcx>,
2156 lhs: &'tcx Expr<'_>,
2157 rhs: &'tcx Expr<'_>,
2158 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
2159 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2160 use crate::types::ExtremeType::{Maximum, Minimum};
2161 use crate::utils::comparisons::{normalize_comparison, Rel};
2163 // absurd comparison only makes sense on primitive types
2164 // primitive types don't implement comparison operators with each other
2165 if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
2169 // comparisons between fix sized types and target sized types are considered unanalyzable
2170 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
2174 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
2176 let lx = detect_extreme_expr(cx, normalized_lhs);
2177 let rx = detect_extreme_expr(cx, normalized_rhs);
2182 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
2183 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
2189 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
2190 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
2191 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
2192 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
2196 Rel::Ne | Rel::Eq => return None,
2200 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
2201 use crate::types::ExtremeType::{Maximum, Minimum};
2203 let ty = cx.typeck_results().expr_ty(expr);
2205 let cv = constant(cx, cx.typeck_results(), expr)?.0;
2207 let which = match (ty.kind(), cv) {
2208 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
2209 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
2213 (&ty::Bool, Constant::Bool(true)) => Maximum,
2214 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
2217 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
2221 Some(ExtremeExpr { which, expr })
2224 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
2225 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2226 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2227 use crate::types::ExtremeType::{Maximum, Minimum};
2229 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2230 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
2231 if !expr.span.from_expansion() {
2232 let msg = "this comparison involving the minimum or maximum element for this \
2233 type contains a case that is always true or always false";
2235 let conclusion = match result {
2236 AlwaysFalse => "this comparison is always false".to_owned(),
2237 AlwaysTrue => "this comparison is always true".to_owned(),
2238 InequalityImpossible => format!(
2239 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
2241 snippet(cx, lhs.span, "lhs"),
2242 snippet(cx, rhs.span, "rhs")
2247 "because `{}` is the {} value for this type, {}",
2248 snippet(cx, culprit.expr.span, "x"),
2249 match culprit.which {
2250 Minimum => "minimum",
2251 Maximum => "maximum",
2256 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
2263 declare_clippy_lint! {
2264 /// **What it does:** Checks for comparisons where the relation is always either
2265 /// true or false, but where one side has been upcast so that the comparison is
2266 /// necessary. Only integer types are checked.
2268 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
2269 /// will mistakenly imply that it is possible for `x` to be outside the range of
2272 /// **Known problems:**
2273 /// https://github.com/rust-lang/rust-clippy/issues/886
2278 /// (x as u32) > 300;
2280 pub INVALID_UPCAST_COMPARISONS,
2282 "a comparison involving an upcast which is always true or false"
2285 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
2287 #[derive(Copy, Clone, Debug, Eq)]
2294 #[allow(clippy::cast_sign_loss)]
2296 fn cmp_s_u(s: i128, u: u128) -> Ordering {
2299 } else if u > (i128::MAX as u128) {
2307 impl PartialEq for FullInt {
2309 fn eq(&self, other: &Self) -> bool {
2310 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
2314 impl PartialOrd for FullInt {
2316 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2317 Some(match (self, other) {
2318 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
2319 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
2320 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
2321 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
2326 impl Ord for FullInt {
2328 fn cmp(&self, other: &Self) -> Ordering {
2329 self.partial_cmp(other)
2330 .expect("`partial_cmp` for FullInt can never return `None`")
2334 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
2335 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2336 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
2337 let cast_ty = cx.typeck_results().expr_ty(expr);
2338 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
2339 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
2342 match pre_cast_ty.kind() {
2343 ty::Int(int_ty) => Some(match int_ty {
2344 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
2345 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
2346 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
2347 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
2348 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
2349 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
2351 ty::Uint(uint_ty) => Some(match uint_ty {
2352 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
2353 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
2354 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
2355 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
2356 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
2357 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
2366 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2367 let val = constant(cx, cx.typeck_results(), expr)?.0;
2368 if let Constant::Int(const_int) = val {
2369 match *cx.typeck_results().expr_ty(expr).kind() {
2370 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2371 ty::Uint(_) => Some(FullInt::U(const_int)),
2379 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
2380 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2383 INVALID_UPCAST_COMPARISONS,
2386 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2387 snippet(cx, cast_val.span, "the expression"),
2388 if always { "true" } else { "false" },
2394 fn upcast_comparison_bounds_err<'tcx>(
2395 cx: &LateContext<'tcx>,
2397 rel: comparisons::Rel,
2398 lhs_bounds: Option<(FullInt, FullInt)>,
2399 lhs: &'tcx Expr<'_>,
2400 rhs: &'tcx Expr<'_>,
2403 use crate::utils::comparisons::Rel;
2405 if let Some((lb, ub)) = lhs_bounds {
2406 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2407 if rel == Rel::Eq || rel == Rel::Ne {
2408 if norm_rhs_val < lb || norm_rhs_val > ub {
2409 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2411 } else if match rel {
2426 Rel::Eq | Rel::Ne => unreachable!(),
2428 err_upcast_comparison(cx, span, lhs, true)
2429 } else if match rel {
2444 Rel::Eq | Rel::Ne => unreachable!(),
2446 err_upcast_comparison(cx, span, lhs, false)
2452 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
2453 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2454 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2455 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2456 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2462 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2463 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2465 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2466 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2471 declare_clippy_lint! {
2472 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2473 /// over different hashers and implicitly defaulting to the default hashing
2474 /// algorithm (`SipHash`).
2476 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2479 /// **Known problems:** Suggestions for replacing constructors can contain
2480 /// false-positives. Also applying suggestions can require modification of other
2481 /// pieces of code, possibly including external crates.
2485 /// # use std::collections::HashMap;
2486 /// # use std::hash::{Hash, BuildHasher};
2487 /// # trait Serialize {};
2488 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2490 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2492 /// could be rewritten as
2494 /// # use std::collections::HashMap;
2495 /// # use std::hash::{Hash, BuildHasher};
2496 /// # trait Serialize {};
2497 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2499 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2501 pub IMPLICIT_HASHER,
2503 "missing generalization over different hashers"
2506 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2508 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
2509 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2510 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
2511 use rustc_span::BytePos;
2513 fn suggestion<'tcx>(
2514 cx: &LateContext<'tcx>,
2515 diag: &mut DiagnosticBuilder<'_>,
2516 generics_span: Span,
2517 generics_suggestion_span: Span,
2518 target: &ImplicitHasherType<'_>,
2519 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2521 let generics_snip = snippet(cx, generics_span, "");
2523 let generics_snip = if generics_snip.is_empty() {
2526 &generics_snip[1..generics_snip.len() - 1]
2531 "consider adding a type parameter",
2534 generics_suggestion_span,
2536 "<{}{}S: ::std::hash::BuildHasher{}>",
2538 if generics_snip.is_empty() { "" } else { ", " },
2539 if vis.suggestions.is_empty() {
2542 // request users to add `Default` bound so that generic constructors can be used
2549 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2554 if !vis.suggestions.is_empty() {
2555 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
2559 if !cx.access_levels.is_exported(item.hir_id) {
2570 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2573 for target in &vis.found {
2574 if differing_macro_contexts(item.span, target.span()) {
2578 let generics_suggestion_span = generics.span.substitute_dummy({
2579 let pos = snippet_opt(cx, item.span.until(target.span()))
2580 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2581 if let Some(pos) = pos {
2582 Span::new(pos, pos, item.span.data().ctxt)
2588 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2589 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2590 ctr_vis.visit_impl_item(item);
2598 "impl for `{}` should be generalized over different hashers",
2602 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2607 ItemKind::Fn(ref sig, ref generics, body_id) => {
2608 let body = cx.tcx.hir().body(body_id);
2610 for ty in sig.decl.inputs {
2611 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2614 for target in &vis.found {
2615 if in_external_macro(cx.sess(), generics.span) {
2618 let generics_suggestion_span = generics.span.substitute_dummy({
2619 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2621 let i = snip.find("fn")?;
2622 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2624 .expect("failed to create span for type parameters");
2625 Span::new(pos, pos, item.span.data().ctxt)
2628 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2629 ctr_vis.visit_body(body);
2636 "parameter of type `{}` should be generalized over different hashers",
2640 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2651 enum ImplicitHasherType<'tcx> {
2652 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2653 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2656 impl<'tcx> ImplicitHasherType<'tcx> {
2657 /// Checks that `ty` is a target type without a `BuildHasher`.
2658 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2659 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2660 let params: Vec<_> = path
2668 .filter_map(|arg| match arg {
2669 GenericArg::Type(ty) => Some(ty),
2673 let params_len = params.len();
2675 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2677 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2678 Some(ImplicitHasherType::HashMap(
2681 snippet(cx, params[0].span, "K"),
2682 snippet(cx, params[1].span, "V"),
2684 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2685 Some(ImplicitHasherType::HashSet(
2688 snippet(cx, params[0].span, "T"),
2698 fn type_name(&self) -> &'static str {
2700 ImplicitHasherType::HashMap(..) => "HashMap",
2701 ImplicitHasherType::HashSet(..) => "HashSet",
2705 fn type_arguments(&self) -> String {
2707 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2708 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2712 fn ty(&self) -> Ty<'tcx> {
2714 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2718 fn span(&self) -> Span {
2720 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2725 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2726 cx: &'a LateContext<'tcx>,
2727 found: Vec<ImplicitHasherType<'tcx>>,
2730 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2731 fn new(cx: &'a LateContext<'tcx>) -> Self {
2732 Self { cx, found: vec![] }
2736 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2737 type Map = Map<'tcx>;
2739 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2740 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2741 self.found.push(target);
2747 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2748 NestedVisitorMap::None
2752 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2753 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2754 cx: &'a LateContext<'tcx>,
2755 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
2756 target: &'b ImplicitHasherType<'tcx>,
2757 suggestions: BTreeMap<Span, String>,
2760 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2761 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2764 maybe_typeck_results: cx.maybe_typeck_results(),
2766 suggestions: BTreeMap::new(),
2771 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2772 type Map = Map<'tcx>;
2774 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2775 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
2776 walk_body(self, body);
2777 self.maybe_typeck_results = old_maybe_typeck_results;
2780 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2782 if let ExprKind::Call(ref fun, ref args) = e.kind;
2783 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2784 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2786 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
2790 if match_path(ty_path, &paths::HASHMAP) {
2791 if method.ident.name == sym::new {
2793 .insert(e.span, "HashMap::default()".to_string());
2794 } else if method.ident.name == sym!(with_capacity) {
2795 self.suggestions.insert(
2798 "HashMap::with_capacity_and_hasher({}, Default::default())",
2799 snippet(self.cx, args[0].span, "capacity"),
2803 } else if match_path(ty_path, &paths::HASHSET) {
2804 if method.ident.name == sym::new {
2806 .insert(e.span, "HashSet::default()".to_string());
2807 } else if method.ident.name == sym!(with_capacity) {
2808 self.suggestions.insert(
2811 "HashSet::with_capacity_and_hasher({}, Default::default())",
2812 snippet(self.cx, args[0].span, "capacity"),
2823 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2824 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2828 declare_clippy_lint! {
2829 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2831 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2832 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2835 /// **Known problems:** None.
2841 /// *(r as *const _ as *mut _) += 1;
2846 /// Instead consider using interior mutability types.
2849 /// use std::cell::UnsafeCell;
2851 /// fn x(r: &UnsafeCell<i32>) {
2857 pub CAST_REF_TO_MUT,
2859 "a cast of reference to a mutable pointer"
2862 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2864 impl<'tcx> LateLintPass<'tcx> for RefToMut {
2865 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2867 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2868 if let ExprKind::Cast(e, t) = &e.kind;
2869 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2870 if let ExprKind::Cast(e, t) = &e.kind;
2871 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2872 if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
2878 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",
2885 const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0);
2887 declare_clippy_lint! {
2888 /// **What it does:**
2889 /// Checks for `as` casts between raw pointers without changing its mutability,
2890 /// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
2892 /// **Why is this bad?**
2893 /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
2894 /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
2896 /// **Known problems:** None.
2901 /// let ptr: *const u32 = &42_u32;
2902 /// let mut_ptr: *mut u32 = &mut 42_u32;
2903 /// let _ = ptr as *const i32;
2904 /// let _ = mut_ptr as *mut i32;
2908 /// let ptr: *const u32 = &42_u32;
2909 /// let mut_ptr: *mut u32 = &mut 42_u32;
2910 /// let _ = ptr.cast::<i32>();
2911 /// let _ = mut_ptr.cast::<i32>();
2915 "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
2918 pub struct PtrAsPtr {
2919 msrv: Option<RustcVersion>,
2924 pub fn new(msrv: Option<RustcVersion>) -> Self {
2929 impl_lint_pass!(PtrAsPtr => [PTR_AS_PTR]);
2931 impl<'tcx> LateLintPass<'tcx> for PtrAsPtr {
2932 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2933 if !meets_msrv(self.msrv.as_ref(), &PTR_AS_PTR_MSRV) {
2937 if expr.span.from_expansion() {
2942 if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind;
2943 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr));
2944 if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind();
2945 if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind();
2946 if matches!((from_mutbl, to_mutbl),
2947 (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut));
2948 // The `U` in `pointer::cast` have to be `Sized`
2949 // as explained here: https://github.com/rust-lang/rust/issues/60602.
2950 if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env);
2952 let mut applicability = Applicability::MachineApplicable;
2953 let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability);
2954 let turbofish = match &cast_to_hir_ty.kind {
2955 TyKind::Infer => Cow::Borrowed(""),
2956 TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
2957 _ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
2963 "`as` casting between raw pointers without changing its mutability",
2964 "try `pointer::cast`, a safer alternative",
2965 format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
2972 extract_msrv_attr!(LateContext);