1 #![allow(rustc::default_hash_types)]
7 mod redundant_allocation;
12 use std::cmp::Ordering;
13 use std::collections::BTreeMap;
15 use if_chain::if_chain;
16 use rustc_ast::{LitFloatType, LitIntType, LitKind};
17 use rustc_errors::{Applicability, DiagnosticBuilder};
19 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
21 BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericBounds, GenericParamKind, HirId,
22 ImplItem, ImplItemKind, Item, ItemKind, Lifetime, Lit, Local, MatchSource, MutTy, Mutability, Node, QPath, Stmt,
23 StmtKind, SyntheticTyParamKind, TraitFn, TraitItem, TraitItemKind, TyKind, UnOp,
25 use rustc_lint::{LateContext, LateLintPass, LintContext};
26 use rustc_middle::hir::map::Map;
27 use rustc_middle::lint::in_external_macro;
28 use rustc_middle::ty::{self, FloatTy, InferTy, IntTy, Ty, TyCtxt, TyS, TypeAndMut, TypeckResults, UintTy};
29 use rustc_semver::RustcVersion;
30 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
31 use rustc_span::hygiene::{ExpnKind, MacroKind};
32 use rustc_span::source_map::Span;
33 use rustc_span::symbol::sym;
34 use rustc_target::abi::LayoutOf;
35 use rustc_target::spec::abi::Abi;
36 use rustc_typeck::hir_ty_to_ty;
38 use crate::consts::{constant, Constant};
39 use crate::utils::paths;
40 use crate::utils::sugg::Sugg;
42 clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_hir_ty_cfg_dependant,
43 is_type_diagnostic_item, match_path, meets_msrv, method_chain_args, multispan_sugg,
44 numeric_literal::NumericLiteral, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability,
45 snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
48 declare_clippy_lint! {
49 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
50 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
52 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
53 /// the heap. So if you `Box` it, you just add another level of indirection
54 /// without any benefit whatsoever.
56 /// **Known problems:** None.
61 /// values: Box<Vec<Foo>>,
74 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
77 declare_clippy_lint! {
78 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
79 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
81 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
82 /// the heap. So if you `Box` its contents, you just add another level of indirection.
84 /// **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),
90 /// values: Vec<Box<i32>>,
103 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
106 declare_clippy_lint! {
107 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
110 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
111 /// represents an optional optional value which is logically the same thing as an optional
112 /// value but has an unneeded extra level of wrapping.
114 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
115 /// consider a custom `enum` instead, with clear names for each case.
117 /// **Known problems:** None.
121 /// fn get_data() -> Option<Option<u32>> {
129 /// pub enum Contents {
130 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
131 /// NotYetFetched, // Was Some(None)
132 /// None, // Was None
135 /// fn get_data() -> Contents {
141 "usage of `Option<Option<T>>`"
144 declare_clippy_lint! {
145 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
146 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
148 /// **Why is this bad?** Gankro says:
150 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
151 /// pointers and indirection.
152 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
154 /// > "only" amortized for push/pop, should be faster in the general case for
155 /// almost every possible
156 /// > workload, and isn't even amortized at all if you can predict the capacity
159 /// > `LinkedList`s are only really good if you're doing a lot of merging or
160 /// splitting of lists.
161 /// > This is because they can just mangle some pointers instead of actually
162 /// copying the data. Even
163 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
164 /// can still be better
165 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
167 /// **Known problems:** False positives – the instances where using a
168 /// `LinkedList` makes sense are few and far between, but they can still happen.
172 /// # use std::collections::LinkedList;
173 /// let x: LinkedList<usize> = LinkedList::new();
177 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
180 declare_clippy_lint! {
181 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
182 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
184 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
187 /// **Known problems:** None.
191 /// fn foo(bar: &Box<T>) { ... }
197 /// fn foo(bar: &T) { ... }
201 "a borrow of a boxed type"
204 declare_clippy_lint! {
205 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
207 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
208 /// add an unnecessary level of indirection.
210 /// **Known problems:** None.
214 /// # use std::rc::Rc;
215 /// fn foo(bar: Rc<&usize>) {}
221 /// fn foo(bar: &usize) {}
223 pub REDUNDANT_ALLOCATION,
225 "redundant allocation"
228 declare_clippy_lint! {
229 /// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
231 /// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
232 /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
234 /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
235 /// works if there are no additional references yet, which usually defeats the purpose of
236 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
237 /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
240 /// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
241 /// cases where mutation only happens before there are any additional references.
245 /// # use std::rc::Rc;
246 /// fn foo(interned: Rc<String>) { ... }
252 /// fn foo(interned: Rc<str>) { ... }
256 "shared ownership of a buffer type"
260 vec_box_size_threshold: u64,
263 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
265 impl<'tcx> LateLintPass<'tcx> for Types {
266 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
267 // Skip trait implementations; see issue #605.
268 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
269 if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
274 self.check_fn_decl(cx, decl);
277 fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) {
278 self.check_ty(cx, &field.ty, false);
281 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
283 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
284 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
289 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
290 if let Some(ref ty) = local.ty {
291 self.check_ty(cx, ty, true);
297 pub fn new(vec_box_size_threshold: u64) -> Self {
298 Self { vec_box_size_threshold }
301 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
302 for input in decl.inputs {
303 self.check_ty(cx, input, false);
306 if let FnRetTy::Return(ref ty) = decl.output {
307 self.check_ty(cx, ty, false);
311 /// Recursively check for `TypePass` lints in the given type. Stop at the first
314 /// The parameter `is_local` distinguishes the context of the type; types from
315 /// local bindings should only be checked for the `BORROWED_BOX` lint.
316 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
317 if hir_ty.span.from_expansion() {
321 TyKind::Path(ref qpath) if !is_local => {
322 let hir_id = hir_ty.hir_id;
323 let res = cx.qpath_res(qpath, hir_id);
324 if let Some(def_id) = res.opt_def_id() {
325 let mut triggered = false;
326 triggered |= box_vec::check(cx, hir_ty, qpath, def_id);
327 triggered |= redundant_allocation::check(cx, hir_ty, qpath, def_id);
328 triggered |= rc_buffer::check(cx, hir_ty, qpath, def_id);
329 triggered |= vec_box::check(cx, hir_ty, qpath, def_id, self.vec_box_size_threshold);
330 triggered |= option_option::check(cx, hir_ty, qpath, def_id);
331 triggered |= linked_list::check(cx, hir_ty, def_id);
338 QPath::Resolved(Some(ref ty), ref p) => {
339 self.check_ty(cx, ty, is_local);
340 for ty in p.segments.iter().flat_map(|seg| {
343 .map_or_else(|| [].iter(), |params| params.args.iter())
344 .filter_map(|arg| match arg {
345 GenericArg::Type(ty) => Some(ty),
349 self.check_ty(cx, ty, is_local);
352 QPath::Resolved(None, ref p) => {
353 for ty in p.segments.iter().flat_map(|seg| {
356 .map_or_else(|| [].iter(), |params| params.args.iter())
357 .filter_map(|arg| match arg {
358 GenericArg::Type(ty) => Some(ty),
362 self.check_ty(cx, ty, is_local);
365 QPath::TypeRelative(ref ty, ref seg) => {
366 self.check_ty(cx, ty, is_local);
367 if let Some(ref params) = seg.args {
368 for ty in params.args.iter().filter_map(|arg| match arg {
369 GenericArg::Type(ty) => Some(ty),
372 self.check_ty(cx, ty, is_local);
376 QPath::LangItem(..) => {},
379 TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
380 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
381 self.check_ty(cx, ty, is_local)
383 TyKind::Tup(tys) => {
385 self.check_ty(cx, ty, is_local);
394 cx: &LateContext<'_>,
395 hir_ty: &hir::Ty<'_>,
400 match mut_ty.ty.kind {
401 TyKind::Path(ref qpath) => {
402 let hir_id = mut_ty.ty.hir_id;
403 let def = cx.qpath_res(qpath, hir_id);
405 if let Some(def_id) = def.opt_def_id();
406 if Some(def_id) == cx.tcx.lang_items().owned_box();
407 if let QPath::Resolved(None, ref path) = *qpath;
408 if let [ref bx] = *path.segments;
409 if let Some(ref params) = bx.args;
410 if !params.parenthesized;
411 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
412 GenericArg::Type(ty) => Some(ty),
416 if is_any_trait(inner) {
417 // Ignore `Box<Any>` types; see issue #1884 for details.
421 let ltopt = if lt.is_elided() {
424 format!("{} ", lt.name.ident().as_str())
427 if mut_ty.mutbl == Mutability::Mut {
428 // Ignore `&mut Box<T>` types; see issue #2907 for
433 // When trait objects or opaque types have lifetime or auto-trait bounds,
434 // we need to add parentheses to avoid a syntax error due to its ambiguity.
435 // Originally reported as the issue #3128.
436 let inner_snippet = snippet(cx, inner.span, "..");
437 let suggestion = match &inner.kind {
438 TyKind::TraitObject(bounds, lt_bound) if bounds.len() > 1 || !lt_bound.is_elided() => {
439 format!("&{}({})", ltopt, &inner_snippet)
442 if get_bounds_if_impl_trait(cx, qpath, inner.hir_id)
443 .map_or(false, |bounds| bounds.len() > 1) =>
445 format!("&{}({})", ltopt, &inner_snippet)
447 _ => format!("&{}{}", ltopt, &inner_snippet),
453 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
456 // To make this `MachineApplicable`, at least one needs to check if it isn't a trait item
457 // because the trait impls of it will break otherwise;
458 // and there may be other cases that result in invalid code.
459 // For example, type coercion doesn't work nicely.
460 Applicability::Unspecified,
462 return; // don't recurse into the type
465 self.check_ty(cx, &mut_ty.ty, is_local);
467 _ => self.check_ty(cx, &mut_ty.ty, is_local),
472 // Returns true if given type is `Any` trait.
473 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
475 if let TyKind::TraitObject(ref traits, _) = t.kind;
476 if !traits.is_empty();
477 // Only Send/Sync can be used as additional traits, so it is enough to
478 // check only the first trait.
479 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
488 fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: HirId) -> Option<GenericBounds<'tcx>> {
490 if let Some(did) = cx.qpath_res(qpath, id).opt_def_id();
491 if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did);
492 if let GenericParamKind::Type { synthetic, .. } = generic_param.kind;
493 if synthetic == Some(SyntheticTyParamKind::ImplTrait);
495 Some(generic_param.bounds)
502 declare_clippy_lint! {
503 /// **What it does:** Checks for binding a unit value.
505 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
506 /// binding one is kind of pointless.
508 /// **Known problems:** None.
518 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
521 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
523 impl<'tcx> LateLintPass<'tcx> for LetUnitValue {
524 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
525 if let StmtKind::Local(ref local) = stmt.kind {
526 if is_unit(cx.typeck_results().pat_ty(&local.pat)) {
527 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
530 if higher::is_from_for_desugar(local) {
537 "this let-binding has unit value",
539 if let Some(expr) = &local.init {
540 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
541 diag.span_suggestion(
543 "omit the `let` binding",
544 format!("{};", snip),
545 Applicability::MachineApplicable, // snippet
555 declare_clippy_lint! {
556 /// **What it does:** Checks for comparisons to unit. This includes all binary
557 /// comparisons (like `==` and `<`) and asserts.
559 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
560 /// clumsily written constant. Mostly this happens when someone accidentally
561 /// adds semicolons at the end of the operands.
563 /// **Known problems:** None.
594 /// assert_eq!({ foo(); }, { bar(); });
596 /// will always succeed
599 "comparing unit values"
602 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
604 impl<'tcx> LateLintPass<'tcx> for UnitCmp {
605 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
606 if expr.span.from_expansion() {
607 if let Some(callee) = expr.span.source_callee() {
608 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
609 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
611 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
612 let result = match &*symbol.as_str() {
613 "assert_eq" | "debug_assert_eq" => "succeed",
614 "assert_ne" | "debug_assert_ne" => "fail",
622 "`{}` of unit values detected. This will always {}",
633 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
635 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
636 let result = match op {
637 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
645 "{}-comparison of unit values detected. This will always be {}",
655 declare_clippy_lint! {
656 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
657 /// unit literal (`()`).
659 /// **Why is this bad?** This is likely the result of an accidental semicolon.
661 /// **Known problems:** None.
672 "passing unit to a function"
675 declare_lint_pass!(UnitArg => [UNIT_ARG]);
677 impl<'tcx> LateLintPass<'tcx> for UnitArg {
678 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
679 if expr.span.from_expansion() {
683 // apparently stuff in the desugaring of `?` can trigger this
684 // so check for that here
685 // only the calls to `Try::from_error` is marked as desugared,
686 // so we need to check both the current Expr and its parent.
687 if is_questionmark_desugar_marked_call(expr) {
691 let map = &cx.tcx.hir();
692 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
693 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
694 if is_questionmark_desugar_marked_call(parent_expr);
701 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => {
702 let args_to_recover = args
705 if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) {
708 ExprKind::Match(.., MatchSource::TryDesugar) | ExprKind::Path(..)
714 .collect::<Vec<_>>();
715 if !args_to_recover.is_empty() {
716 lint_unit_args(cx, expr, &args_to_recover);
724 fn fmt_stmts_and_call(
725 cx: &LateContext<'_>,
726 call_expr: &Expr<'_>,
728 args_snippets: &[impl AsRef<str>],
729 non_empty_block_args_snippets: &[impl AsRef<str>],
731 let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
732 let call_snippet_with_replacements = args_snippets
734 .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
736 let mut stmts_and_call = non_empty_block_args_snippets
738 .map(|it| it.as_ref().to_owned())
739 .collect::<Vec<_>>();
740 stmts_and_call.push(call_snippet_with_replacements);
741 stmts_and_call = stmts_and_call
743 .map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
746 let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
747 // expr is not in a block statement or result expression position, wrap in a block
748 let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
749 if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
750 let block_indent = call_expr_indent + 4;
751 stmts_and_call_snippet =
752 reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
753 stmts_and_call_snippet = format!(
755 " ".repeat(block_indent),
756 &stmts_and_call_snippet,
757 " ".repeat(call_expr_indent)
760 stmts_and_call_snippet
763 fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
764 let mut applicability = Applicability::MachineApplicable;
765 let (singular, plural) = if args_to_recover.len() > 1 {
774 &format!("passing {}unit value{} to a function", singular, plural),
781 if let ExprKind::Block(block, _) = arg.kind;
782 if block.expr.is_none();
783 if let Some(last_stmt) = block.stmts.iter().last();
784 if let StmtKind::Semi(last_expr) = last_stmt.kind;
785 if let Some(snip) = snippet_opt(cx, last_expr.span);
797 .for_each(|(span, sugg)| {
800 "remove the semicolon from the last statement in the block",
802 Applicability::MaybeIncorrect,
805 applicability = Applicability::MaybeIncorrect;
808 let arg_snippets: Vec<String> = args_to_recover
810 .filter_map(|arg| snippet_opt(cx, arg.span))
812 let arg_snippets_without_empty_blocks: Vec<String> = args_to_recover
814 .filter(|arg| !is_empty_block(arg))
815 .filter_map(|arg| snippet_opt(cx, arg.span))
818 if let Some(call_snippet) = snippet_opt(cx, expr.span) {
819 let sugg = fmt_stmts_and_call(
824 &arg_snippets_without_empty_blocks,
827 if arg_snippets_without_empty_blocks.is_empty() {
828 db.multipart_suggestion(
829 &format!("use {}unit literal{} instead", singular, plural),
832 .map(|arg| (arg.span, "()".to_string()))
833 .collect::<Vec<_>>(),
837 let plural = arg_snippets_without_empty_blocks.len() > 1;
838 let empty_or_s = if plural { "s" } else { "" };
839 let it_or_them = if plural { "them" } else { "it" };
843 "{}move the expression{} in front of the call and replace {} with the unit literal `()`",
844 or, empty_or_s, it_or_them
855 fn is_empty_block(expr: &Expr<'_>) -> bool {
869 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
870 use rustc_span::hygiene::DesugaringKind;
871 if let ExprKind::Call(ref callee, _) = expr.kind {
872 callee.span.is_desugaring(DesugaringKind::QuestionMark)
878 fn is_unit(ty: Ty<'_>) -> bool {
879 matches!(ty.kind(), ty::Tuple(slice) if slice.is_empty())
882 fn is_unit_literal(expr: &Expr<'_>) -> bool {
883 matches!(expr.kind, ExprKind::Tup(ref slice) if slice.is_empty())
886 declare_clippy_lint! {
887 /// **What it does:** Checks for casts from any numerical to a float type where
888 /// the receiving type cannot store all values from the original type without
889 /// rounding errors. This possible rounding is to be expected, so this lint is
890 /// `Allow` by default.
892 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
893 /// or any 64-bit integer to `f64`.
895 /// **Why is this bad?** It's not bad at all. But in some applications it can be
896 /// helpful to know where precision loss can take place. This lint can help find
897 /// those places in the code.
899 /// **Known problems:** None.
903 /// let x = u64::MAX;
906 pub CAST_PRECISION_LOSS,
908 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
911 declare_clippy_lint! {
912 /// **What it does:** Checks for casts from a signed to an unsigned numerical
913 /// type. In this case, negative values wrap around to large positive values,
914 /// which can be quite surprising in practice. However, as the cast works as
915 /// defined, this lint is `Allow` by default.
917 /// **Why is this bad?** Possibly surprising results. You can activate this lint
918 /// as a one-time check to see where numerical wrapping can arise.
920 /// **Known problems:** None.
925 /// y as u128; // will return 18446744073709551615
929 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
932 declare_clippy_lint! {
933 /// **What it does:** Checks for casts between numerical types that may
934 /// truncate large values. This is expected behavior, so the cast is `Allow` by
937 /// **Why is this bad?** In some problem domains, it is good practice to avoid
938 /// truncation. This lint can be activated to help assess where additional
939 /// checks could be beneficial.
941 /// **Known problems:** None.
945 /// fn as_u8(x: u64) -> u8 {
949 pub CAST_POSSIBLE_TRUNCATION,
951 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
954 declare_clippy_lint! {
955 /// **What it does:** Checks for casts from an unsigned type to a signed type of
956 /// the same size. Performing such a cast is a 'no-op' for the compiler,
957 /// i.e., nothing is changed at the bit level, and the binary representation of
958 /// the value is reinterpreted. This can cause wrapping if the value is too big
959 /// for the target signed type. However, the cast works as defined, so this lint
960 /// is `Allow` by default.
962 /// **Why is this bad?** While such a cast is not bad in itself, the results can
963 /// be surprising when this is not the intended behavior, as demonstrated by the
966 /// **Known problems:** None.
970 /// u32::MAX as i32; // will yield a value of `-1`
972 pub CAST_POSSIBLE_WRAP,
974 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
977 declare_clippy_lint! {
978 /// **What it does:** Checks for casts between numerical types that may
979 /// be replaced by safe conversion functions.
981 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
982 /// conversions, including silently lossy conversions. Conversion functions such
983 /// as `i32::from` will only perform lossless conversions. Using the conversion
984 /// functions prevents conversions from turning into silent lossy conversions if
985 /// the types of the input expressions ever change, and make it easier for
986 /// people reading the code to know that the conversion is lossless.
988 /// **Known problems:** None.
992 /// fn as_u64(x: u8) -> u64 {
997 /// Using `::from` would look like this:
1000 /// fn as_u64(x: u8) -> u64 {
1006 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
1009 declare_clippy_lint! {
1010 /// **What it does:** Checks for casts to the same type, casts of int literals to integer types
1011 /// and casts of float literals to float types.
1013 /// **Why is this bad?** It's just unnecessary.
1015 /// **Known problems:** None.
1019 /// let _ = 2i32 as i32;
1020 /// let _ = 0.5 as f32;
1027 /// let _ = 0.5_f32;
1029 pub UNNECESSARY_CAST,
1031 "cast to the same type, e.g., `x as i32` where `x: i32`"
1034 declare_clippy_lint! {
1035 /// **What it does:** Checks for casts, using `as` or `pointer::cast`,
1036 /// from a less-strictly-aligned pointer to a more-strictly-aligned pointer
1038 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
1041 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
1042 /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
1043 /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
1047 /// let _ = (&1u8 as *const u8) as *const u16;
1048 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
1050 /// (&1u8 as *const u8).cast::<u16>();
1051 /// (&mut 1u8 as *mut u8).cast::<u16>();
1053 pub CAST_PTR_ALIGNMENT,
1055 "cast from a pointer to a more-strictly-aligned pointer"
1058 declare_clippy_lint! {
1059 /// **What it does:** Checks for casts of function pointers to something other than usize
1061 /// **Why is this bad?**
1062 /// Casting a function pointer to anything other than usize/isize is not portable across
1063 /// architectures, because you end up losing bits if the target type is too small or end up with a
1064 /// bunch of extra bits that waste space and add more instructions to the final binary than
1065 /// strictly necessary for the problem
1067 /// Casting to isize also doesn't make sense since there are no signed addresses.
1073 /// fn fun() -> i32 { 1 }
1074 /// let a = fun as i64;
1077 /// fn fun2() -> i32 { 1 }
1078 /// let a = fun2 as usize;
1080 pub FN_TO_NUMERIC_CAST,
1082 "casting a function pointer to a numeric type other than usize"
1085 declare_clippy_lint! {
1086 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1089 /// **Why is this bad?**
1090 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1091 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1092 /// a comment) to perform the truncation.
1098 /// fn fn1() -> i16 {
1101 /// let _ = fn1 as i32;
1103 /// // Better: Cast to usize first, then comment with the reason for the truncation
1104 /// fn fn2() -> i16 {
1107 /// let fn_ptr = fn2 as usize;
1108 /// let fn_ptr_truncated = fn_ptr as i32;
1110 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1112 "casting a function pointer to a numeric type not wide enough to store the address"
1115 /// Returns the size in bits of an integral type.
1116 /// Will return 0 if the type is not an int or uint variant
1117 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1119 ty::Int(i) => match i {
1120 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1127 ty::Uint(i) => match i {
1128 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1133 UintTy::U128 => 128,
1139 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1140 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
1143 fn span_precision_loss_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1144 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1145 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1146 let arch_dependent_str = "on targets with 64-bit wide pointers ";
1147 let from_nbits_str = if arch_dependent {
1149 } else if is_isize_or_usize(cast_from) {
1150 "32 or 64".to_owned()
1152 int_ty_to_nbits(cast_from, cx.tcx).to_string()
1156 CAST_PRECISION_LOSS,
1159 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1160 but `{1}`'s mantissa is only {4} bits wide)",
1162 if cast_to_f64 { "f64" } else { "f32" },
1163 if arch_dependent { arch_dependent_str } else { "" },
1170 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1171 if let ExprKind::Binary(_, _, _) = op.kind {
1172 if snip.starts_with('(') && snip.ends_with(')') {
1179 fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1180 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1181 if in_constant(cx, expr.hir_id) {
1184 // The suggestion is to use a function call, so if the original expression
1185 // has parens on the outside, they are no longer needed.
1186 let mut applicability = Applicability::MachineApplicable;
1187 let opt = snippet_opt(cx, op.span);
1188 let sugg = opt.as_ref().map_or_else(
1190 applicability = Applicability::HasPlaceholders;
1194 if should_strip_parens(op, snip) {
1195 &snip[1..snip.len() - 1]
1207 "casting `{}` to `{}` may become silently lossy if you later change the type",
1211 format!("{}::from({})", cast_to, sugg),
1222 fn check_loss_of_sign(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1223 if !cast_from.is_signed() || cast_to.is_signed() {
1227 // don't lint for positive constants
1228 let const_val = constant(cx, &cx.typeck_results(), op);
1230 if let Some((Constant::Int(n), _)) = const_val;
1231 if let ty::Int(ity) = *cast_from.kind();
1232 if sext(cx.tcx, n, ity) >= 0;
1238 // don't lint for the result of methods that always return non-negative values
1239 if let ExprKind::MethodCall(ref path, _, _, _) = op.kind {
1240 let mut method_name = path.ident.name.as_str();
1241 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1244 if method_name == "unwrap";
1245 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1246 if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
1248 method_name = inner_path.ident.name.as_str();
1252 if allowed_methods.iter().any(|&name| method_name == name) {
1262 "casting `{}` to `{}` may lose the sign of the value",
1268 fn check_truncation_and_wrapping(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1269 let arch_64_suffix = " on targets with 64-bit wide pointers";
1270 let arch_32_suffix = " on targets with 32-bit wide pointers";
1271 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1272 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1273 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1274 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1275 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1276 (true, true) | (false, false) => (
1277 to_nbits < from_nbits,
1279 to_nbits == from_nbits && cast_unsigned_to_signed,
1289 to_nbits <= 32 && cast_unsigned_to_signed,
1295 cast_unsigned_to_signed,
1296 if from_nbits == 64 {
1303 if span_truncation {
1306 CAST_POSSIBLE_TRUNCATION,
1309 "casting `{}` to `{}` may truncate the value{}",
1312 match suffix_truncation {
1313 ArchSuffix::_32 => arch_32_suffix,
1314 ArchSuffix::_64 => arch_64_suffix,
1315 ArchSuffix::None => "",
1326 "casting `{}` to `{}` may wrap around the value{}",
1330 ArchSuffix::_32 => arch_32_suffix,
1331 ArchSuffix::_64 => arch_64_suffix,
1332 ArchSuffix::None => "",
1339 fn check_lossless(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1340 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1341 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1342 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1343 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1345 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1349 declare_lint_pass!(Casts => [
1350 CAST_PRECISION_LOSS,
1352 CAST_POSSIBLE_TRUNCATION,
1358 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1361 // Check if the given type is either `core::ffi::c_void` or
1362 // one of the platform specific `libc::<platform>::c_void` of libc.
1363 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
1364 if let ty::Adt(adt, _) = ty.kind() {
1365 let names = cx.get_def_path(adt.did);
1367 if names.is_empty() {
1370 if names[0] == sym::libc || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1377 /// Returns the mantissa bits wide of a fp type.
1378 /// Will return 0 if the type is not a fp
1379 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1381 ty::Float(FloatTy::F32) => 23,
1382 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1387 impl<'tcx> LateLintPass<'tcx> for Casts {
1388 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1389 if expr.span.from_expansion() {
1392 if let ExprKind::Cast(ref ex, cast_to) = expr.kind {
1393 if is_hir_ty_cfg_dependant(cx, cast_to) {
1396 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
1397 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1398 if let Some(lit) = get_numeric_literal(ex) {
1399 let literal_str = snippet_opt(cx, ex.span).unwrap_or_default();
1402 if let LitKind::Int(n, _) = lit.node;
1403 if let Some(src) = snippet_opt(cx, lit.span);
1404 if cast_to.is_floating_point();
1405 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1406 let from_nbits = 128 - n.leading_zeros();
1407 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1408 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1410 let literal_str = if is_unary_neg(ex) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
1411 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1417 LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
1418 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1420 LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
1421 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1423 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1425 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
1431 "casting to the same type is unnecessary (`{}` -> `{}`)",
1439 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1440 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1443 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1444 } else if let ExprKind::MethodCall(method_path, _, args, _) = expr.kind {
1446 if method_path.ident.name == sym!(cast);
1447 if let Some(generic_args) = method_path.args;
1448 if let [GenericArg::Type(cast_to)] = generic_args.args;
1449 // There probably is no obvious reason to do this, just to be consistent with `as` cases.
1450 if !is_hir_ty_cfg_dependant(cx, cast_to);
1452 let (cast_from, cast_to) =
1453 (cx.typeck_results().expr_ty(&args[0]), cx.typeck_results().expr_ty(expr));
1454 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1461 fn is_unary_neg(expr: &Expr<'_>) -> bool {
1462 matches!(expr.kind, ExprKind::Unary(UnOp::Neg, _))
1465 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
1467 ExprKind::Lit(ref lit) => Some(lit),
1468 ExprKind::Unary(UnOp::Neg, e) => {
1469 if let ExprKind::Lit(ref lit) = e.kind {
1479 fn show_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1480 let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
1485 &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
1487 format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
1488 Applicability::MachineApplicable,
1492 fn lint_numeric_casts<'tcx>(
1493 cx: &LateContext<'tcx>,
1495 cast_expr: &Expr<'_>,
1496 cast_from: Ty<'tcx>,
1499 match (cast_from.is_integral(), cast_to.is_integral()) {
1501 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1502 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
1507 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1508 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1510 if from_nbits < to_nbits {
1511 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1517 CAST_POSSIBLE_TRUNCATION,
1519 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1521 if !cast_to.is_signed() {
1527 "casting `{}` to `{}` may lose the sign of the value",
1534 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1535 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1536 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1539 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
1542 CAST_POSSIBLE_TRUNCATION,
1544 "casting `f64` to `f32` may truncate the value",
1547 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
1548 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1554 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1556 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
1557 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
1558 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1559 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1560 if from_layout.align.abi < to_layout.align.abi;
1561 // with c_void, we inherently need to trust the user
1562 if !is_c_void(cx, from_ptr_ty.ty);
1563 // when casting from a ZST, we don't know enough to properly lint
1564 if !from_layout.is_zst();
1571 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1574 from_layout.align.abi.bytes(),
1575 to_layout.align.abi.bytes(),
1582 fn lint_fn_to_numeric_cast(
1583 cx: &LateContext<'_>,
1585 cast_expr: &Expr<'_>,
1589 // We only want to check casts to `ty::Uint` or `ty::Int`
1590 match cast_to.kind() {
1591 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1594 match cast_from.kind() {
1595 ty::FnDef(..) | ty::FnPtr(_) => {
1596 let mut applicability = Applicability::MaybeIncorrect;
1597 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1599 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1600 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1603 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1606 "casting function pointer `{}` to `{}`, which truncates the value",
1607 from_snippet, cast_to
1610 format!("{} as usize", from_snippet),
1613 } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
1618 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1620 format!("{} as usize", from_snippet),
1629 declare_clippy_lint! {
1630 /// **What it does:** Checks for types used in structs, parameters and `let`
1631 /// declarations above a certain complexity threshold.
1633 /// **Why is this bad?** Too complex types make the code less readable. Consider
1634 /// using a `type` definition to simplify them.
1636 /// **Known problems:** None.
1640 /// # use std::rc::Rc;
1642 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1645 pub TYPE_COMPLEXITY,
1647 "usage of very complex types that might be better factored into `type` definitions"
1650 pub struct TypeComplexity {
1654 impl TypeComplexity {
1656 pub fn new(threshold: u64) -> Self {
1661 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1663 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
1666 cx: &LateContext<'tcx>,
1668 decl: &'tcx FnDecl<'_>,
1673 self.check_fndecl(cx, decl);
1676 fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
1677 // enum variants are also struct fields now
1678 self.check_type(cx, &field.ty);
1681 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1683 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1684 // functions, enums, structs, impls and traits are covered
1689 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1691 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1692 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1693 // methods with default impl are covered by check_fn
1698 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
1700 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1701 // methods are covered by check_fn
1706 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
1707 if let Some(ref ty) = local.ty {
1708 self.check_type(cx, ty);
1713 impl<'tcx> TypeComplexity {
1714 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
1715 for arg in decl.inputs {
1716 self.check_type(cx, arg);
1718 if let FnRetTy::Return(ref ty) = decl.output {
1719 self.check_type(cx, ty);
1723 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
1724 if ty.span.from_expansion() {
1728 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1729 visitor.visit_ty(ty);
1733 if score > self.threshold {
1738 "very complex type used. Consider factoring parts into `type` definitions",
1744 /// Walks a type and assigns a complexity score to it.
1745 struct TypeComplexityVisitor {
1746 /// total complexity score of the type
1748 /// current nesting level
1752 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1753 type Map = Map<'tcx>;
1755 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1756 let (add_score, sub_nest) = match ty.kind {
1757 // _, &x and *x have only small overhead; don't mess with nesting level
1758 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1760 // the "normal" components of a type: named types, arrays/tuples
1761 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1763 // function types bring a lot of overhead
1764 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1766 TyKind::TraitObject(ref param_bounds, _) => {
1767 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1769 .bound_generic_params
1771 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
1773 if has_lifetime_parameters {
1774 // complex trait bounds like A<'a, 'b>
1777 // simple trait bounds like A + B
1784 self.score += add_score;
1785 self.nest += sub_nest;
1787 self.nest -= sub_nest;
1789 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1790 NestedVisitorMap::None
1794 declare_clippy_lint! {
1795 /// **What it does:** Checks for expressions where a character literal is cast
1796 /// to `u8` and suggests using a byte literal instead.
1798 /// **Why is this bad?** In general, casting values to smaller types is
1799 /// error-prone and should be avoided where possible. In the particular case of
1800 /// converting a character literal to u8, it is easy to avoid by just using a
1801 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1802 /// than `'a' as u8`.
1804 /// **Known problems:** None.
1811 /// A better version, using the byte literal:
1818 "casting a character literal to `u8` truncates"
1821 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1823 impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
1824 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1826 if !expr.span.from_expansion();
1827 if let ExprKind::Cast(e, _) = &expr.kind;
1828 if let ExprKind::Lit(l) = &e.kind;
1829 if let LitKind::Char(c) = l.node;
1830 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
1832 let mut applicability = Applicability::MachineApplicable;
1833 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
1839 "casting a character literal to `u8` truncates",
1841 diag.note("`char` is four bytes wide, but `u8` is a single byte");
1844 diag.span_suggestion(
1846 "use a byte literal instead",
1847 format!("b{}", snippet),
1857 declare_clippy_lint! {
1858 /// **What it does:** Checks for comparisons where one side of the relation is
1859 /// either the minimum or maximum value for its type and warns if it involves a
1860 /// case that is always true or always false. Only integer and boolean types are
1863 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1864 /// that it is possible for `x` to be less than the minimum. Expressions like
1865 /// `max < x` are probably mistakes.
1867 /// **Known problems:** For `usize` the size of the current compile target will
1868 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1869 /// a comparison to detect target pointer width will trigger this lint. One can
1870 /// use `mem::sizeof` and compare its value or conditional compilation
1872 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1877 /// let vec: Vec<isize> = Vec::new();
1878 /// if vec.len() <= 0 {}
1879 /// if 100 > i32::MAX {}
1881 pub ABSURD_EXTREME_COMPARISONS,
1883 "a comparison with a maximum or minimum value that is always true or false"
1886 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1893 struct ExtremeExpr<'a> {
1898 enum AbsurdComparisonResult {
1901 InequalityImpossible,
1904 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1905 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1906 let precast_ty = cx.typeck_results().expr_ty(cast_exp);
1907 let cast_ty = cx.typeck_results().expr_ty(expr);
1909 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1915 fn detect_absurd_comparison<'tcx>(
1916 cx: &LateContext<'tcx>,
1918 lhs: &'tcx Expr<'_>,
1919 rhs: &'tcx Expr<'_>,
1920 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1921 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
1922 use crate::types::ExtremeType::{Maximum, Minimum};
1923 use crate::utils::comparisons::{normalize_comparison, Rel};
1925 // absurd comparison only makes sense on primitive types
1926 // primitive types don't implement comparison operators with each other
1927 if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
1931 // comparisons between fix sized types and target sized types are considered unanalyzable
1932 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1936 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
1938 let lx = detect_extreme_expr(cx, normalized_lhs);
1939 let rx = detect_extreme_expr(cx, normalized_rhs);
1944 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1945 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1951 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1952 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1953 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1954 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1958 Rel::Ne | Rel::Eq => return None,
1962 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
1963 use crate::types::ExtremeType::{Maximum, Minimum};
1965 let ty = cx.typeck_results().expr_ty(expr);
1967 let cv = constant(cx, cx.typeck_results(), expr)?.0;
1969 let which = match (ty.kind(), cv) {
1970 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1971 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
1975 (&ty::Bool, Constant::Bool(true)) => Maximum,
1976 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
1979 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
1983 Some(ExtremeExpr { which, expr })
1986 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
1987 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1988 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
1989 use crate::types::ExtremeType::{Maximum, Minimum};
1991 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
1992 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1993 if !expr.span.from_expansion() {
1994 let msg = "this comparison involving the minimum or maximum element for this \
1995 type contains a case that is always true or always false";
1997 let conclusion = match result {
1998 AlwaysFalse => "this comparison is always false".to_owned(),
1999 AlwaysTrue => "this comparison is always true".to_owned(),
2000 InequalityImpossible => format!(
2001 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
2003 snippet(cx, lhs.span, "lhs"),
2004 snippet(cx, rhs.span, "rhs")
2009 "because `{}` is the {} value for this type, {}",
2010 snippet(cx, culprit.expr.span, "x"),
2011 match culprit.which {
2012 Minimum => "minimum",
2013 Maximum => "maximum",
2018 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
2025 declare_clippy_lint! {
2026 /// **What it does:** Checks for comparisons where the relation is always either
2027 /// true or false, but where one side has been upcast so that the comparison is
2028 /// necessary. Only integer types are checked.
2030 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
2031 /// will mistakenly imply that it is possible for `x` to be outside the range of
2034 /// **Known problems:**
2035 /// https://github.com/rust-lang/rust-clippy/issues/886
2040 /// (x as u32) > 300;
2042 pub INVALID_UPCAST_COMPARISONS,
2044 "a comparison involving an upcast which is always true or false"
2047 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
2049 #[derive(Copy, Clone, Debug, Eq)]
2056 #[allow(clippy::cast_sign_loss)]
2058 fn cmp_s_u(s: i128, u: u128) -> Ordering {
2061 } else if u > (i128::MAX as u128) {
2069 impl PartialEq for FullInt {
2071 fn eq(&self, other: &Self) -> bool {
2072 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
2076 impl PartialOrd for FullInt {
2078 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2079 Some(match (self, other) {
2080 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
2081 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
2082 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
2083 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
2088 impl Ord for FullInt {
2090 fn cmp(&self, other: &Self) -> Ordering {
2091 self.partial_cmp(other)
2092 .expect("`partial_cmp` for FullInt can never return `None`")
2096 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
2097 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2098 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
2099 let cast_ty = cx.typeck_results().expr_ty(expr);
2100 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
2101 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
2104 match pre_cast_ty.kind() {
2105 ty::Int(int_ty) => Some(match int_ty {
2106 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
2107 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
2108 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
2109 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
2110 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
2111 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
2113 ty::Uint(uint_ty) => Some(match uint_ty {
2114 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
2115 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
2116 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
2117 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
2118 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
2119 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
2128 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2129 let val = constant(cx, cx.typeck_results(), expr)?.0;
2130 if let Constant::Int(const_int) = val {
2131 match *cx.typeck_results().expr_ty(expr).kind() {
2132 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2133 ty::Uint(_) => Some(FullInt::U(const_int)),
2141 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
2142 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2145 INVALID_UPCAST_COMPARISONS,
2148 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2149 snippet(cx, cast_val.span, "the expression"),
2150 if always { "true" } else { "false" },
2156 fn upcast_comparison_bounds_err<'tcx>(
2157 cx: &LateContext<'tcx>,
2159 rel: comparisons::Rel,
2160 lhs_bounds: Option<(FullInt, FullInt)>,
2161 lhs: &'tcx Expr<'_>,
2162 rhs: &'tcx Expr<'_>,
2165 use crate::utils::comparisons::Rel;
2167 if let Some((lb, ub)) = lhs_bounds {
2168 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2169 if rel == Rel::Eq || rel == Rel::Ne {
2170 if norm_rhs_val < lb || norm_rhs_val > ub {
2171 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2173 } else if match rel {
2188 Rel::Eq | Rel::Ne => unreachable!(),
2190 err_upcast_comparison(cx, span, lhs, true)
2191 } else if match rel {
2206 Rel::Eq | Rel::Ne => unreachable!(),
2208 err_upcast_comparison(cx, span, lhs, false)
2214 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
2215 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2216 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2217 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2218 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2224 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2225 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2227 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2228 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2233 declare_clippy_lint! {
2234 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2235 /// over different hashers and implicitly defaulting to the default hashing
2236 /// algorithm (`SipHash`).
2238 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2241 /// **Known problems:** Suggestions for replacing constructors can contain
2242 /// false-positives. Also applying suggestions can require modification of other
2243 /// pieces of code, possibly including external crates.
2247 /// # use std::collections::HashMap;
2248 /// # use std::hash::{Hash, BuildHasher};
2249 /// # trait Serialize {};
2250 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2252 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2254 /// could be rewritten as
2256 /// # use std::collections::HashMap;
2257 /// # use std::hash::{Hash, BuildHasher};
2258 /// # trait Serialize {};
2259 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2261 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2263 pub IMPLICIT_HASHER,
2265 "missing generalization over different hashers"
2268 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2270 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
2271 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2272 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
2273 use rustc_span::BytePos;
2275 fn suggestion<'tcx>(
2276 cx: &LateContext<'tcx>,
2277 diag: &mut DiagnosticBuilder<'_>,
2278 generics_span: Span,
2279 generics_suggestion_span: Span,
2280 target: &ImplicitHasherType<'_>,
2281 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2283 let generics_snip = snippet(cx, generics_span, "");
2285 let generics_snip = if generics_snip.is_empty() {
2288 &generics_snip[1..generics_snip.len() - 1]
2293 "consider adding a type parameter",
2296 generics_suggestion_span,
2298 "<{}{}S: ::std::hash::BuildHasher{}>",
2300 if generics_snip.is_empty() { "" } else { ", " },
2301 if vis.suggestions.is_empty() {
2304 // request users to add `Default` bound so that generic constructors can be used
2311 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2316 if !vis.suggestions.is_empty() {
2317 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
2321 if !cx.access_levels.is_exported(item.hir_id()) {
2326 ItemKind::Impl(ref impl_) => {
2327 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2328 vis.visit_ty(impl_.self_ty);
2330 for target in &vis.found {
2331 if differing_macro_contexts(item.span, target.span()) {
2335 let generics_suggestion_span = impl_.generics.span.substitute_dummy({
2336 let pos = snippet_opt(cx, item.span.until(target.span()))
2337 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2338 if let Some(pos) = pos {
2339 Span::new(pos, pos, item.span.data().ctxt)
2345 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2346 for item in impl_.items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2347 ctr_vis.visit_impl_item(item);
2355 "impl for `{}` should be generalized over different hashers",
2359 suggestion(cx, diag, impl_.generics.span, generics_suggestion_span, target, ctr_vis);
2364 ItemKind::Fn(ref sig, ref generics, body_id) => {
2365 let body = cx.tcx.hir().body(body_id);
2367 for ty in sig.decl.inputs {
2368 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2371 for target in &vis.found {
2372 if in_external_macro(cx.sess(), generics.span) {
2375 let generics_suggestion_span = generics.span.substitute_dummy({
2376 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2378 let i = snip.find("fn")?;
2379 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2381 .expect("failed to create span for type parameters");
2382 Span::new(pos, pos, item.span.data().ctxt)
2385 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2386 ctr_vis.visit_body(body);
2393 "parameter of type `{}` should be generalized over different hashers",
2397 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2408 enum ImplicitHasherType<'tcx> {
2409 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2410 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2413 impl<'tcx> ImplicitHasherType<'tcx> {
2414 /// Checks that `ty` is a target type without a `BuildHasher`.
2415 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2416 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2417 let params: Vec<_> = path
2425 .filter_map(|arg| match arg {
2426 GenericArg::Type(ty) => Some(ty),
2430 let params_len = params.len();
2432 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2434 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2435 Some(ImplicitHasherType::HashMap(
2438 snippet(cx, params[0].span, "K"),
2439 snippet(cx, params[1].span, "V"),
2441 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2442 Some(ImplicitHasherType::HashSet(
2445 snippet(cx, params[0].span, "T"),
2455 fn type_name(&self) -> &'static str {
2457 ImplicitHasherType::HashMap(..) => "HashMap",
2458 ImplicitHasherType::HashSet(..) => "HashSet",
2462 fn type_arguments(&self) -> String {
2464 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2465 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2469 fn ty(&self) -> Ty<'tcx> {
2471 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2475 fn span(&self) -> Span {
2477 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2482 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2483 cx: &'a LateContext<'tcx>,
2484 found: Vec<ImplicitHasherType<'tcx>>,
2487 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2488 fn new(cx: &'a LateContext<'tcx>) -> Self {
2489 Self { cx, found: vec![] }
2493 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2494 type Map = Map<'tcx>;
2496 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2497 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2498 self.found.push(target);
2504 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2505 NestedVisitorMap::None
2509 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2510 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2511 cx: &'a LateContext<'tcx>,
2512 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
2513 target: &'b ImplicitHasherType<'tcx>,
2514 suggestions: BTreeMap<Span, String>,
2517 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2518 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2521 maybe_typeck_results: cx.maybe_typeck_results(),
2523 suggestions: BTreeMap::new(),
2528 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2529 type Map = Map<'tcx>;
2531 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2532 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
2533 walk_body(self, body);
2534 self.maybe_typeck_results = old_maybe_typeck_results;
2537 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2539 if let ExprKind::Call(ref fun, ref args) = e.kind;
2540 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2541 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2543 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
2547 if match_path(ty_path, &paths::HASHMAP) {
2548 if method.ident.name == sym::new {
2550 .insert(e.span, "HashMap::default()".to_string());
2551 } else if method.ident.name == sym!(with_capacity) {
2552 self.suggestions.insert(
2555 "HashMap::with_capacity_and_hasher({}, Default::default())",
2556 snippet(self.cx, args[0].span, "capacity"),
2560 } else if match_path(ty_path, &paths::HASHSET) {
2561 if method.ident.name == sym::new {
2563 .insert(e.span, "HashSet::default()".to_string());
2564 } else if method.ident.name == sym!(with_capacity) {
2565 self.suggestions.insert(
2568 "HashSet::with_capacity_and_hasher({}, Default::default())",
2569 snippet(self.cx, args[0].span, "capacity"),
2580 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2581 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2585 declare_clippy_lint! {
2586 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2588 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2589 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2592 /// **Known problems:** None.
2598 /// *(r as *const _ as *mut _) += 1;
2603 /// Instead consider using interior mutability types.
2606 /// use std::cell::UnsafeCell;
2608 /// fn x(r: &UnsafeCell<i32>) {
2614 pub CAST_REF_TO_MUT,
2616 "a cast of reference to a mutable pointer"
2619 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2621 impl<'tcx> LateLintPass<'tcx> for RefToMut {
2622 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2624 if let ExprKind::Unary(UnOp::Deref, e) = &expr.kind;
2625 if let ExprKind::Cast(e, t) = &e.kind;
2626 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2627 if let ExprKind::Cast(e, t) = &e.kind;
2628 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2629 if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
2635 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",
2642 const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0);
2644 declare_clippy_lint! {
2645 /// **What it does:**
2646 /// Checks for `as` casts between raw pointers without changing its mutability,
2647 /// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
2649 /// **Why is this bad?**
2650 /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
2651 /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
2653 /// **Known problems:** None.
2658 /// let ptr: *const u32 = &42_u32;
2659 /// let mut_ptr: *mut u32 = &mut 42_u32;
2660 /// let _ = ptr as *const i32;
2661 /// let _ = mut_ptr as *mut i32;
2665 /// let ptr: *const u32 = &42_u32;
2666 /// let mut_ptr: *mut u32 = &mut 42_u32;
2667 /// let _ = ptr.cast::<i32>();
2668 /// let _ = mut_ptr.cast::<i32>();
2672 "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
2675 pub struct PtrAsPtr {
2676 msrv: Option<RustcVersion>,
2681 pub fn new(msrv: Option<RustcVersion>) -> Self {
2686 impl_lint_pass!(PtrAsPtr => [PTR_AS_PTR]);
2688 impl<'tcx> LateLintPass<'tcx> for PtrAsPtr {
2689 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2690 if !meets_msrv(self.msrv.as_ref(), &PTR_AS_PTR_MSRV) {
2694 if expr.span.from_expansion() {
2699 if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind;
2700 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr));
2701 if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind();
2702 if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind();
2703 if matches!((from_mutbl, to_mutbl),
2704 (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut));
2705 // The `U` in `pointer::cast` have to be `Sized`
2706 // as explained here: https://github.com/rust-lang/rust/issues/60602.
2707 if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env);
2709 let mut applicability = Applicability::MachineApplicable;
2710 let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability);
2711 let turbofish = match &cast_to_hir_ty.kind {
2712 TyKind::Infer => Cow::Borrowed(""),
2713 TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
2714 _ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
2720 "`as` casting between raw pointers without changing its mutability",
2721 "try `pointer::cast`, a safer alternative",
2722 format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
2729 extract_msrv_attr!(LateContext);