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, TypeckResults};
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;
34 clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item,
35 last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral,
36 qpath_res, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite,
37 span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
40 declare_clippy_lint! {
41 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
42 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
44 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
45 /// the heap. So if you `Box` it, you just add another level of indirection
46 /// without any benefit whatsoever.
48 /// **Known problems:** None.
53 /// values: Box<Vec<Foo>>,
66 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
69 declare_clippy_lint! {
70 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
71 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
73 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
74 /// the heap. So if you `Box` its contents, you just add another level of indirection.
76 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
82 /// values: Vec<Box<i32>>,
95 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
98 declare_clippy_lint! {
99 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
102 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
103 /// represents an optional optional value which is logically the same thing as an optional
104 /// value but has an unneeded extra level of wrapping.
106 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
107 /// consider a custom `enum` instead, with clear names for each case.
109 /// **Known problems:** None.
113 /// fn get_data() -> Option<Option<u32>> {
121 /// pub enum Contents {
122 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
123 /// NotYetFetched, // Was Some(None)
124 /// None, // Was None
127 /// fn get_data() -> Contents {
133 "usage of `Option<Option<T>>`"
136 declare_clippy_lint! {
137 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
138 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
140 /// **Why is this bad?** Gankro says:
142 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
143 /// pointers and indirection.
144 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
146 /// > "only" amortized for push/pop, should be faster in the general case for
147 /// almost every possible
148 /// > workload, and isn't even amortized at all if you can predict the capacity
151 /// > `LinkedList`s are only really good if you're doing a lot of merging or
152 /// splitting of lists.
153 /// > This is because they can just mangle some pointers instead of actually
154 /// copying the data. Even
155 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
156 /// can still be better
157 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
159 /// **Known problems:** False positives – the instances where using a
160 /// `LinkedList` makes sense are few and far between, but they can still happen.
164 /// # use std::collections::LinkedList;
165 /// let x: LinkedList<usize> = LinkedList::new();
169 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
172 declare_clippy_lint! {
173 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
174 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
176 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
179 /// **Known problems:** None.
183 /// fn foo(bar: &Box<T>) { ... }
189 /// fn foo(bar: &T) { ... }
193 "a borrow of a boxed type"
196 declare_clippy_lint! {
197 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
199 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
200 /// add an unnecessary level of indirection.
202 /// **Known problems:** None.
206 /// # use std::rc::Rc;
207 /// fn foo(bar: Rc<&usize>) {}
213 /// fn foo(bar: &usize) {}
215 pub REDUNDANT_ALLOCATION,
217 "redundant allocation"
220 declare_clippy_lint! {
221 /// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
223 /// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
224 /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
226 /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
227 /// works if there are no additional references yet, which usually defeats the purpose of
228 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
229 /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
232 /// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
233 /// cases where mutation only happens before there are any additional references.
237 /// # use std::rc::Rc;
238 /// fn foo(interned: Rc<String>) { ... }
244 /// fn foo(interned: Rc<str>) { ... }
248 "shared ownership of a buffer type"
252 vec_box_size_threshold: u64,
255 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
257 impl<'tcx> LateLintPass<'tcx> for Types {
258 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
259 // Skip trait implementations; see issue #605.
260 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
261 if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
266 self.check_fn_decl(cx, decl);
269 fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) {
270 self.check_ty(cx, &field.ty, false);
273 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
275 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
276 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
281 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
282 if let Some(ref ty) = local.ty {
283 self.check_ty(cx, ty, true);
288 /// Checks if `qpath` has last segment with type parameter matching `path`
289 fn match_type_parameter(cx: &LateContext<'_>, qpath: &QPath<'_>, path: &[&str]) -> Option<Span> {
290 let last = last_path_segment(qpath);
292 if let Some(ref params) = last.args;
293 if !params.parenthesized;
294 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
295 GenericArg::Type(ty) => Some(ty),
298 if let TyKind::Path(ref qpath) = ty.kind;
299 if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
300 if match_def_path(cx, did, path);
302 return Some(ty.span);
308 fn match_buffer_type(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<&'static str> {
309 if match_type_parameter(cx, qpath, &paths::STRING).is_some() {
312 if match_type_parameter(cx, qpath, &paths::OS_STRING).is_some() {
313 return Some("std::ffi::OsStr");
315 if match_type_parameter(cx, qpath, &paths::PATH_BUF).is_some() {
316 return Some("std::path::Path");
321 fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<Span> {
322 let last = last_path_segment(qpath);
324 if let Some(ref params) = last.args;
325 if !params.parenthesized;
326 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
327 GenericArg::Type(ty) => Some(ty),
330 if let TyKind::Rptr(..) = ty.kind;
332 return Some(ty.span);
339 pub fn new(vec_box_size_threshold: u64) -> Self {
340 Self { vec_box_size_threshold }
343 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
344 for input in decl.inputs {
345 self.check_ty(cx, input, false);
348 if let FnRetTy::Return(ref ty) = decl.output {
349 self.check_ty(cx, ty, false);
353 /// Recursively check for `TypePass` lints in the given type. Stop at the first
356 /// The parameter `is_local` distinguishes the context of the type; types from
357 /// local bindings should only be checked for the `BORROWED_BOX` lint.
358 #[allow(clippy::too_many_lines)]
359 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
360 if hir_ty.span.from_expansion() {
364 TyKind::Path(ref qpath) if !is_local => {
365 let hir_id = hir_ty.hir_id;
366 let res = qpath_res(cx, qpath, hir_id);
367 if let Some(def_id) = res.opt_def_id() {
368 if Some(def_id) == cx.tcx.lang_items().owned_box() {
369 if let Some(span) = match_borrows_parameter(cx, qpath) {
370 let mut applicability = Applicability::MachineApplicable;
373 REDUNDANT_ALLOCATION,
375 "usage of `Box<&T>`",
377 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
380 return; // don't recurse into the type
382 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
387 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
389 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
391 return; // don't recurse into the type
393 } else if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
394 if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) {
395 let mut applicability = Applicability::MachineApplicable;
398 REDUNDANT_ALLOCATION,
400 "usage of `Rc<Rc<T>>`",
402 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
405 return; // don't recurse into the type
407 if match_type_parameter(cx, qpath, &paths::BOX).is_some() {
408 let box_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
409 GenericArg::Type(ty) => match &ty.kind {
410 TyKind::Path(qpath) => qpath,
415 let inner_span = match &last_path_segment(&box_ty).args.unwrap().args[0] {
416 GenericArg::Type(ty) => ty.span,
419 let mut applicability = Applicability::MachineApplicable;
422 REDUNDANT_ALLOCATION,
424 "usage of `Rc<Box<T>>`",
428 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
432 return; // don't recurse into the type
434 if let Some(alternate) = match_buffer_type(cx, qpath) {
439 "usage of `Rc<T>` when T is a buffer type",
441 format!("Rc<{}>", alternate),
442 Applicability::MachineApplicable,
444 return; // don't recurse into the type
446 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
447 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
448 GenericArg::Type(ty) => match &ty.kind {
449 TyKind::Path(qpath) => qpath,
454 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
455 GenericArg::Type(ty) => ty.span,
458 let mut applicability = Applicability::MachineApplicable;
463 "usage of `Rc<T>` when T is a buffer type",
467 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
469 Applicability::MachineApplicable,
471 return; // don't recurse into the type
473 if let Some(span) = match_borrows_parameter(cx, qpath) {
474 let mut applicability = Applicability::MachineApplicable;
477 REDUNDANT_ALLOCATION,
481 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
484 return; // don't recurse into the type
486 } else if cx.tcx.is_diagnostic_item(sym::Arc, def_id) {
487 if let Some(alternate) = match_buffer_type(cx, qpath) {
492 "usage of `Arc<T>` when T is a buffer type",
494 format!("Arc<{}>", alternate),
495 Applicability::MachineApplicable,
497 return; // don't recurse into the type
499 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
500 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
501 GenericArg::Type(ty) => match &ty.kind {
502 TyKind::Path(qpath) => qpath,
507 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
508 GenericArg::Type(ty) => ty.span,
511 let mut applicability = Applicability::MachineApplicable;
516 "usage of `Arc<T>` when T is a buffer type",
520 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
522 Applicability::MachineApplicable,
524 return; // don't recurse into the type
526 } else if cx.tcx.is_diagnostic_item(sym::vec_type, def_id) {
528 // Get the _ part of Vec<_>
529 if let Some(ref last) = last_path_segment(qpath).args;
530 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
531 GenericArg::Type(ty) => Some(ty),
534 // ty is now _ at this point
535 if let TyKind::Path(ref ty_qpath) = ty.kind;
536 let res = qpath_res(cx, ty_qpath, ty.hir_id);
537 if let Some(def_id) = res.opt_def_id();
538 if Some(def_id) == cx.tcx.lang_items().owned_box();
539 // At this point, we know ty is Box<T>, now get T
540 if let Some(ref last) = last_path_segment(ty_qpath).args;
541 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
542 GenericArg::Type(ty) => Some(ty),
545 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
546 if !ty_ty.has_escaping_bound_vars();
547 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env);
548 if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes());
549 if ty_ty_size <= self.vec_box_size_threshold;
555 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
557 format!("Vec<{}>", snippet(cx, boxed_ty.span, "..")),
558 Applicability::MachineApplicable,
560 return; // don't recurse into the type
563 } else if cx.tcx.is_diagnostic_item(sym::option_type, def_id) {
564 if match_type_parameter(cx, qpath, &paths::OPTION).is_some() {
569 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
570 enum if you need to distinguish all 3 cases",
572 return; // don't recurse into the type
574 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
579 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
581 "a `VecDeque` might work",
583 return; // don't recurse into the type
587 QPath::Resolved(Some(ref ty), ref p) => {
588 self.check_ty(cx, ty, is_local);
589 for ty in p.segments.iter().flat_map(|seg| {
592 .map_or_else(|| [].iter(), |params| params.args.iter())
593 .filter_map(|arg| match arg {
594 GenericArg::Type(ty) => Some(ty),
598 self.check_ty(cx, ty, is_local);
601 QPath::Resolved(None, ref p) => {
602 for ty in p.segments.iter().flat_map(|seg| {
605 .map_or_else(|| [].iter(), |params| params.args.iter())
606 .filter_map(|arg| match arg {
607 GenericArg::Type(ty) => Some(ty),
611 self.check_ty(cx, ty, is_local);
614 QPath::TypeRelative(ref ty, ref seg) => {
615 self.check_ty(cx, ty, is_local);
616 if let Some(ref params) = seg.args {
617 for ty in params.args.iter().filter_map(|arg| match arg {
618 GenericArg::Type(ty) => Some(ty),
621 self.check_ty(cx, ty, is_local);
625 QPath::LangItem(..) => {},
628 TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
630 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
631 self.check_ty(cx, ty, is_local)
633 TyKind::Tup(tys) => {
635 self.check_ty(cx, ty, is_local);
644 cx: &LateContext<'_>,
645 hir_ty: &hir::Ty<'_>,
650 match mut_ty.ty.kind {
651 TyKind::Path(ref qpath) => {
652 let hir_id = mut_ty.ty.hir_id;
653 let def = qpath_res(cx, qpath, hir_id);
655 if let Some(def_id) = def.opt_def_id();
656 if Some(def_id) == cx.tcx.lang_items().owned_box();
657 if let QPath::Resolved(None, ref path) = *qpath;
658 if let [ref bx] = *path.segments;
659 if let Some(ref params) = bx.args;
660 if !params.parenthesized;
661 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
662 GenericArg::Type(ty) => Some(ty),
666 if is_any_trait(inner) {
667 // Ignore `Box<Any>` types; see issue #1884 for details.
671 let ltopt = if lt.is_elided() {
674 format!("{} ", lt.name.ident().as_str())
677 if mut_ty.mutbl == Mutability::Mut {
678 // Ignore `&mut Box<T>` types; see issue #2907 for
683 // When trait objects or opaque types have lifetime or auto-trait bounds,
684 // we need to add parentheses to avoid a syntax error due to its ambiguity.
685 // Originally reported as the issue #3128.
686 let inner_snippet = snippet(cx, inner.span, "..");
687 let suggestion = match &inner.kind {
688 TyKind::TraitObject(bounds, lt_bound) if bounds.len() > 1 || !lt_bound.is_elided() => {
689 format!("&{}({})", ltopt, &inner_snippet)
692 if get_bounds_if_impl_trait(cx, qpath, inner.hir_id)
693 .map_or(false, |bounds| bounds.len() > 1) =>
695 format!("&{}({})", ltopt, &inner_snippet)
697 _ => format!("&{}{}", ltopt, &inner_snippet),
703 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
706 // To make this `MachineApplicable`, at least one needs to check if it isn't a trait item
707 // because the trait impls of it will break otherwise;
708 // and there may be other cases that result in invalid code.
709 // For example, type coercion doesn't work nicely.
710 Applicability::Unspecified,
712 return; // don't recurse into the type
715 self.check_ty(cx, &mut_ty.ty, is_local);
717 _ => self.check_ty(cx, &mut_ty.ty, is_local),
722 // Returns true if given type is `Any` trait.
723 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
725 if let TyKind::TraitObject(ref traits, _) = t.kind;
726 if !traits.is_empty();
727 // Only Send/Sync can be used as additional traits, so it is enough to
728 // check only the first trait.
729 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
738 fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: HirId) -> Option<GenericBounds<'tcx>> {
740 if let Some(did) = qpath_res(cx, qpath, id).opt_def_id();
741 if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did);
742 if let GenericParamKind::Type { synthetic, .. } = generic_param.kind;
743 if synthetic == Some(SyntheticTyParamKind::ImplTrait);
745 Some(generic_param.bounds)
752 declare_clippy_lint! {
753 /// **What it does:** Checks for binding a unit value.
755 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
756 /// binding one is kind of pointless.
758 /// **Known problems:** None.
768 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
771 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
773 impl<'tcx> LateLintPass<'tcx> for LetUnitValue {
774 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
775 if let StmtKind::Local(ref local) = stmt.kind {
776 if is_unit(cx.typeck_results().pat_ty(&local.pat)) {
777 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
780 if higher::is_from_for_desugar(local) {
787 "this let-binding has unit value",
789 if let Some(expr) = &local.init {
790 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
791 diag.span_suggestion(
793 "omit the `let` binding",
794 format!("{};", snip),
795 Applicability::MachineApplicable, // snippet
805 declare_clippy_lint! {
806 /// **What it does:** Checks for comparisons to unit. This includes all binary
807 /// comparisons (like `==` and `<`) and asserts.
809 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
810 /// clumsily written constant. Mostly this happens when someone accidentally
811 /// adds semicolons at the end of the operands.
813 /// **Known problems:** None.
844 /// assert_eq!({ foo(); }, { bar(); });
846 /// will always succeed
849 "comparing unit values"
852 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
854 impl<'tcx> LateLintPass<'tcx> for UnitCmp {
855 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
856 if expr.span.from_expansion() {
857 if let Some(callee) = expr.span.source_callee() {
858 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
859 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
861 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
862 let result = match &*symbol.as_str() {
863 "assert_eq" | "debug_assert_eq" => "succeed",
864 "assert_ne" | "debug_assert_ne" => "fail",
872 "`{}` of unit values detected. This will always {}",
883 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
885 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
886 let result = match op {
887 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
895 "{}-comparison of unit values detected. This will always be {}",
905 declare_clippy_lint! {
906 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
907 /// unit literal (`()`).
909 /// **Why is this bad?** This is likely the result of an accidental semicolon.
911 /// **Known problems:** None.
922 "passing unit to a function"
925 declare_lint_pass!(UnitArg => [UNIT_ARG]);
927 impl<'tcx> LateLintPass<'tcx> for UnitArg {
928 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
929 if expr.span.from_expansion() {
933 // apparently stuff in the desugaring of `?` can trigger this
934 // so check for that here
935 // only the calls to `Try::from_error` is marked as desugared,
936 // so we need to check both the current Expr and its parent.
937 if is_questionmark_desugar_marked_call(expr) {
941 let map = &cx.tcx.hir();
942 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
943 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
944 if is_questionmark_desugar_marked_call(parent_expr);
951 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => {
952 let args_to_recover = args
955 if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) {
956 !matches!(&arg.kind, ExprKind::Match(.., MatchSource::TryDesugar))
961 .collect::<Vec<_>>();
962 if !args_to_recover.is_empty() {
963 lint_unit_args(cx, expr, &args_to_recover);
971 fn fmt_stmts_and_call(
972 cx: &LateContext<'_>,
973 call_expr: &Expr<'_>,
975 args_snippets: &[impl AsRef<str>],
976 non_empty_block_args_snippets: &[impl AsRef<str>],
978 let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
979 let call_snippet_with_replacements = args_snippets
981 .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
983 let mut stmts_and_call = non_empty_block_args_snippets
985 .map(|it| it.as_ref().to_owned())
986 .collect::<Vec<_>>();
987 stmts_and_call.push(call_snippet_with_replacements);
988 stmts_and_call = stmts_and_call
990 .map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
993 let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
994 // expr is not in a block statement or result expression position, wrap in a block
995 let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
996 if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
997 let block_indent = call_expr_indent + 4;
998 stmts_and_call_snippet =
999 reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
1000 stmts_and_call_snippet = format!(
1002 " ".repeat(block_indent),
1003 &stmts_and_call_snippet,
1004 " ".repeat(call_expr_indent)
1007 stmts_and_call_snippet
1010 fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
1011 let mut applicability = Applicability::MachineApplicable;
1012 let (singular, plural) = if args_to_recover.len() > 1 {
1021 &format!("passing {}unit value{} to a function", singular, plural),
1028 if let ExprKind::Block(block, _) = arg.kind;
1029 if block.expr.is_none();
1030 if let Some(last_stmt) = block.stmts.iter().last();
1031 if let StmtKind::Semi(last_expr) = last_stmt.kind;
1032 if let Some(snip) = snippet_opt(cx, last_expr.span);
1044 .for_each(|(span, sugg)| {
1047 "remove the semicolon from the last statement in the block",
1049 Applicability::MaybeIncorrect,
1052 applicability = Applicability::MaybeIncorrect;
1055 let arg_snippets: Vec<String> = args_to_recover
1057 .filter_map(|arg| snippet_opt(cx, arg.span))
1059 let arg_snippets_without_empty_blocks: Vec<String> = args_to_recover
1061 .filter(|arg| !is_empty_block(arg))
1062 .filter_map(|arg| snippet_opt(cx, arg.span))
1065 if let Some(call_snippet) = snippet_opt(cx, expr.span) {
1066 let sugg = fmt_stmts_and_call(
1071 &arg_snippets_without_empty_blocks,
1074 if arg_snippets_without_empty_blocks.is_empty() {
1075 db.multipart_suggestion(
1076 &format!("use {}unit literal{} instead", singular, plural),
1079 .map(|arg| (arg.span, "()".to_string()))
1080 .collect::<Vec<_>>(),
1084 let plural = arg_snippets_without_empty_blocks.len() > 1;
1085 let empty_or_s = if plural { "s" } else { "" };
1086 let it_or_them = if plural { "them" } else { "it" };
1090 "{}move the expression{} in front of the call and replace {} with the unit literal `()`",
1091 or, empty_or_s, it_or_them
1102 fn is_empty_block(expr: &Expr<'_>) -> bool {
1107 stmts: &[], expr: None, ..
1114 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
1115 use rustc_span::hygiene::DesugaringKind;
1116 if let ExprKind::Call(ref callee, _) = expr.kind {
1117 callee.span.is_desugaring(DesugaringKind::QuestionMark)
1123 fn is_unit(ty: Ty<'_>) -> bool {
1124 matches!(ty.kind(), ty::Tuple(slice) if slice.is_empty())
1127 fn is_unit_literal(expr: &Expr<'_>) -> bool {
1128 matches!(expr.kind, ExprKind::Tup(ref slice) if slice.is_empty())
1131 declare_clippy_lint! {
1132 /// **What it does:** Checks for casts from any numerical to a float type where
1133 /// the receiving type cannot store all values from the original type without
1134 /// rounding errors. This possible rounding is to be expected, so this lint is
1135 /// `Allow` by default.
1137 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
1138 /// or any 64-bit integer to `f64`.
1140 /// **Why is this bad?** It's not bad at all. But in some applications it can be
1141 /// helpful to know where precision loss can take place. This lint can help find
1142 /// those places in the code.
1144 /// **Known problems:** None.
1148 /// let x = u64::MAX;
1151 pub CAST_PRECISION_LOSS,
1153 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
1156 declare_clippy_lint! {
1157 /// **What it does:** Checks for casts from a signed to an unsigned numerical
1158 /// type. In this case, negative values wrap around to large positive values,
1159 /// which can be quite surprising in practice. However, as the cast works as
1160 /// defined, this lint is `Allow` by default.
1162 /// **Why is this bad?** Possibly surprising results. You can activate this lint
1163 /// as a one-time check to see where numerical wrapping can arise.
1165 /// **Known problems:** None.
1170 /// y as u128; // will return 18446744073709551615
1174 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
1177 declare_clippy_lint! {
1178 /// **What it does:** Checks for casts between numerical types that may
1179 /// truncate large values. This is expected behavior, so the cast is `Allow` by
1182 /// **Why is this bad?** In some problem domains, it is good practice to avoid
1183 /// truncation. This lint can be activated to help assess where additional
1184 /// checks could be beneficial.
1186 /// **Known problems:** None.
1190 /// fn as_u8(x: u64) -> u8 {
1194 pub CAST_POSSIBLE_TRUNCATION,
1196 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
1199 declare_clippy_lint! {
1200 /// **What it does:** Checks for casts from an unsigned type to a signed type of
1201 /// the same size. Performing such a cast is a 'no-op' for the compiler,
1202 /// i.e., nothing is changed at the bit level, and the binary representation of
1203 /// the value is reinterpreted. This can cause wrapping if the value is too big
1204 /// for the target signed type. However, the cast works as defined, so this lint
1205 /// is `Allow` by default.
1207 /// **Why is this bad?** While such a cast is not bad in itself, the results can
1208 /// be surprising when this is not the intended behavior, as demonstrated by the
1211 /// **Known problems:** None.
1215 /// u32::MAX as i32; // will yield a value of `-1`
1217 pub CAST_POSSIBLE_WRAP,
1219 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
1222 declare_clippy_lint! {
1223 /// **What it does:** Checks for casts between numerical types that may
1224 /// be replaced by safe conversion functions.
1226 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
1227 /// conversions, including silently lossy conversions. Conversion functions such
1228 /// as `i32::from` will only perform lossless conversions. Using the conversion
1229 /// functions prevents conversions from turning into silent lossy conversions if
1230 /// the types of the input expressions ever change, and make it easier for
1231 /// people reading the code to know that the conversion is lossless.
1233 /// **Known problems:** None.
1237 /// fn as_u64(x: u8) -> u64 {
1242 /// Using `::from` would look like this:
1245 /// fn as_u64(x: u8) -> u64 {
1251 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
1254 declare_clippy_lint! {
1255 /// **What it does:** Checks for casts to the same type, casts of int literals to integer types
1256 /// and casts of float literals to float types.
1258 /// **Why is this bad?** It's just unnecessary.
1260 /// **Known problems:** None.
1264 /// let _ = 2i32 as i32;
1265 /// let _ = 0.5 as f32;
1272 /// let _ = 0.5_f32;
1274 pub UNNECESSARY_CAST,
1276 "cast to the same type, e.g., `x as i32` where `x: i32`"
1279 declare_clippy_lint! {
1280 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
1281 /// more-strictly-aligned pointer
1283 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
1286 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
1287 /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
1288 /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
1292 /// let _ = (&1u8 as *const u8) as *const u16;
1293 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
1295 pub CAST_PTR_ALIGNMENT,
1297 "cast from a pointer to a more-strictly-aligned pointer"
1300 declare_clippy_lint! {
1301 /// **What it does:** Checks for casts of function pointers to something other than usize
1303 /// **Why is this bad?**
1304 /// Casting a function pointer to anything other than usize/isize is not portable across
1305 /// architectures, because you end up losing bits if the target type is too small or end up with a
1306 /// bunch of extra bits that waste space and add more instructions to the final binary than
1307 /// strictly necessary for the problem
1309 /// Casting to isize also doesn't make sense since there are no signed addresses.
1315 /// fn fun() -> i32 { 1 }
1316 /// let a = fun as i64;
1319 /// fn fun2() -> i32 { 1 }
1320 /// let a = fun2 as usize;
1322 pub FN_TO_NUMERIC_CAST,
1324 "casting a function pointer to a numeric type other than usize"
1327 declare_clippy_lint! {
1328 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1331 /// **Why is this bad?**
1332 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1333 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1334 /// a comment) to perform the truncation.
1340 /// fn fn1() -> i16 {
1343 /// let _ = fn1 as i32;
1345 /// // Better: Cast to usize first, then comment with the reason for the truncation
1346 /// fn fn2() -> i16 {
1349 /// let fn_ptr = fn2 as usize;
1350 /// let fn_ptr_truncated = fn_ptr as i32;
1352 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1354 "casting a function pointer to a numeric type not wide enough to store the address"
1357 /// Returns the size in bits of an integral type.
1358 /// Will return 0 if the type is not an int or uint variant
1359 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1361 ty::Int(i) => match i {
1362 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1369 ty::Uint(i) => match i {
1370 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1375 UintTy::U128 => 128,
1381 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1382 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
1385 fn span_precision_loss_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1386 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1387 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1388 let arch_dependent_str = "on targets with 64-bit wide pointers ";
1389 let from_nbits_str = if arch_dependent {
1391 } else if is_isize_or_usize(cast_from) {
1392 "32 or 64".to_owned()
1394 int_ty_to_nbits(cast_from, cx.tcx).to_string()
1398 CAST_PRECISION_LOSS,
1401 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1402 but `{1}`'s mantissa is only {4} bits wide)",
1404 if cast_to_f64 { "f64" } else { "f32" },
1405 if arch_dependent { arch_dependent_str } else { "" },
1412 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1413 if let ExprKind::Binary(_, _, _) = op.kind {
1414 if snip.starts_with('(') && snip.ends_with(')') {
1421 fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1422 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1423 if in_constant(cx, expr.hir_id) {
1426 // The suggestion is to use a function call, so if the original expression
1427 // has parens on the outside, they are no longer needed.
1428 let mut applicability = Applicability::MachineApplicable;
1429 let opt = snippet_opt(cx, op.span);
1430 let sugg = opt.as_ref().map_or_else(
1432 applicability = Applicability::HasPlaceholders;
1436 if should_strip_parens(op, snip) {
1437 &snip[1..snip.len() - 1]
1449 "casting `{}` to `{}` may become silently lossy if you later change the type",
1453 format!("{}::from({})", cast_to, sugg),
1464 fn check_loss_of_sign(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1465 if !cast_from.is_signed() || cast_to.is_signed() {
1469 // don't lint for positive constants
1470 let const_val = constant(cx, &cx.typeck_results(), op);
1472 if let Some((Constant::Int(n), _)) = const_val;
1473 if let ty::Int(ity) = *cast_from.kind();
1474 if sext(cx.tcx, n, ity) >= 0;
1480 // don't lint for the result of methods that always return non-negative values
1481 if let ExprKind::MethodCall(ref path, _, _, _) = op.kind {
1482 let mut method_name = path.ident.name.as_str();
1483 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1486 if method_name == "unwrap";
1487 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1488 if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
1490 method_name = inner_path.ident.name.as_str();
1494 if allowed_methods.iter().any(|&name| method_name == name) {
1504 "casting `{}` to `{}` may lose the sign of the value",
1510 fn check_truncation_and_wrapping(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1511 let arch_64_suffix = " on targets with 64-bit wide pointers";
1512 let arch_32_suffix = " on targets with 32-bit wide pointers";
1513 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1514 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1515 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1516 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1517 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1518 (true, true) | (false, false) => (
1519 to_nbits < from_nbits,
1521 to_nbits == from_nbits && cast_unsigned_to_signed,
1531 to_nbits <= 32 && cast_unsigned_to_signed,
1537 cast_unsigned_to_signed,
1538 if from_nbits == 64 {
1545 if span_truncation {
1548 CAST_POSSIBLE_TRUNCATION,
1551 "casting `{}` to `{}` may truncate the value{}",
1554 match suffix_truncation {
1555 ArchSuffix::_32 => arch_32_suffix,
1556 ArchSuffix::_64 => arch_64_suffix,
1557 ArchSuffix::None => "",
1568 "casting `{}` to `{}` may wrap around the value{}",
1572 ArchSuffix::_32 => arch_32_suffix,
1573 ArchSuffix::_64 => arch_64_suffix,
1574 ArchSuffix::None => "",
1581 fn check_lossless(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1582 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1583 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1584 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1585 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1587 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1591 declare_lint_pass!(Casts => [
1592 CAST_PRECISION_LOSS,
1594 CAST_POSSIBLE_TRUNCATION,
1600 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1603 // Check if the given type is either `core::ffi::c_void` or
1604 // one of the platform specific `libc::<platform>::c_void` of libc.
1605 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
1606 if let ty::Adt(adt, _) = ty.kind() {
1607 let names = cx.get_def_path(adt.did);
1609 if names.is_empty() {
1612 if names[0] == sym::libc || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1619 /// Returns the mantissa bits wide of a fp type.
1620 /// Will return 0 if the type is not a fp
1621 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1623 ty::Float(FloatTy::F32) => 23,
1624 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1629 impl<'tcx> LateLintPass<'tcx> for Casts {
1630 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1631 if expr.span.from_expansion() {
1634 if let ExprKind::Cast(ref ex, cast_to) = expr.kind {
1635 if let TyKind::Path(QPath::Resolved(_, path)) = cast_to.kind {
1636 if let Res::Def(_, def_id) = path.res {
1637 if cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr) {
1642 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
1643 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1644 if let Some(lit) = get_numeric_literal(ex) {
1645 let literal_str = snippet_opt(cx, ex.span).unwrap_or_default();
1648 if let LitKind::Int(n, _) = lit.node;
1649 if let Some(src) = snippet_opt(cx, lit.span);
1650 if cast_to.is_floating_point();
1651 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1652 let from_nbits = 128 - n.leading_zeros();
1653 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1654 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1656 let literal_str = if is_unary_neg(ex) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
1657 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1663 LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
1664 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1666 LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
1667 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1669 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1671 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
1677 "casting to the same type is unnecessary (`{}` -> `{}`)",
1685 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1686 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1689 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1694 fn is_unary_neg(expr: &Expr<'_>) -> bool {
1695 matches!(expr.kind, ExprKind::Unary(UnOp::UnNeg, _))
1698 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
1700 ExprKind::Lit(ref lit) => Some(lit),
1701 ExprKind::Unary(UnOp::UnNeg, e) => {
1702 if let ExprKind::Lit(ref lit) = e.kind {
1712 fn show_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1713 let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
1718 &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
1720 format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
1721 Applicability::MachineApplicable,
1725 fn lint_numeric_casts<'tcx>(
1726 cx: &LateContext<'tcx>,
1728 cast_expr: &Expr<'_>,
1729 cast_from: Ty<'tcx>,
1732 match (cast_from.is_integral(), cast_to.is_integral()) {
1734 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1735 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
1740 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1741 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1743 if from_nbits < to_nbits {
1744 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1750 CAST_POSSIBLE_TRUNCATION,
1752 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1754 if !cast_to.is_signed() {
1760 "casting `{}` to `{}` may lose the sign of the value",
1767 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1768 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1769 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1772 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
1775 CAST_POSSIBLE_TRUNCATION,
1777 "casting `f64` to `f32` may truncate the value",
1780 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
1781 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1787 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1789 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
1790 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
1791 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1792 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1793 if from_layout.align.abi < to_layout.align.abi;
1794 // with c_void, we inherently need to trust the user
1795 if !is_c_void(cx, from_ptr_ty.ty);
1796 // when casting from a ZST, we don't know enough to properly lint
1797 if !from_layout.is_zst();
1804 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1807 from_layout.align.abi.bytes(),
1808 to_layout.align.abi.bytes(),
1815 fn lint_fn_to_numeric_cast(
1816 cx: &LateContext<'_>,
1818 cast_expr: &Expr<'_>,
1822 // We only want to check casts to `ty::Uint` or `ty::Int`
1823 match cast_to.kind() {
1824 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1827 match cast_from.kind() {
1828 ty::FnDef(..) | ty::FnPtr(_) => {
1829 let mut applicability = Applicability::MaybeIncorrect;
1830 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1832 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1833 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1836 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1839 "casting function pointer `{}` to `{}`, which truncates the value",
1840 from_snippet, cast_to
1843 format!("{} as usize", from_snippet),
1846 } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
1851 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1853 format!("{} as usize", from_snippet),
1862 declare_clippy_lint! {
1863 /// **What it does:** Checks for types used in structs, parameters and `let`
1864 /// declarations above a certain complexity threshold.
1866 /// **Why is this bad?** Too complex types make the code less readable. Consider
1867 /// using a `type` definition to simplify them.
1869 /// **Known problems:** None.
1873 /// # use std::rc::Rc;
1875 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1878 pub TYPE_COMPLEXITY,
1880 "usage of very complex types that might be better factored into `type` definitions"
1883 pub struct TypeComplexity {
1887 impl TypeComplexity {
1889 pub fn new(threshold: u64) -> Self {
1894 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1896 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
1899 cx: &LateContext<'tcx>,
1901 decl: &'tcx FnDecl<'_>,
1906 self.check_fndecl(cx, decl);
1909 fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
1910 // enum variants are also struct fields now
1911 self.check_type(cx, &field.ty);
1914 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1916 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1917 // functions, enums, structs, impls and traits are covered
1922 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1924 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1925 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1926 // methods with default impl are covered by check_fn
1931 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
1933 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1934 // methods are covered by check_fn
1939 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
1940 if let Some(ref ty) = local.ty {
1941 self.check_type(cx, ty);
1946 impl<'tcx> TypeComplexity {
1947 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
1948 for arg in decl.inputs {
1949 self.check_type(cx, arg);
1951 if let FnRetTy::Return(ref ty) = decl.output {
1952 self.check_type(cx, ty);
1956 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
1957 if ty.span.from_expansion() {
1961 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1962 visitor.visit_ty(ty);
1966 if score > self.threshold {
1971 "very complex type used. Consider factoring parts into `type` definitions",
1977 /// Walks a type and assigns a complexity score to it.
1978 struct TypeComplexityVisitor {
1979 /// total complexity score of the type
1981 /// current nesting level
1985 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1986 type Map = Map<'tcx>;
1988 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1989 let (add_score, sub_nest) = match ty.kind {
1990 // _, &x and *x have only small overhead; don't mess with nesting level
1991 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1993 // the "normal" components of a type: named types, arrays/tuples
1994 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1996 // function types bring a lot of overhead
1997 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1999 TyKind::TraitObject(ref param_bounds, _) => {
2000 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
2002 .bound_generic_params
2004 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
2006 if has_lifetime_parameters {
2007 // complex trait bounds like A<'a, 'b>
2010 // simple trait bounds like A + B
2017 self.score += add_score;
2018 self.nest += sub_nest;
2020 self.nest -= sub_nest;
2022 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2023 NestedVisitorMap::None
2027 declare_clippy_lint! {
2028 /// **What it does:** Checks for expressions where a character literal is cast
2029 /// to `u8` and suggests using a byte literal instead.
2031 /// **Why is this bad?** In general, casting values to smaller types is
2032 /// error-prone and should be avoided where possible. In the particular case of
2033 /// converting a character literal to u8, it is easy to avoid by just using a
2034 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
2035 /// than `'a' as u8`.
2037 /// **Known problems:** None.
2044 /// A better version, using the byte literal:
2051 "casting a character literal to `u8` truncates"
2054 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
2056 impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
2057 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2059 if !expr.span.from_expansion();
2060 if let ExprKind::Cast(e, _) = &expr.kind;
2061 if let ExprKind::Lit(l) = &e.kind;
2062 if let LitKind::Char(c) = l.node;
2063 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
2065 let mut applicability = Applicability::MachineApplicable;
2066 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
2072 "casting a character literal to `u8` truncates",
2074 diag.note("`char` is four bytes wide, but `u8` is a single byte");
2077 diag.span_suggestion(
2079 "use a byte literal instead",
2080 format!("b{}", snippet),
2090 declare_clippy_lint! {
2091 /// **What it does:** Checks for comparisons where one side of the relation is
2092 /// either the minimum or maximum value for its type and warns if it involves a
2093 /// case that is always true or always false. Only integer and boolean types are
2096 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
2097 /// that it is possible for `x` to be less than the minimum. Expressions like
2098 /// `max < x` are probably mistakes.
2100 /// **Known problems:** For `usize` the size of the current compile target will
2101 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
2102 /// a comparison to detect target pointer width will trigger this lint. One can
2103 /// use `mem::sizeof` and compare its value or conditional compilation
2105 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
2110 /// let vec: Vec<isize> = Vec::new();
2111 /// if vec.len() <= 0 {}
2112 /// if 100 > i32::MAX {}
2114 pub ABSURD_EXTREME_COMPARISONS,
2116 "a comparison with a maximum or minimum value that is always true or false"
2119 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
2126 struct ExtremeExpr<'a> {
2131 enum AbsurdComparisonResult {
2134 InequalityImpossible,
2137 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
2138 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2139 let precast_ty = cx.typeck_results().expr_ty(cast_exp);
2140 let cast_ty = cx.typeck_results().expr_ty(expr);
2142 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
2148 fn detect_absurd_comparison<'tcx>(
2149 cx: &LateContext<'tcx>,
2151 lhs: &'tcx Expr<'_>,
2152 rhs: &'tcx Expr<'_>,
2153 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
2154 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2155 use crate::types::ExtremeType::{Maximum, Minimum};
2156 use crate::utils::comparisons::{normalize_comparison, Rel};
2158 // absurd comparison only makes sense on primitive types
2159 // primitive types don't implement comparison operators with each other
2160 if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
2164 // comparisons between fix sized types and target sized types are considered unanalyzable
2165 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
2169 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
2171 let lx = detect_extreme_expr(cx, normalized_lhs);
2172 let rx = detect_extreme_expr(cx, normalized_rhs);
2177 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
2178 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
2184 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
2185 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
2186 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
2187 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
2191 Rel::Ne | Rel::Eq => return None,
2195 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
2196 use crate::types::ExtremeType::{Maximum, Minimum};
2198 let ty = cx.typeck_results().expr_ty(expr);
2200 let cv = constant(cx, cx.typeck_results(), expr)?.0;
2202 let which = match (ty.kind(), cv) {
2203 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
2204 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
2208 (&ty::Bool, Constant::Bool(true)) => Maximum,
2209 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
2212 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
2216 Some(ExtremeExpr { which, expr })
2219 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
2220 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2221 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2222 use crate::types::ExtremeType::{Maximum, Minimum};
2224 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2225 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
2226 if !expr.span.from_expansion() {
2227 let msg = "this comparison involving the minimum or maximum element for this \
2228 type contains a case that is always true or always false";
2230 let conclusion = match result {
2231 AlwaysFalse => "this comparison is always false".to_owned(),
2232 AlwaysTrue => "this comparison is always true".to_owned(),
2233 InequalityImpossible => format!(
2234 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
2236 snippet(cx, lhs.span, "lhs"),
2237 snippet(cx, rhs.span, "rhs")
2242 "because `{}` is the {} value for this type, {}",
2243 snippet(cx, culprit.expr.span, "x"),
2244 match culprit.which {
2245 Minimum => "minimum",
2246 Maximum => "maximum",
2251 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
2258 declare_clippy_lint! {
2259 /// **What it does:** Checks for comparisons where the relation is always either
2260 /// true or false, but where one side has been upcast so that the comparison is
2261 /// necessary. Only integer types are checked.
2263 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
2264 /// will mistakenly imply that it is possible for `x` to be outside the range of
2267 /// **Known problems:**
2268 /// https://github.com/rust-lang/rust-clippy/issues/886
2273 /// (x as u32) > 300;
2275 pub INVALID_UPCAST_COMPARISONS,
2277 "a comparison involving an upcast which is always true or false"
2280 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
2282 #[derive(Copy, Clone, Debug, Eq)]
2289 #[allow(clippy::cast_sign_loss)]
2291 fn cmp_s_u(s: i128, u: u128) -> Ordering {
2294 } else if u > (i128::MAX as u128) {
2302 impl PartialEq for FullInt {
2304 fn eq(&self, other: &Self) -> bool {
2305 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
2309 impl PartialOrd for FullInt {
2311 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2312 Some(match (self, other) {
2313 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
2314 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
2315 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
2316 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
2321 impl Ord for FullInt {
2323 fn cmp(&self, other: &Self) -> Ordering {
2324 self.partial_cmp(other)
2325 .expect("`partial_cmp` for FullInt can never return `None`")
2329 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
2330 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2331 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
2332 let cast_ty = cx.typeck_results().expr_ty(expr);
2333 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
2334 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
2337 match pre_cast_ty.kind() {
2338 ty::Int(int_ty) => Some(match int_ty {
2339 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
2340 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
2341 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
2342 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
2343 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
2344 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
2346 ty::Uint(uint_ty) => Some(match uint_ty {
2347 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
2348 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
2349 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
2350 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
2351 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
2352 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
2361 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2362 let val = constant(cx, cx.typeck_results(), expr)?.0;
2363 if let Constant::Int(const_int) = val {
2364 match *cx.typeck_results().expr_ty(expr).kind() {
2365 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2366 ty::Uint(_) => Some(FullInt::U(const_int)),
2374 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
2375 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2378 INVALID_UPCAST_COMPARISONS,
2381 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2382 snippet(cx, cast_val.span, "the expression"),
2383 if always { "true" } else { "false" },
2389 fn upcast_comparison_bounds_err<'tcx>(
2390 cx: &LateContext<'tcx>,
2392 rel: comparisons::Rel,
2393 lhs_bounds: Option<(FullInt, FullInt)>,
2394 lhs: &'tcx Expr<'_>,
2395 rhs: &'tcx Expr<'_>,
2398 use crate::utils::comparisons::Rel;
2400 if let Some((lb, ub)) = lhs_bounds {
2401 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2402 if rel == Rel::Eq || rel == Rel::Ne {
2403 if norm_rhs_val < lb || norm_rhs_val > ub {
2404 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2406 } else if match rel {
2421 Rel::Eq | Rel::Ne => unreachable!(),
2423 err_upcast_comparison(cx, span, lhs, true)
2424 } else if match rel {
2439 Rel::Eq | Rel::Ne => unreachable!(),
2441 err_upcast_comparison(cx, span, lhs, false)
2447 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
2448 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2449 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2450 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2451 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2457 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2458 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2460 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2461 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2466 declare_clippy_lint! {
2467 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2468 /// over different hashers and implicitly defaulting to the default hashing
2469 /// algorithm (`SipHash`).
2471 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2474 /// **Known problems:** Suggestions for replacing constructors can contain
2475 /// false-positives. Also applying suggestions can require modification of other
2476 /// pieces of code, possibly including external crates.
2480 /// # use std::collections::HashMap;
2481 /// # use std::hash::{Hash, BuildHasher};
2482 /// # trait Serialize {};
2483 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2485 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2487 /// could be rewritten as
2489 /// # use std::collections::HashMap;
2490 /// # use std::hash::{Hash, BuildHasher};
2491 /// # trait Serialize {};
2492 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2494 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2496 pub IMPLICIT_HASHER,
2498 "missing generalization over different hashers"
2501 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2503 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
2504 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2505 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
2506 use rustc_span::BytePos;
2508 fn suggestion<'tcx>(
2509 cx: &LateContext<'tcx>,
2510 diag: &mut DiagnosticBuilder<'_>,
2511 generics_span: Span,
2512 generics_suggestion_span: Span,
2513 target: &ImplicitHasherType<'_>,
2514 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2516 let generics_snip = snippet(cx, generics_span, "");
2518 let generics_snip = if generics_snip.is_empty() {
2521 &generics_snip[1..generics_snip.len() - 1]
2526 "consider adding a type parameter",
2529 generics_suggestion_span,
2531 "<{}{}S: ::std::hash::BuildHasher{}>",
2533 if generics_snip.is_empty() { "" } else { ", " },
2534 if vis.suggestions.is_empty() {
2537 // request users to add `Default` bound so that generic constructors can be used
2544 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2549 if !vis.suggestions.is_empty() {
2550 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
2554 if !cx.access_levels.is_exported(item.hir_id) {
2565 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2568 for target in &vis.found {
2569 if differing_macro_contexts(item.span, target.span()) {
2573 let generics_suggestion_span = generics.span.substitute_dummy({
2574 let pos = snippet_opt(cx, item.span.until(target.span()))
2575 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2576 if let Some(pos) = pos {
2577 Span::new(pos, pos, item.span.data().ctxt)
2583 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2584 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2585 ctr_vis.visit_impl_item(item);
2593 "impl for `{}` should be generalized over different hashers",
2597 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2602 ItemKind::Fn(ref sig, ref generics, body_id) => {
2603 let body = cx.tcx.hir().body(body_id);
2605 for ty in sig.decl.inputs {
2606 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2609 for target in &vis.found {
2610 if in_external_macro(cx.sess(), generics.span) {
2613 let generics_suggestion_span = generics.span.substitute_dummy({
2614 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2616 let i = snip.find("fn")?;
2617 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2619 .expect("failed to create span for type parameters");
2620 Span::new(pos, pos, item.span.data().ctxt)
2623 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2624 ctr_vis.visit_body(body);
2631 "parameter of type `{}` should be generalized over different hashers",
2635 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2646 enum ImplicitHasherType<'tcx> {
2647 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2648 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2651 impl<'tcx> ImplicitHasherType<'tcx> {
2652 /// Checks that `ty` is a target type without a `BuildHasher`.
2653 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2654 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2655 let params: Vec<_> = path
2663 .filter_map(|arg| match arg {
2664 GenericArg::Type(ty) => Some(ty),
2668 let params_len = params.len();
2670 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2672 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2673 Some(ImplicitHasherType::HashMap(
2676 snippet(cx, params[0].span, "K"),
2677 snippet(cx, params[1].span, "V"),
2679 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2680 Some(ImplicitHasherType::HashSet(
2683 snippet(cx, params[0].span, "T"),
2693 fn type_name(&self) -> &'static str {
2695 ImplicitHasherType::HashMap(..) => "HashMap",
2696 ImplicitHasherType::HashSet(..) => "HashSet",
2700 fn type_arguments(&self) -> String {
2702 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2703 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2707 fn ty(&self) -> Ty<'tcx> {
2709 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2713 fn span(&self) -> Span {
2715 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2720 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2721 cx: &'a LateContext<'tcx>,
2722 found: Vec<ImplicitHasherType<'tcx>>,
2725 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2726 fn new(cx: &'a LateContext<'tcx>) -> Self {
2727 Self { cx, found: vec![] }
2731 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2732 type Map = Map<'tcx>;
2734 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2735 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2736 self.found.push(target);
2742 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2743 NestedVisitorMap::None
2747 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2748 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2749 cx: &'a LateContext<'tcx>,
2750 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
2751 target: &'b ImplicitHasherType<'tcx>,
2752 suggestions: BTreeMap<Span, String>,
2755 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2756 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2759 maybe_typeck_results: cx.maybe_typeck_results(),
2761 suggestions: BTreeMap::new(),
2766 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2767 type Map = Map<'tcx>;
2769 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2770 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
2771 walk_body(self, body);
2772 self.maybe_typeck_results = old_maybe_typeck_results;
2775 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2777 if let ExprKind::Call(ref fun, ref args) = e.kind;
2778 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2779 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2781 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
2785 if match_path(ty_path, &paths::HASHMAP) {
2786 if method.ident.name == sym::new {
2788 .insert(e.span, "HashMap::default()".to_string());
2789 } else if method.ident.name == sym!(with_capacity) {
2790 self.suggestions.insert(
2793 "HashMap::with_capacity_and_hasher({}, Default::default())",
2794 snippet(self.cx, args[0].span, "capacity"),
2798 } else if match_path(ty_path, &paths::HASHSET) {
2799 if method.ident.name == sym::new {
2801 .insert(e.span, "HashSet::default()".to_string());
2802 } else if method.ident.name == sym!(with_capacity) {
2803 self.suggestions.insert(
2806 "HashSet::with_capacity_and_hasher({}, Default::default())",
2807 snippet(self.cx, args[0].span, "capacity"),
2818 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2819 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2823 declare_clippy_lint! {
2824 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2826 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2827 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2830 /// **Known problems:** None.
2836 /// *(r as *const _ as *mut _) += 1;
2841 /// Instead consider using interior mutability types.
2844 /// use std::cell::UnsafeCell;
2846 /// fn x(r: &UnsafeCell<i32>) {
2852 pub CAST_REF_TO_MUT,
2854 "a cast of reference to a mutable pointer"
2857 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2859 impl<'tcx> LateLintPass<'tcx> for RefToMut {
2860 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2862 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2863 if let ExprKind::Cast(e, t) = &e.kind;
2864 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2865 if let ExprKind::Cast(e, t) = &e.kind;
2866 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2867 if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
2873 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",