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::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
13 BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericBounds, GenericParamKind, HirId,
14 ImplItem, ImplItemKind, Item, ItemKind, Lifetime, Lit, Local, MatchSource, MutTy, Mutability, Node, QPath, Stmt,
15 StmtKind, SyntheticTyParamKind, TraitFn, TraitItem, TraitItemKind, TyKind, UnOp,
17 use rustc_lint::{LateContext, LateLintPass, LintContext};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::lint::in_external_macro;
20 use rustc_middle::ty::TypeFoldable;
21 use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeAndMut, TypeckResults};
22 use rustc_semver::RustcVersion;
23 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
24 use rustc_span::hygiene::{ExpnKind, MacroKind};
25 use rustc_span::source_map::Span;
26 use rustc_span::symbol::sym;
27 use rustc_target::abi::LayoutOf;
28 use rustc_target::spec::abi::Abi;
29 use rustc_typeck::hir_ty_to_ty;
31 use crate::consts::{constant, Constant};
32 use crate::utils::paths;
33 use crate::utils::sugg::Sugg;
35 clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_hir_ty_cfg_dependant,
36 is_type_diagnostic_item, last_path_segment, match_def_path, match_path, meets_msrv, method_chain_args,
37 multispan_sugg, numeric_literal::NumericLiteral, qpath_res, reindent_multiline, sext, snippet, snippet_opt,
38 snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg,
39 span_lint_and_then, unsext,
42 declare_clippy_lint! {
43 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
44 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
46 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
47 /// the heap. So if you `Box` it, you just add another level of indirection
48 /// without any benefit whatsoever.
50 /// **Known problems:** None.
55 /// values: Box<Vec<Foo>>,
68 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
71 declare_clippy_lint! {
72 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
73 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
75 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
76 /// the heap. So if you `Box` its contents, you just add another level of indirection.
78 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see [#3530](https://github.com/rust-lang/rust-clippy/issues/3530),
84 /// values: Vec<Box<i32>>,
97 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
100 declare_clippy_lint! {
101 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
104 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
105 /// represents an optional optional value which is logically the same thing as an optional
106 /// value but has an unneeded extra level of wrapping.
108 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
109 /// consider a custom `enum` instead, with clear names for each case.
111 /// **Known problems:** None.
115 /// fn get_data() -> Option<Option<u32>> {
123 /// pub enum Contents {
124 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
125 /// NotYetFetched, // Was Some(None)
126 /// None, // Was None
129 /// fn get_data() -> Contents {
135 "usage of `Option<Option<T>>`"
138 declare_clippy_lint! {
139 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
140 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
142 /// **Why is this bad?** Gankro says:
144 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
145 /// pointers and indirection.
146 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
148 /// > "only" amortized for push/pop, should be faster in the general case for
149 /// almost every possible
150 /// > workload, and isn't even amortized at all if you can predict the capacity
153 /// > `LinkedList`s are only really good if you're doing a lot of merging or
154 /// splitting of lists.
155 /// > This is because they can just mangle some pointers instead of actually
156 /// copying the data. Even
157 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
158 /// can still be better
159 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
161 /// **Known problems:** False positives – the instances where using a
162 /// `LinkedList` makes sense are few and far between, but they can still happen.
166 /// # use std::collections::LinkedList;
167 /// let x: LinkedList<usize> = LinkedList::new();
171 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
174 declare_clippy_lint! {
175 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
176 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
178 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
181 /// **Known problems:** None.
185 /// fn foo(bar: &Box<T>) { ... }
191 /// fn foo(bar: &T) { ... }
195 "a borrow of a boxed type"
198 declare_clippy_lint! {
199 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
201 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
202 /// add an unnecessary level of indirection.
204 /// **Known problems:** None.
208 /// # use std::rc::Rc;
209 /// fn foo(bar: Rc<&usize>) {}
215 /// fn foo(bar: &usize) {}
217 pub REDUNDANT_ALLOCATION,
219 "redundant allocation"
222 declare_clippy_lint! {
223 /// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
225 /// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
226 /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
228 /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
229 /// works if there are no additional references yet, which usually defeats the purpose of
230 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
231 /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
234 /// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
235 /// cases where mutation only happens before there are any additional references.
239 /// # use std::rc::Rc;
240 /// fn foo(interned: Rc<String>) { ... }
246 /// fn foo(interned: Rc<str>) { ... }
250 "shared ownership of a buffer type"
254 vec_box_size_threshold: u64,
257 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
259 impl<'tcx> LateLintPass<'tcx> for Types {
260 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
261 // Skip trait implementations; see issue #605.
262 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
263 if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
268 self.check_fn_decl(cx, decl);
271 fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) {
272 self.check_ty(cx, &field.ty, false);
275 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
277 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
278 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
283 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
284 if let Some(ref ty) = local.ty {
285 self.check_ty(cx, ty, true);
290 /// Checks if `qpath` has last segment with type parameter matching `path`
291 fn match_type_parameter(cx: &LateContext<'_>, qpath: &QPath<'_>, path: &[&str]) -> Option<Span> {
292 let last = last_path_segment(qpath);
294 if let Some(ref params) = last.args;
295 if !params.parenthesized;
296 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
297 GenericArg::Type(ty) => Some(ty),
300 if let TyKind::Path(ref qpath) = ty.kind;
301 if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
302 if match_def_path(cx, did, path);
304 return Some(ty.span);
310 fn match_buffer_type(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<&'static str> {
311 if match_type_parameter(cx, qpath, &paths::STRING).is_some() {
314 if match_type_parameter(cx, qpath, &paths::OS_STRING).is_some() {
315 return Some("std::ffi::OsStr");
317 if match_type_parameter(cx, qpath, &paths::PATH_BUF).is_some() {
318 return Some("std::path::Path");
323 fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<Span> {
324 let last = last_path_segment(qpath);
326 if let Some(ref params) = last.args;
327 if !params.parenthesized;
328 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
329 GenericArg::Type(ty) => Some(ty),
332 if let TyKind::Rptr(..) = ty.kind;
334 return Some(ty.span);
341 pub fn new(vec_box_size_threshold: u64) -> Self {
342 Self { vec_box_size_threshold }
345 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
346 for input in decl.inputs {
347 self.check_ty(cx, input, false);
350 if let FnRetTy::Return(ref ty) = decl.output {
351 self.check_ty(cx, ty, false);
355 /// Recursively check for `TypePass` lints in the given type. Stop at the first
358 /// The parameter `is_local` distinguishes the context of the type; types from
359 /// local bindings should only be checked for the `BORROWED_BOX` lint.
360 #[allow(clippy::too_many_lines)]
361 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
362 if hir_ty.span.from_expansion() {
366 TyKind::Path(ref qpath) if !is_local => {
367 let hir_id = hir_ty.hir_id;
368 let res = qpath_res(cx, qpath, hir_id);
369 if let Some(def_id) = res.opt_def_id() {
370 if Some(def_id) == cx.tcx.lang_items().owned_box() {
371 if let Some(span) = match_borrows_parameter(cx, qpath) {
372 let mut applicability = Applicability::MachineApplicable;
375 REDUNDANT_ALLOCATION,
377 "usage of `Box<&T>`",
379 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
382 return; // don't recurse into the type
384 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
389 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
391 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
393 return; // don't recurse into the type
395 } else if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
396 if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) {
397 let mut applicability = Applicability::MachineApplicable;
400 REDUNDANT_ALLOCATION,
402 "usage of `Rc<Rc<T>>`",
404 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
407 return; // don't recurse into the type
409 if match_type_parameter(cx, qpath, &paths::BOX).is_some() {
410 let box_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
411 GenericArg::Type(ty) => match &ty.kind {
412 TyKind::Path(qpath) => qpath,
417 let inner_span = match &last_path_segment(&box_ty).args.unwrap().args[0] {
418 GenericArg::Type(ty) => ty.span,
421 let mut applicability = Applicability::MachineApplicable;
424 REDUNDANT_ALLOCATION,
426 "usage of `Rc<Box<T>>`",
430 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
434 return; // don't recurse into the type
436 if let Some(alternate) = match_buffer_type(cx, qpath) {
441 "usage of `Rc<T>` when T is a buffer type",
443 format!("Rc<{}>", alternate),
444 Applicability::MachineApplicable,
446 return; // don't recurse into the type
448 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
449 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
450 GenericArg::Type(ty) => match &ty.kind {
451 TyKind::Path(qpath) => qpath,
456 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
457 GenericArg::Type(ty) => ty.span,
460 let mut applicability = Applicability::MachineApplicable;
465 "usage of `Rc<T>` when T is a buffer type",
469 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
471 Applicability::MachineApplicable,
473 return; // don't recurse into the type
475 if let Some(span) = match_borrows_parameter(cx, qpath) {
476 let mut applicability = Applicability::MachineApplicable;
479 REDUNDANT_ALLOCATION,
483 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
486 return; // don't recurse into the type
488 } else if cx.tcx.is_diagnostic_item(sym::Arc, def_id) {
489 if let Some(alternate) = match_buffer_type(cx, qpath) {
494 "usage of `Arc<T>` when T is a buffer type",
496 format!("Arc<{}>", alternate),
497 Applicability::MachineApplicable,
499 return; // don't recurse into the type
501 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
502 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
503 GenericArg::Type(ty) => match &ty.kind {
504 TyKind::Path(qpath) => qpath,
509 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
510 GenericArg::Type(ty) => ty.span,
513 let mut applicability = Applicability::MachineApplicable;
518 "usage of `Arc<T>` when T is a buffer type",
522 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
524 Applicability::MachineApplicable,
526 return; // don't recurse into the type
528 } else if cx.tcx.is_diagnostic_item(sym::vec_type, def_id) {
530 // Get the _ part of Vec<_>
531 if let Some(ref last) = last_path_segment(qpath).args;
532 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
533 GenericArg::Type(ty) => Some(ty),
536 // ty is now _ at this point
537 if let TyKind::Path(ref ty_qpath) = ty.kind;
538 let res = qpath_res(cx, ty_qpath, ty.hir_id);
539 if let Some(def_id) = res.opt_def_id();
540 if Some(def_id) == cx.tcx.lang_items().owned_box();
541 // At this point, we know ty is Box<T>, now get T
542 if let Some(ref last) = last_path_segment(ty_qpath).args;
543 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
544 GenericArg::Type(ty) => Some(ty),
547 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
548 if !ty_ty.has_escaping_bound_vars();
549 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env);
550 if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes());
551 if ty_ty_size <= self.vec_box_size_threshold;
557 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
559 format!("Vec<{}>", snippet(cx, boxed_ty.span, "..")),
560 Applicability::MachineApplicable,
562 return; // don't recurse into the type
565 } else if cx.tcx.is_diagnostic_item(sym::option_type, def_id) {
566 if match_type_parameter(cx, qpath, &paths::OPTION).is_some() {
571 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
572 enum if you need to distinguish all 3 cases",
574 return; // don't recurse into the type
576 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
581 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
583 "a `VecDeque` might work",
585 return; // don't recurse into the type
589 QPath::Resolved(Some(ref ty), ref p) => {
590 self.check_ty(cx, ty, is_local);
591 for ty in p.segments.iter().flat_map(|seg| {
594 .map_or_else(|| [].iter(), |params| params.args.iter())
595 .filter_map(|arg| match arg {
596 GenericArg::Type(ty) => Some(ty),
600 self.check_ty(cx, ty, is_local);
603 QPath::Resolved(None, ref p) => {
604 for ty in p.segments.iter().flat_map(|seg| {
607 .map_or_else(|| [].iter(), |params| params.args.iter())
608 .filter_map(|arg| match arg {
609 GenericArg::Type(ty) => Some(ty),
613 self.check_ty(cx, ty, is_local);
616 QPath::TypeRelative(ref ty, ref seg) => {
617 self.check_ty(cx, ty, is_local);
618 if let Some(ref params) = seg.args {
619 for ty in params.args.iter().filter_map(|arg| match arg {
620 GenericArg::Type(ty) => Some(ty),
623 self.check_ty(cx, ty, is_local);
627 QPath::LangItem(..) => {},
630 TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
632 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
633 self.check_ty(cx, ty, is_local)
635 TyKind::Tup(tys) => {
637 self.check_ty(cx, ty, is_local);
646 cx: &LateContext<'_>,
647 hir_ty: &hir::Ty<'_>,
652 match mut_ty.ty.kind {
653 TyKind::Path(ref qpath) => {
654 let hir_id = mut_ty.ty.hir_id;
655 let def = qpath_res(cx, qpath, hir_id);
657 if let Some(def_id) = def.opt_def_id();
658 if Some(def_id) == cx.tcx.lang_items().owned_box();
659 if let QPath::Resolved(None, ref path) = *qpath;
660 if let [ref bx] = *path.segments;
661 if let Some(ref params) = bx.args;
662 if !params.parenthesized;
663 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
664 GenericArg::Type(ty) => Some(ty),
668 if is_any_trait(inner) {
669 // Ignore `Box<Any>` types; see issue #1884 for details.
673 let ltopt = if lt.is_elided() {
676 format!("{} ", lt.name.ident().as_str())
679 if mut_ty.mutbl == Mutability::Mut {
680 // Ignore `&mut Box<T>` types; see issue #2907 for
685 // When trait objects or opaque types have lifetime or auto-trait bounds,
686 // we need to add parentheses to avoid a syntax error due to its ambiguity.
687 // Originally reported as the issue #3128.
688 let inner_snippet = snippet(cx, inner.span, "..");
689 let suggestion = match &inner.kind {
690 TyKind::TraitObject(bounds, lt_bound) if bounds.len() > 1 || !lt_bound.is_elided() => {
691 format!("&{}({})", ltopt, &inner_snippet)
694 if get_bounds_if_impl_trait(cx, qpath, inner.hir_id)
695 .map_or(false, |bounds| bounds.len() > 1) =>
697 format!("&{}({})", ltopt, &inner_snippet)
699 _ => format!("&{}{}", ltopt, &inner_snippet),
705 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
708 // To make this `MachineApplicable`, at least one needs to check if it isn't a trait item
709 // because the trait impls of it will break otherwise;
710 // and there may be other cases that result in invalid code.
711 // For example, type coercion doesn't work nicely.
712 Applicability::Unspecified,
714 return; // don't recurse into the type
717 self.check_ty(cx, &mut_ty.ty, is_local);
719 _ => self.check_ty(cx, &mut_ty.ty, is_local),
724 // Returns true if given type is `Any` trait.
725 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
727 if let TyKind::TraitObject(ref traits, _) = t.kind;
728 if !traits.is_empty();
729 // Only Send/Sync can be used as additional traits, so it is enough to
730 // check only the first trait.
731 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
740 fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: HirId) -> Option<GenericBounds<'tcx>> {
742 if let Some(did) = qpath_res(cx, qpath, id).opt_def_id();
743 if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did);
744 if let GenericParamKind::Type { synthetic, .. } = generic_param.kind;
745 if synthetic == Some(SyntheticTyParamKind::ImplTrait);
747 Some(generic_param.bounds)
754 declare_clippy_lint! {
755 /// **What it does:** Checks for binding a unit value.
757 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
758 /// binding one is kind of pointless.
760 /// **Known problems:** None.
770 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
773 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
775 impl<'tcx> LateLintPass<'tcx> for LetUnitValue {
776 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
777 if let StmtKind::Local(ref local) = stmt.kind {
778 if is_unit(cx.typeck_results().pat_ty(&local.pat)) {
779 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
782 if higher::is_from_for_desugar(local) {
789 "this let-binding has unit value",
791 if let Some(expr) = &local.init {
792 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
793 diag.span_suggestion(
795 "omit the `let` binding",
796 format!("{};", snip),
797 Applicability::MachineApplicable, // snippet
807 declare_clippy_lint! {
808 /// **What it does:** Checks for comparisons to unit. This includes all binary
809 /// comparisons (like `==` and `<`) and asserts.
811 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
812 /// clumsily written constant. Mostly this happens when someone accidentally
813 /// adds semicolons at the end of the operands.
815 /// **Known problems:** None.
846 /// assert_eq!({ foo(); }, { bar(); });
848 /// will always succeed
851 "comparing unit values"
854 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
856 impl<'tcx> LateLintPass<'tcx> for UnitCmp {
857 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
858 if expr.span.from_expansion() {
859 if let Some(callee) = expr.span.source_callee() {
860 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
861 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
863 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
864 let result = match &*symbol.as_str() {
865 "assert_eq" | "debug_assert_eq" => "succeed",
866 "assert_ne" | "debug_assert_ne" => "fail",
874 "`{}` of unit values detected. This will always {}",
885 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
887 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
888 let result = match op {
889 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
897 "{}-comparison of unit values detected. This will always be {}",
907 declare_clippy_lint! {
908 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
909 /// unit literal (`()`).
911 /// **Why is this bad?** This is likely the result of an accidental semicolon.
913 /// **Known problems:** None.
924 "passing unit to a function"
927 declare_lint_pass!(UnitArg => [UNIT_ARG]);
929 impl<'tcx> LateLintPass<'tcx> for UnitArg {
930 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
931 if expr.span.from_expansion() {
935 // apparently stuff in the desugaring of `?` can trigger this
936 // so check for that here
937 // only the calls to `Try::from_error` is marked as desugared,
938 // so we need to check both the current Expr and its parent.
939 if is_questionmark_desugar_marked_call(expr) {
943 let map = &cx.tcx.hir();
944 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
945 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
946 if is_questionmark_desugar_marked_call(parent_expr);
953 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => {
954 let args_to_recover = args
957 if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) {
960 ExprKind::Match(.., MatchSource::TryDesugar) | ExprKind::Path(..)
966 .collect::<Vec<_>>();
967 if !args_to_recover.is_empty() {
968 lint_unit_args(cx, expr, &args_to_recover);
976 fn fmt_stmts_and_call(
977 cx: &LateContext<'_>,
978 call_expr: &Expr<'_>,
980 args_snippets: &[impl AsRef<str>],
981 non_empty_block_args_snippets: &[impl AsRef<str>],
983 let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
984 let call_snippet_with_replacements = args_snippets
986 .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
988 let mut stmts_and_call = non_empty_block_args_snippets
990 .map(|it| it.as_ref().to_owned())
991 .collect::<Vec<_>>();
992 stmts_and_call.push(call_snippet_with_replacements);
993 stmts_and_call = stmts_and_call
995 .map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
998 let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
999 // expr is not in a block statement or result expression position, wrap in a block
1000 let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
1001 if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
1002 let block_indent = call_expr_indent + 4;
1003 stmts_and_call_snippet =
1004 reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
1005 stmts_and_call_snippet = format!(
1007 " ".repeat(block_indent),
1008 &stmts_and_call_snippet,
1009 " ".repeat(call_expr_indent)
1012 stmts_and_call_snippet
1015 fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
1016 let mut applicability = Applicability::MachineApplicable;
1017 let (singular, plural) = if args_to_recover.len() > 1 {
1026 &format!("passing {}unit value{} to a function", singular, plural),
1033 if let ExprKind::Block(block, _) = arg.kind;
1034 if block.expr.is_none();
1035 if let Some(last_stmt) = block.stmts.iter().last();
1036 if let StmtKind::Semi(last_expr) = last_stmt.kind;
1037 if let Some(snip) = snippet_opt(cx, last_expr.span);
1049 .for_each(|(span, sugg)| {
1052 "remove the semicolon from the last statement in the block",
1054 Applicability::MaybeIncorrect,
1057 applicability = Applicability::MaybeIncorrect;
1060 let arg_snippets: Vec<String> = args_to_recover
1062 .filter_map(|arg| snippet_opt(cx, arg.span))
1064 let arg_snippets_without_empty_blocks: Vec<String> = args_to_recover
1066 .filter(|arg| !is_empty_block(arg))
1067 .filter_map(|arg| snippet_opt(cx, arg.span))
1070 if let Some(call_snippet) = snippet_opt(cx, expr.span) {
1071 let sugg = fmt_stmts_and_call(
1076 &arg_snippets_without_empty_blocks,
1079 if arg_snippets_without_empty_blocks.is_empty() {
1080 db.multipart_suggestion(
1081 &format!("use {}unit literal{} instead", singular, plural),
1084 .map(|arg| (arg.span, "()".to_string()))
1085 .collect::<Vec<_>>(),
1089 let plural = arg_snippets_without_empty_blocks.len() > 1;
1090 let empty_or_s = if plural { "s" } else { "" };
1091 let it_or_them = if plural { "them" } else { "it" };
1095 "{}move the expression{} in front of the call and replace {} with the unit literal `()`",
1096 or, empty_or_s, it_or_them
1107 fn is_empty_block(expr: &Expr<'_>) -> bool {
1121 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
1122 use rustc_span::hygiene::DesugaringKind;
1123 if let ExprKind::Call(ref callee, _) = expr.kind {
1124 callee.span.is_desugaring(DesugaringKind::QuestionMark)
1130 fn is_unit(ty: Ty<'_>) -> bool {
1131 matches!(ty.kind(), ty::Tuple(slice) if slice.is_empty())
1134 fn is_unit_literal(expr: &Expr<'_>) -> bool {
1135 matches!(expr.kind, ExprKind::Tup(ref slice) if slice.is_empty())
1138 declare_clippy_lint! {
1139 /// **What it does:** Checks for casts from any numerical to a float type where
1140 /// the receiving type cannot store all values from the original type without
1141 /// rounding errors. This possible rounding is to be expected, so this lint is
1142 /// `Allow` by default.
1144 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
1145 /// or any 64-bit integer to `f64`.
1147 /// **Why is this bad?** It's not bad at all. But in some applications it can be
1148 /// helpful to know where precision loss can take place. This lint can help find
1149 /// those places in the code.
1151 /// **Known problems:** None.
1155 /// let x = u64::MAX;
1158 pub CAST_PRECISION_LOSS,
1160 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
1163 declare_clippy_lint! {
1164 /// **What it does:** Checks for casts from a signed to an unsigned numerical
1165 /// type. In this case, negative values wrap around to large positive values,
1166 /// which can be quite surprising in practice. However, as the cast works as
1167 /// defined, this lint is `Allow` by default.
1169 /// **Why is this bad?** Possibly surprising results. You can activate this lint
1170 /// as a one-time check to see where numerical wrapping can arise.
1172 /// **Known problems:** None.
1177 /// y as u128; // will return 18446744073709551615
1181 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
1184 declare_clippy_lint! {
1185 /// **What it does:** Checks for casts between numerical types that may
1186 /// truncate large values. This is expected behavior, so the cast is `Allow` by
1189 /// **Why is this bad?** In some problem domains, it is good practice to avoid
1190 /// truncation. This lint can be activated to help assess where additional
1191 /// checks could be beneficial.
1193 /// **Known problems:** None.
1197 /// fn as_u8(x: u64) -> u8 {
1201 pub CAST_POSSIBLE_TRUNCATION,
1203 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
1206 declare_clippy_lint! {
1207 /// **What it does:** Checks for casts from an unsigned type to a signed type of
1208 /// the same size. Performing such a cast is a 'no-op' for the compiler,
1209 /// i.e., nothing is changed at the bit level, and the binary representation of
1210 /// the value is reinterpreted. This can cause wrapping if the value is too big
1211 /// for the target signed type. However, the cast works as defined, so this lint
1212 /// is `Allow` by default.
1214 /// **Why is this bad?** While such a cast is not bad in itself, the results can
1215 /// be surprising when this is not the intended behavior, as demonstrated by the
1218 /// **Known problems:** None.
1222 /// u32::MAX as i32; // will yield a value of `-1`
1224 pub CAST_POSSIBLE_WRAP,
1226 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
1229 declare_clippy_lint! {
1230 /// **What it does:** Checks for casts between numerical types that may
1231 /// be replaced by safe conversion functions.
1233 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
1234 /// conversions, including silently lossy conversions. Conversion functions such
1235 /// as `i32::from` will only perform lossless conversions. Using the conversion
1236 /// functions prevents conversions from turning into silent lossy conversions if
1237 /// the types of the input expressions ever change, and make it easier for
1238 /// people reading the code to know that the conversion is lossless.
1240 /// **Known problems:** None.
1244 /// fn as_u64(x: u8) -> u64 {
1249 /// Using `::from` would look like this:
1252 /// fn as_u64(x: u8) -> u64 {
1258 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
1261 declare_clippy_lint! {
1262 /// **What it does:** Checks for casts to the same type, casts of int literals to integer types
1263 /// and casts of float literals to float types.
1265 /// **Why is this bad?** It's just unnecessary.
1267 /// **Known problems:** None.
1271 /// let _ = 2i32 as i32;
1272 /// let _ = 0.5 as f32;
1279 /// let _ = 0.5_f32;
1281 pub UNNECESSARY_CAST,
1283 "cast to the same type, e.g., `x as i32` where `x: i32`"
1286 declare_clippy_lint! {
1287 /// **What it does:** Checks for casts, using `as` or `pointer::cast`,
1288 /// from a less-strictly-aligned pointer to a more-strictly-aligned pointer
1290 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
1293 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
1294 /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
1295 /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
1299 /// let _ = (&1u8 as *const u8) as *const u16;
1300 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
1302 /// (&1u8 as *const u8).cast::<u16>();
1303 /// (&mut 1u8 as *mut u8).cast::<u16>();
1305 pub CAST_PTR_ALIGNMENT,
1307 "cast from a pointer to a more-strictly-aligned pointer"
1310 declare_clippy_lint! {
1311 /// **What it does:** Checks for casts of function pointers to something other than usize
1313 /// **Why is this bad?**
1314 /// Casting a function pointer to anything other than usize/isize is not portable across
1315 /// architectures, because you end up losing bits if the target type is too small or end up with a
1316 /// bunch of extra bits that waste space and add more instructions to the final binary than
1317 /// strictly necessary for the problem
1319 /// Casting to isize also doesn't make sense since there are no signed addresses.
1325 /// fn fun() -> i32 { 1 }
1326 /// let a = fun as i64;
1329 /// fn fun2() -> i32 { 1 }
1330 /// let a = fun2 as usize;
1332 pub FN_TO_NUMERIC_CAST,
1334 "casting a function pointer to a numeric type other than usize"
1337 declare_clippy_lint! {
1338 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1341 /// **Why is this bad?**
1342 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1343 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1344 /// a comment) to perform the truncation.
1350 /// fn fn1() -> i16 {
1353 /// let _ = fn1 as i32;
1355 /// // Better: Cast to usize first, then comment with the reason for the truncation
1356 /// fn fn2() -> i16 {
1359 /// let fn_ptr = fn2 as usize;
1360 /// let fn_ptr_truncated = fn_ptr as i32;
1362 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1364 "casting a function pointer to a numeric type not wide enough to store the address"
1367 /// Returns the size in bits of an integral type.
1368 /// Will return 0 if the type is not an int or uint variant
1369 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1371 ty::Int(i) => match i {
1372 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1379 ty::Uint(i) => match i {
1380 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1385 UintTy::U128 => 128,
1391 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1392 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
1395 fn span_precision_loss_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1396 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1397 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1398 let arch_dependent_str = "on targets with 64-bit wide pointers ";
1399 let from_nbits_str = if arch_dependent {
1401 } else if is_isize_or_usize(cast_from) {
1402 "32 or 64".to_owned()
1404 int_ty_to_nbits(cast_from, cx.tcx).to_string()
1408 CAST_PRECISION_LOSS,
1411 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1412 but `{1}`'s mantissa is only {4} bits wide)",
1414 if cast_to_f64 { "f64" } else { "f32" },
1415 if arch_dependent { arch_dependent_str } else { "" },
1422 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1423 if let ExprKind::Binary(_, _, _) = op.kind {
1424 if snip.starts_with('(') && snip.ends_with(')') {
1431 fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1432 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1433 if in_constant(cx, expr.hir_id) {
1436 // The suggestion is to use a function call, so if the original expression
1437 // has parens on the outside, they are no longer needed.
1438 let mut applicability = Applicability::MachineApplicable;
1439 let opt = snippet_opt(cx, op.span);
1440 let sugg = opt.as_ref().map_or_else(
1442 applicability = Applicability::HasPlaceholders;
1446 if should_strip_parens(op, snip) {
1447 &snip[1..snip.len() - 1]
1459 "casting `{}` to `{}` may become silently lossy if you later change the type",
1463 format!("{}::from({})", cast_to, sugg),
1474 fn check_loss_of_sign(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1475 if !cast_from.is_signed() || cast_to.is_signed() {
1479 // don't lint for positive constants
1480 let const_val = constant(cx, &cx.typeck_results(), op);
1482 if let Some((Constant::Int(n), _)) = const_val;
1483 if let ty::Int(ity) = *cast_from.kind();
1484 if sext(cx.tcx, n, ity) >= 0;
1490 // don't lint for the result of methods that always return non-negative values
1491 if let ExprKind::MethodCall(ref path, _, _, _) = op.kind {
1492 let mut method_name = path.ident.name.as_str();
1493 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1496 if method_name == "unwrap";
1497 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1498 if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
1500 method_name = inner_path.ident.name.as_str();
1504 if allowed_methods.iter().any(|&name| method_name == name) {
1514 "casting `{}` to `{}` may lose the sign of the value",
1520 fn check_truncation_and_wrapping(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1521 let arch_64_suffix = " on targets with 64-bit wide pointers";
1522 let arch_32_suffix = " on targets with 32-bit wide pointers";
1523 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1524 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1525 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1526 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1527 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1528 (true, true) | (false, false) => (
1529 to_nbits < from_nbits,
1531 to_nbits == from_nbits && cast_unsigned_to_signed,
1541 to_nbits <= 32 && cast_unsigned_to_signed,
1547 cast_unsigned_to_signed,
1548 if from_nbits == 64 {
1555 if span_truncation {
1558 CAST_POSSIBLE_TRUNCATION,
1561 "casting `{}` to `{}` may truncate the value{}",
1564 match suffix_truncation {
1565 ArchSuffix::_32 => arch_32_suffix,
1566 ArchSuffix::_64 => arch_64_suffix,
1567 ArchSuffix::None => "",
1578 "casting `{}` to `{}` may wrap around the value{}",
1582 ArchSuffix::_32 => arch_32_suffix,
1583 ArchSuffix::_64 => arch_64_suffix,
1584 ArchSuffix::None => "",
1591 fn check_lossless(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1592 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1593 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1594 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1595 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1597 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1601 declare_lint_pass!(Casts => [
1602 CAST_PRECISION_LOSS,
1604 CAST_POSSIBLE_TRUNCATION,
1610 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1613 // Check if the given type is either `core::ffi::c_void` or
1614 // one of the platform specific `libc::<platform>::c_void` of libc.
1615 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
1616 if let ty::Adt(adt, _) = ty.kind() {
1617 let names = cx.get_def_path(adt.did);
1619 if names.is_empty() {
1622 if names[0] == sym::libc || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1629 /// Returns the mantissa bits wide of a fp type.
1630 /// Will return 0 if the type is not a fp
1631 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1633 ty::Float(FloatTy::F32) => 23,
1634 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1639 impl<'tcx> LateLintPass<'tcx> for Casts {
1640 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1641 if expr.span.from_expansion() {
1644 if let ExprKind::Cast(ref ex, cast_to) = expr.kind {
1645 if is_hir_ty_cfg_dependant(cx, cast_to) {
1648 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
1649 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1650 if let Some(lit) = get_numeric_literal(ex) {
1651 let literal_str = snippet_opt(cx, ex.span).unwrap_or_default();
1654 if let LitKind::Int(n, _) = lit.node;
1655 if let Some(src) = snippet_opt(cx, lit.span);
1656 if cast_to.is_floating_point();
1657 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1658 let from_nbits = 128 - n.leading_zeros();
1659 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1660 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1662 let literal_str = if is_unary_neg(ex) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
1663 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1669 LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
1670 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1672 LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
1673 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1675 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1677 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
1683 "casting to the same type is unnecessary (`{}` -> `{}`)",
1691 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1692 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1695 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1696 } else if let ExprKind::MethodCall(method_path, _, args, _) = expr.kind {
1698 if method_path.ident.name == sym!(cast);
1699 if let Some(generic_args) = method_path.args;
1700 if let [GenericArg::Type(cast_to)] = generic_args.args;
1701 // There probably is no obvious reason to do this, just to be consistent with `as` cases.
1702 if !is_hir_ty_cfg_dependant(cx, cast_to);
1704 let (cast_from, cast_to) =
1705 (cx.typeck_results().expr_ty(&args[0]), cx.typeck_results().expr_ty(expr));
1706 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1713 fn is_unary_neg(expr: &Expr<'_>) -> bool {
1714 matches!(expr.kind, ExprKind::Unary(UnOp::UnNeg, _))
1717 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
1719 ExprKind::Lit(ref lit) => Some(lit),
1720 ExprKind::Unary(UnOp::UnNeg, e) => {
1721 if let ExprKind::Lit(ref lit) = e.kind {
1731 fn show_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1732 let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
1737 &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
1739 format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
1740 Applicability::MachineApplicable,
1744 fn lint_numeric_casts<'tcx>(
1745 cx: &LateContext<'tcx>,
1747 cast_expr: &Expr<'_>,
1748 cast_from: Ty<'tcx>,
1751 match (cast_from.is_integral(), cast_to.is_integral()) {
1753 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1754 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
1759 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1760 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1762 if from_nbits < to_nbits {
1763 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1769 CAST_POSSIBLE_TRUNCATION,
1771 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1773 if !cast_to.is_signed() {
1779 "casting `{}` to `{}` may lose the sign of the value",
1786 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1787 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1788 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1791 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
1794 CAST_POSSIBLE_TRUNCATION,
1796 "casting `f64` to `f32` may truncate the value",
1799 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
1800 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1806 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1808 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
1809 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
1810 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1811 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1812 if from_layout.align.abi < to_layout.align.abi;
1813 // with c_void, we inherently need to trust the user
1814 if !is_c_void(cx, from_ptr_ty.ty);
1815 // when casting from a ZST, we don't know enough to properly lint
1816 if !from_layout.is_zst();
1823 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1826 from_layout.align.abi.bytes(),
1827 to_layout.align.abi.bytes(),
1834 fn lint_fn_to_numeric_cast(
1835 cx: &LateContext<'_>,
1837 cast_expr: &Expr<'_>,
1841 // We only want to check casts to `ty::Uint` or `ty::Int`
1842 match cast_to.kind() {
1843 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1846 match cast_from.kind() {
1847 ty::FnDef(..) | ty::FnPtr(_) => {
1848 let mut applicability = Applicability::MaybeIncorrect;
1849 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1851 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1852 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1855 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1858 "casting function pointer `{}` to `{}`, which truncates the value",
1859 from_snippet, cast_to
1862 format!("{} as usize", from_snippet),
1865 } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
1870 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1872 format!("{} as usize", from_snippet),
1881 declare_clippy_lint! {
1882 /// **What it does:** Checks for types used in structs, parameters and `let`
1883 /// declarations above a certain complexity threshold.
1885 /// **Why is this bad?** Too complex types make the code less readable. Consider
1886 /// using a `type` definition to simplify them.
1888 /// **Known problems:** None.
1892 /// # use std::rc::Rc;
1894 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1897 pub TYPE_COMPLEXITY,
1899 "usage of very complex types that might be better factored into `type` definitions"
1902 pub struct TypeComplexity {
1906 impl TypeComplexity {
1908 pub fn new(threshold: u64) -> Self {
1913 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1915 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
1918 cx: &LateContext<'tcx>,
1920 decl: &'tcx FnDecl<'_>,
1925 self.check_fndecl(cx, decl);
1928 fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
1929 // enum variants are also struct fields now
1930 self.check_type(cx, &field.ty);
1933 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1935 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1936 // functions, enums, structs, impls and traits are covered
1941 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1943 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1944 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1945 // methods with default impl are covered by check_fn
1950 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
1952 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1953 // methods are covered by check_fn
1958 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
1959 if let Some(ref ty) = local.ty {
1960 self.check_type(cx, ty);
1965 impl<'tcx> TypeComplexity {
1966 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
1967 for arg in decl.inputs {
1968 self.check_type(cx, arg);
1970 if let FnRetTy::Return(ref ty) = decl.output {
1971 self.check_type(cx, ty);
1975 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
1976 if ty.span.from_expansion() {
1980 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1981 visitor.visit_ty(ty);
1985 if score > self.threshold {
1990 "very complex type used. Consider factoring parts into `type` definitions",
1996 /// Walks a type and assigns a complexity score to it.
1997 struct TypeComplexityVisitor {
1998 /// total complexity score of the type
2000 /// current nesting level
2004 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
2005 type Map = Map<'tcx>;
2007 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
2008 let (add_score, sub_nest) = match ty.kind {
2009 // _, &x and *x have only small overhead; don't mess with nesting level
2010 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
2012 // the "normal" components of a type: named types, arrays/tuples
2013 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
2015 // function types bring a lot of overhead
2016 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
2018 TyKind::TraitObject(ref param_bounds, _) => {
2019 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
2021 .bound_generic_params
2023 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
2025 if has_lifetime_parameters {
2026 // complex trait bounds like A<'a, 'b>
2029 // simple trait bounds like A + B
2036 self.score += add_score;
2037 self.nest += sub_nest;
2039 self.nest -= sub_nest;
2041 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2042 NestedVisitorMap::None
2046 declare_clippy_lint! {
2047 /// **What it does:** Checks for expressions where a character literal is cast
2048 /// to `u8` and suggests using a byte literal instead.
2050 /// **Why is this bad?** In general, casting values to smaller types is
2051 /// error-prone and should be avoided where possible. In the particular case of
2052 /// converting a character literal to u8, it is easy to avoid by just using a
2053 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
2054 /// than `'a' as u8`.
2056 /// **Known problems:** None.
2063 /// A better version, using the byte literal:
2070 "casting a character literal to `u8` truncates"
2073 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
2075 impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
2076 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2078 if !expr.span.from_expansion();
2079 if let ExprKind::Cast(e, _) = &expr.kind;
2080 if let ExprKind::Lit(l) = &e.kind;
2081 if let LitKind::Char(c) = l.node;
2082 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
2084 let mut applicability = Applicability::MachineApplicable;
2085 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
2091 "casting a character literal to `u8` truncates",
2093 diag.note("`char` is four bytes wide, but `u8` is a single byte");
2096 diag.span_suggestion(
2098 "use a byte literal instead",
2099 format!("b{}", snippet),
2109 declare_clippy_lint! {
2110 /// **What it does:** Checks for comparisons where one side of the relation is
2111 /// either the minimum or maximum value for its type and warns if it involves a
2112 /// case that is always true or always false. Only integer and boolean types are
2115 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
2116 /// that it is possible for `x` to be less than the minimum. Expressions like
2117 /// `max < x` are probably mistakes.
2119 /// **Known problems:** For `usize` the size of the current compile target will
2120 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
2121 /// a comparison to detect target pointer width will trigger this lint. One can
2122 /// use `mem::sizeof` and compare its value or conditional compilation
2124 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
2129 /// let vec: Vec<isize> = Vec::new();
2130 /// if vec.len() <= 0 {}
2131 /// if 100 > i32::MAX {}
2133 pub ABSURD_EXTREME_COMPARISONS,
2135 "a comparison with a maximum or minimum value that is always true or false"
2138 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
2145 struct ExtremeExpr<'a> {
2150 enum AbsurdComparisonResult {
2153 InequalityImpossible,
2156 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
2157 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2158 let precast_ty = cx.typeck_results().expr_ty(cast_exp);
2159 let cast_ty = cx.typeck_results().expr_ty(expr);
2161 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
2167 fn detect_absurd_comparison<'tcx>(
2168 cx: &LateContext<'tcx>,
2170 lhs: &'tcx Expr<'_>,
2171 rhs: &'tcx Expr<'_>,
2172 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
2173 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2174 use crate::types::ExtremeType::{Maximum, Minimum};
2175 use crate::utils::comparisons::{normalize_comparison, Rel};
2177 // absurd comparison only makes sense on primitive types
2178 // primitive types don't implement comparison operators with each other
2179 if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
2183 // comparisons between fix sized types and target sized types are considered unanalyzable
2184 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
2188 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
2190 let lx = detect_extreme_expr(cx, normalized_lhs);
2191 let rx = detect_extreme_expr(cx, normalized_rhs);
2196 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
2197 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
2203 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
2204 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
2205 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
2206 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
2210 Rel::Ne | Rel::Eq => return None,
2214 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
2215 use crate::types::ExtremeType::{Maximum, Minimum};
2217 let ty = cx.typeck_results().expr_ty(expr);
2219 let cv = constant(cx, cx.typeck_results(), expr)?.0;
2221 let which = match (ty.kind(), cv) {
2222 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
2223 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
2227 (&ty::Bool, Constant::Bool(true)) => Maximum,
2228 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
2231 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
2235 Some(ExtremeExpr { which, expr })
2238 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
2239 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2240 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2241 use crate::types::ExtremeType::{Maximum, Minimum};
2243 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2244 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
2245 if !expr.span.from_expansion() {
2246 let msg = "this comparison involving the minimum or maximum element for this \
2247 type contains a case that is always true or always false";
2249 let conclusion = match result {
2250 AlwaysFalse => "this comparison is always false".to_owned(),
2251 AlwaysTrue => "this comparison is always true".to_owned(),
2252 InequalityImpossible => format!(
2253 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
2255 snippet(cx, lhs.span, "lhs"),
2256 snippet(cx, rhs.span, "rhs")
2261 "because `{}` is the {} value for this type, {}",
2262 snippet(cx, culprit.expr.span, "x"),
2263 match culprit.which {
2264 Minimum => "minimum",
2265 Maximum => "maximum",
2270 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
2277 declare_clippy_lint! {
2278 /// **What it does:** Checks for comparisons where the relation is always either
2279 /// true or false, but where one side has been upcast so that the comparison is
2280 /// necessary. Only integer types are checked.
2282 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
2283 /// will mistakenly imply that it is possible for `x` to be outside the range of
2286 /// **Known problems:**
2287 /// https://github.com/rust-lang/rust-clippy/issues/886
2292 /// (x as u32) > 300;
2294 pub INVALID_UPCAST_COMPARISONS,
2296 "a comparison involving an upcast which is always true or false"
2299 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
2301 #[derive(Copy, Clone, Debug, Eq)]
2308 #[allow(clippy::cast_sign_loss)]
2310 fn cmp_s_u(s: i128, u: u128) -> Ordering {
2313 } else if u > (i128::MAX as u128) {
2321 impl PartialEq for FullInt {
2323 fn eq(&self, other: &Self) -> bool {
2324 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
2328 impl PartialOrd for FullInt {
2330 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2331 Some(match (self, other) {
2332 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
2333 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
2334 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
2335 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
2340 impl Ord for FullInt {
2342 fn cmp(&self, other: &Self) -> Ordering {
2343 self.partial_cmp(other)
2344 .expect("`partial_cmp` for FullInt can never return `None`")
2348 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
2349 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2350 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
2351 let cast_ty = cx.typeck_results().expr_ty(expr);
2352 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
2353 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
2356 match pre_cast_ty.kind() {
2357 ty::Int(int_ty) => Some(match int_ty {
2358 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
2359 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
2360 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
2361 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
2362 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
2363 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
2365 ty::Uint(uint_ty) => Some(match uint_ty {
2366 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
2367 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
2368 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
2369 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
2370 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
2371 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
2380 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2381 let val = constant(cx, cx.typeck_results(), expr)?.0;
2382 if let Constant::Int(const_int) = val {
2383 match *cx.typeck_results().expr_ty(expr).kind() {
2384 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2385 ty::Uint(_) => Some(FullInt::U(const_int)),
2393 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
2394 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2397 INVALID_UPCAST_COMPARISONS,
2400 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2401 snippet(cx, cast_val.span, "the expression"),
2402 if always { "true" } else { "false" },
2408 fn upcast_comparison_bounds_err<'tcx>(
2409 cx: &LateContext<'tcx>,
2411 rel: comparisons::Rel,
2412 lhs_bounds: Option<(FullInt, FullInt)>,
2413 lhs: &'tcx Expr<'_>,
2414 rhs: &'tcx Expr<'_>,
2417 use crate::utils::comparisons::Rel;
2419 if let Some((lb, ub)) = lhs_bounds {
2420 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2421 if rel == Rel::Eq || rel == Rel::Ne {
2422 if norm_rhs_val < lb || norm_rhs_val > ub {
2423 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2425 } else if match rel {
2440 Rel::Eq | Rel::Ne => unreachable!(),
2442 err_upcast_comparison(cx, span, lhs, true)
2443 } else if match rel {
2458 Rel::Eq | Rel::Ne => unreachable!(),
2460 err_upcast_comparison(cx, span, lhs, false)
2466 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
2467 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2468 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2469 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2470 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2476 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2477 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2479 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2480 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2485 declare_clippy_lint! {
2486 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2487 /// over different hashers and implicitly defaulting to the default hashing
2488 /// algorithm (`SipHash`).
2490 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2493 /// **Known problems:** Suggestions for replacing constructors can contain
2494 /// false-positives. Also applying suggestions can require modification of other
2495 /// pieces of code, possibly including external crates.
2499 /// # use std::collections::HashMap;
2500 /// # use std::hash::{Hash, BuildHasher};
2501 /// # trait Serialize {};
2502 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2504 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2506 /// could be rewritten as
2508 /// # use std::collections::HashMap;
2509 /// # use std::hash::{Hash, BuildHasher};
2510 /// # trait Serialize {};
2511 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2513 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2515 pub IMPLICIT_HASHER,
2517 "missing generalization over different hashers"
2520 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2522 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
2523 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2524 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
2525 use rustc_span::BytePos;
2527 fn suggestion<'tcx>(
2528 cx: &LateContext<'tcx>,
2529 diag: &mut DiagnosticBuilder<'_>,
2530 generics_span: Span,
2531 generics_suggestion_span: Span,
2532 target: &ImplicitHasherType<'_>,
2533 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2535 let generics_snip = snippet(cx, generics_span, "");
2537 let generics_snip = if generics_snip.is_empty() {
2540 &generics_snip[1..generics_snip.len() - 1]
2545 "consider adding a type parameter",
2548 generics_suggestion_span,
2550 "<{}{}S: ::std::hash::BuildHasher{}>",
2552 if generics_snip.is_empty() { "" } else { ", " },
2553 if vis.suggestions.is_empty() {
2556 // request users to add `Default` bound so that generic constructors can be used
2563 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2568 if !vis.suggestions.is_empty() {
2569 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
2573 if !cx.access_levels.is_exported(item.hir_id) {
2578 ItemKind::Impl(ref impl_) => {
2579 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2580 vis.visit_ty(impl_.self_ty);
2582 for target in &vis.found {
2583 if differing_macro_contexts(item.span, target.span()) {
2587 let generics_suggestion_span = impl_.generics.span.substitute_dummy({
2588 let pos = snippet_opt(cx, item.span.until(target.span()))
2589 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2590 if let Some(pos) = pos {
2591 Span::new(pos, pos, item.span.data().ctxt)
2597 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2598 for item in impl_.items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2599 ctr_vis.visit_impl_item(item);
2607 "impl for `{}` should be generalized over different hashers",
2611 suggestion(cx, diag, impl_.generics.span, generics_suggestion_span, target, ctr_vis);
2616 ItemKind::Fn(ref sig, ref generics, body_id) => {
2617 let body = cx.tcx.hir().body(body_id);
2619 for ty in sig.decl.inputs {
2620 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2623 for target in &vis.found {
2624 if in_external_macro(cx.sess(), generics.span) {
2627 let generics_suggestion_span = generics.span.substitute_dummy({
2628 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2630 let i = snip.find("fn")?;
2631 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2633 .expect("failed to create span for type parameters");
2634 Span::new(pos, pos, item.span.data().ctxt)
2637 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2638 ctr_vis.visit_body(body);
2645 "parameter of type `{}` should be generalized over different hashers",
2649 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2660 enum ImplicitHasherType<'tcx> {
2661 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2662 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2665 impl<'tcx> ImplicitHasherType<'tcx> {
2666 /// Checks that `ty` is a target type without a `BuildHasher`.
2667 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2668 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2669 let params: Vec<_> = path
2677 .filter_map(|arg| match arg {
2678 GenericArg::Type(ty) => Some(ty),
2682 let params_len = params.len();
2684 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2686 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2687 Some(ImplicitHasherType::HashMap(
2690 snippet(cx, params[0].span, "K"),
2691 snippet(cx, params[1].span, "V"),
2693 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2694 Some(ImplicitHasherType::HashSet(
2697 snippet(cx, params[0].span, "T"),
2707 fn type_name(&self) -> &'static str {
2709 ImplicitHasherType::HashMap(..) => "HashMap",
2710 ImplicitHasherType::HashSet(..) => "HashSet",
2714 fn type_arguments(&self) -> String {
2716 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2717 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2721 fn ty(&self) -> Ty<'tcx> {
2723 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2727 fn span(&self) -> Span {
2729 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2734 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2735 cx: &'a LateContext<'tcx>,
2736 found: Vec<ImplicitHasherType<'tcx>>,
2739 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2740 fn new(cx: &'a LateContext<'tcx>) -> Self {
2741 Self { cx, found: vec![] }
2745 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2746 type Map = Map<'tcx>;
2748 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2749 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2750 self.found.push(target);
2756 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2757 NestedVisitorMap::None
2761 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2762 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2763 cx: &'a LateContext<'tcx>,
2764 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
2765 target: &'b ImplicitHasherType<'tcx>,
2766 suggestions: BTreeMap<Span, String>,
2769 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2770 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2773 maybe_typeck_results: cx.maybe_typeck_results(),
2775 suggestions: BTreeMap::new(),
2780 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2781 type Map = Map<'tcx>;
2783 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2784 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
2785 walk_body(self, body);
2786 self.maybe_typeck_results = old_maybe_typeck_results;
2789 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2791 if let ExprKind::Call(ref fun, ref args) = e.kind;
2792 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2793 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2795 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
2799 if match_path(ty_path, &paths::HASHMAP) {
2800 if method.ident.name == sym::new {
2802 .insert(e.span, "HashMap::default()".to_string());
2803 } else if method.ident.name == sym!(with_capacity) {
2804 self.suggestions.insert(
2807 "HashMap::with_capacity_and_hasher({}, Default::default())",
2808 snippet(self.cx, args[0].span, "capacity"),
2812 } else if match_path(ty_path, &paths::HASHSET) {
2813 if method.ident.name == sym::new {
2815 .insert(e.span, "HashSet::default()".to_string());
2816 } else if method.ident.name == sym!(with_capacity) {
2817 self.suggestions.insert(
2820 "HashSet::with_capacity_and_hasher({}, Default::default())",
2821 snippet(self.cx, args[0].span, "capacity"),
2832 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2833 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2837 declare_clippy_lint! {
2838 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2840 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2841 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2844 /// **Known problems:** None.
2850 /// *(r as *const _ as *mut _) += 1;
2855 /// Instead consider using interior mutability types.
2858 /// use std::cell::UnsafeCell;
2860 /// fn x(r: &UnsafeCell<i32>) {
2866 pub CAST_REF_TO_MUT,
2868 "a cast of reference to a mutable pointer"
2871 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2873 impl<'tcx> LateLintPass<'tcx> for RefToMut {
2874 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2876 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2877 if let ExprKind::Cast(e, t) = &e.kind;
2878 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2879 if let ExprKind::Cast(e, t) = &e.kind;
2880 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2881 if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
2887 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",
2894 const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0);
2896 declare_clippy_lint! {
2897 /// **What it does:**
2898 /// Checks for `as` casts between raw pointers without changing its mutability,
2899 /// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
2901 /// **Why is this bad?**
2902 /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
2903 /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
2905 /// **Known problems:** None.
2910 /// let ptr: *const u32 = &42_u32;
2911 /// let mut_ptr: *mut u32 = &mut 42_u32;
2912 /// let _ = ptr as *const i32;
2913 /// let _ = mut_ptr as *mut i32;
2917 /// let ptr: *const u32 = &42_u32;
2918 /// let mut_ptr: *mut u32 = &mut 42_u32;
2919 /// let _ = ptr.cast::<i32>();
2920 /// let _ = mut_ptr.cast::<i32>();
2924 "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
2927 pub struct PtrAsPtr {
2928 msrv: Option<RustcVersion>,
2933 pub fn new(msrv: Option<RustcVersion>) -> Self {
2938 impl_lint_pass!(PtrAsPtr => [PTR_AS_PTR]);
2940 impl<'tcx> LateLintPass<'tcx> for PtrAsPtr {
2941 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2942 if !meets_msrv(self.msrv.as_ref(), &PTR_AS_PTR_MSRV) {
2946 if expr.span.from_expansion() {
2951 if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind;
2952 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr));
2953 if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind();
2954 if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind();
2955 if matches!((from_mutbl, to_mutbl),
2956 (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut));
2957 // The `U` in `pointer::cast` have to be `Sized`
2958 // as explained here: https://github.com/rust-lang/rust/issues/60602.
2959 if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env);
2961 let mut applicability = Applicability::MachineApplicable;
2962 let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability);
2963 let turbofish = match &cast_to_hir_ty.kind {
2964 TyKind::Infer => Cow::Borrowed(""),
2965 TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
2966 _ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
2972 "`as` casting between raw pointers without changing its mutability",
2973 "try `pointer::cast`, a safer alternative",
2974 format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
2981 extract_msrv_attr!(LateContext);