1 #![allow(rustc::default_hash_types)]
5 mod redundant_allocation;
10 use std::cmp::Ordering;
11 use std::collections::BTreeMap;
13 use if_chain::if_chain;
14 use rustc_ast::{LitFloatType, LitIntType, LitKind};
15 use rustc_errors::{Applicability, DiagnosticBuilder};
17 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
19 BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericBounds, GenericParamKind, HirId,
20 ImplItem, ImplItemKind, Item, ItemKind, Lifetime, Lit, Local, MatchSource, MutTy, Mutability, Node, QPath, Stmt,
21 StmtKind, SyntheticTyParamKind, TraitFn, TraitItem, TraitItemKind, TyKind, UnOp,
23 use rustc_lint::{LateContext, LateLintPass, LintContext};
24 use rustc_middle::hir::map::Map;
25 use rustc_middle::lint::in_external_macro;
26 use rustc_middle::ty::{self, FloatTy, InferTy, IntTy, Ty, TyCtxt, TyS, TypeAndMut, TypeckResults, UintTy};
27 use rustc_semver::RustcVersion;
28 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
29 use rustc_span::hygiene::{ExpnKind, MacroKind};
30 use rustc_span::source_map::Span;
31 use rustc_span::symbol::sym;
32 use rustc_target::abi::LayoutOf;
33 use rustc_target::spec::abi::Abi;
34 use rustc_typeck::hir_ty_to_ty;
36 use crate::consts::{constant, Constant};
37 use crate::utils::paths;
38 use crate::utils::sugg::Sugg;
40 clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_hir_ty_cfg_dependant,
41 is_ty_param_diagnostic_item, is_type_diagnostic_item, match_def_path, match_path, meets_msrv, method_chain_args,
42 multispan_sugg, numeric_literal::NumericLiteral, reindent_multiline, sext, snippet, snippet_opt,
43 snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg,
44 span_lint_and_then, unsext,
47 declare_clippy_lint! {
48 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
49 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
51 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
52 /// the heap. So if you `Box` it, you just add another level of indirection
53 /// without any benefit whatsoever.
55 /// **Known problems:** None.
60 /// values: Box<Vec<Foo>>,
73 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
76 declare_clippy_lint! {
77 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
78 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
80 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
81 /// the heap. So if you `Box` its contents, you just add another level of indirection.
83 /// **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),
89 /// values: Vec<Box<i32>>,
102 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
105 declare_clippy_lint! {
106 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
109 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
110 /// represents an optional optional value which is logically the same thing as an optional
111 /// value but has an unneeded extra level of wrapping.
113 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
114 /// consider a custom `enum` instead, with clear names for each case.
116 /// **Known problems:** None.
120 /// fn get_data() -> Option<Option<u32>> {
128 /// pub enum Contents {
129 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
130 /// NotYetFetched, // Was Some(None)
131 /// None, // Was None
134 /// fn get_data() -> Contents {
140 "usage of `Option<Option<T>>`"
143 declare_clippy_lint! {
144 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
145 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
147 /// **Why is this bad?** Gankro says:
149 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
150 /// pointers and indirection.
151 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
153 /// > "only" amortized for push/pop, should be faster in the general case for
154 /// almost every possible
155 /// > workload, and isn't even amortized at all if you can predict the capacity
158 /// > `LinkedList`s are only really good if you're doing a lot of merging or
159 /// splitting of lists.
160 /// > This is because they can just mangle some pointers instead of actually
161 /// copying the data. Even
162 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
163 /// can still be better
164 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
166 /// **Known problems:** False positives – the instances where using a
167 /// `LinkedList` makes sense are few and far between, but they can still happen.
171 /// # use std::collections::LinkedList;
172 /// let x: LinkedList<usize> = LinkedList::new();
176 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
179 declare_clippy_lint! {
180 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
181 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
183 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
186 /// **Known problems:** None.
190 /// fn foo(bar: &Box<T>) { ... }
196 /// fn foo(bar: &T) { ... }
200 "a borrow of a boxed type"
203 declare_clippy_lint! {
204 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
206 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
207 /// add an unnecessary level of indirection.
209 /// **Known problems:** None.
213 /// # use std::rc::Rc;
214 /// fn foo(bar: Rc<&usize>) {}
220 /// fn foo(bar: &usize) {}
222 pub REDUNDANT_ALLOCATION,
224 "redundant allocation"
227 declare_clippy_lint! {
228 /// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
230 /// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
231 /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
233 /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
234 /// works if there are no additional references yet, which usually defeats the purpose of
235 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
236 /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
239 /// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
240 /// cases where mutation only happens before there are any additional references.
244 /// # use std::rc::Rc;
245 /// fn foo(interned: Rc<String>) { ... }
251 /// fn foo(interned: Rc<str>) { ... }
255 "shared ownership of a buffer type"
259 vec_box_size_threshold: u64,
262 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
264 impl<'tcx> LateLintPass<'tcx> for Types {
265 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
266 // Skip trait implementations; see issue #605.
267 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
268 if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
273 self.check_fn_decl(cx, decl);
276 fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) {
277 self.check_ty(cx, &field.ty, false);
280 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
282 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
283 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
288 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
289 if let Some(ref ty) = local.ty {
290 self.check_ty(cx, ty, true);
296 pub fn new(vec_box_size_threshold: u64) -> Self {
297 Self { vec_box_size_threshold }
300 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
301 for input in decl.inputs {
302 self.check_ty(cx, input, false);
305 if let FnRetTy::Return(ref ty) = decl.output {
306 self.check_ty(cx, ty, false);
310 /// Recursively check for `TypePass` lints in the given type. Stop at the first
313 /// The parameter `is_local` distinguishes the context of the type; types from
314 /// local bindings should only be checked for the `BORROWED_BOX` lint.
315 #[allow(clippy::too_many_lines)]
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 box_vec::check(cx, hir_ty, qpath, def_id);
326 redundant_allocation::check(cx, hir_ty, qpath, def_id);
327 rc_buffer::check(cx, hir_ty, qpath, def_id);
328 vec_box::check(cx, hir_ty, qpath, def_id, self.vec_box_size_threshold);
330 if cx.tcx.is_diagnostic_item(sym::option_type, def_id) {
331 if is_ty_param_diagnostic_item(cx, qpath, sym::option_type).is_some() {
336 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
337 enum if you need to distinguish all 3 cases",
339 return; // don't recurse into the type
341 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
346 "you seem to be using a `LinkedList`! Perhaps you meant some other data structure?",
348 "a `VecDeque` might work",
350 return; // don't recurse into the type
354 QPath::Resolved(Some(ref ty), ref p) => {
355 self.check_ty(cx, ty, is_local);
356 for ty in p.segments.iter().flat_map(|seg| {
359 .map_or_else(|| [].iter(), |params| params.args.iter())
360 .filter_map(|arg| match arg {
361 GenericArg::Type(ty) => Some(ty),
365 self.check_ty(cx, ty, is_local);
368 QPath::Resolved(None, ref p) => {
369 for ty in p.segments.iter().flat_map(|seg| {
372 .map_or_else(|| [].iter(), |params| params.args.iter())
373 .filter_map(|arg| match arg {
374 GenericArg::Type(ty) => Some(ty),
378 self.check_ty(cx, ty, is_local);
381 QPath::TypeRelative(ref ty, ref seg) => {
382 self.check_ty(cx, ty, is_local);
383 if let Some(ref params) = seg.args {
384 for ty in params.args.iter().filter_map(|arg| match arg {
385 GenericArg::Type(ty) => Some(ty),
388 self.check_ty(cx, ty, is_local);
392 QPath::LangItem(..) => {},
395 TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
397 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
398 self.check_ty(cx, ty, is_local)
400 TyKind::Tup(tys) => {
402 self.check_ty(cx, ty, is_local);
411 cx: &LateContext<'_>,
412 hir_ty: &hir::Ty<'_>,
417 match mut_ty.ty.kind {
418 TyKind::Path(ref qpath) => {
419 let hir_id = mut_ty.ty.hir_id;
420 let def = cx.qpath_res(qpath, hir_id);
422 if let Some(def_id) = def.opt_def_id();
423 if Some(def_id) == cx.tcx.lang_items().owned_box();
424 if let QPath::Resolved(None, ref path) = *qpath;
425 if let [ref bx] = *path.segments;
426 if let Some(ref params) = bx.args;
427 if !params.parenthesized;
428 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
429 GenericArg::Type(ty) => Some(ty),
433 if is_any_trait(inner) {
434 // Ignore `Box<Any>` types; see issue #1884 for details.
438 let ltopt = if lt.is_elided() {
441 format!("{} ", lt.name.ident().as_str())
444 if mut_ty.mutbl == Mutability::Mut {
445 // Ignore `&mut Box<T>` types; see issue #2907 for
450 // When trait objects or opaque types have lifetime or auto-trait bounds,
451 // we need to add parentheses to avoid a syntax error due to its ambiguity.
452 // Originally reported as the issue #3128.
453 let inner_snippet = snippet(cx, inner.span, "..");
454 let suggestion = match &inner.kind {
455 TyKind::TraitObject(bounds, lt_bound) if bounds.len() > 1 || !lt_bound.is_elided() => {
456 format!("&{}({})", ltopt, &inner_snippet)
459 if get_bounds_if_impl_trait(cx, qpath, inner.hir_id)
460 .map_or(false, |bounds| bounds.len() > 1) =>
462 format!("&{}({})", ltopt, &inner_snippet)
464 _ => format!("&{}{}", ltopt, &inner_snippet),
470 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
473 // To make this `MachineApplicable`, at least one needs to check if it isn't a trait item
474 // because the trait impls of it will break otherwise;
475 // and there may be other cases that result in invalid code.
476 // For example, type coercion doesn't work nicely.
477 Applicability::Unspecified,
479 return; // don't recurse into the type
482 self.check_ty(cx, &mut_ty.ty, is_local);
484 _ => self.check_ty(cx, &mut_ty.ty, is_local),
489 // Returns true if given type is `Any` trait.
490 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
492 if let TyKind::TraitObject(ref traits, _) = t.kind;
493 if !traits.is_empty();
494 // Only Send/Sync can be used as additional traits, so it is enough to
495 // check only the first trait.
496 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
505 fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: HirId) -> Option<GenericBounds<'tcx>> {
507 if let Some(did) = cx.qpath_res(qpath, id).opt_def_id();
508 if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did);
509 if let GenericParamKind::Type { synthetic, .. } = generic_param.kind;
510 if synthetic == Some(SyntheticTyParamKind::ImplTrait);
512 Some(generic_param.bounds)
519 declare_clippy_lint! {
520 /// **What it does:** Checks for binding a unit value.
522 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
523 /// binding one is kind of pointless.
525 /// **Known problems:** None.
535 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
538 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
540 impl<'tcx> LateLintPass<'tcx> for LetUnitValue {
541 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
542 if let StmtKind::Local(ref local) = stmt.kind {
543 if is_unit(cx.typeck_results().pat_ty(&local.pat)) {
544 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
547 if higher::is_from_for_desugar(local) {
554 "this let-binding has unit value",
556 if let Some(expr) = &local.init {
557 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
558 diag.span_suggestion(
560 "omit the `let` binding",
561 format!("{};", snip),
562 Applicability::MachineApplicable, // snippet
572 declare_clippy_lint! {
573 /// **What it does:** Checks for comparisons to unit. This includes all binary
574 /// comparisons (like `==` and `<`) and asserts.
576 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
577 /// clumsily written constant. Mostly this happens when someone accidentally
578 /// adds semicolons at the end of the operands.
580 /// **Known problems:** None.
611 /// assert_eq!({ foo(); }, { bar(); });
613 /// will always succeed
616 "comparing unit values"
619 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
621 impl<'tcx> LateLintPass<'tcx> for UnitCmp {
622 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
623 if expr.span.from_expansion() {
624 if let Some(callee) = expr.span.source_callee() {
625 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
626 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
628 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
629 let result = match &*symbol.as_str() {
630 "assert_eq" | "debug_assert_eq" => "succeed",
631 "assert_ne" | "debug_assert_ne" => "fail",
639 "`{}` of unit values detected. This will always {}",
650 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
652 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
653 let result = match op {
654 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
662 "{}-comparison of unit values detected. This will always be {}",
672 declare_clippy_lint! {
673 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
674 /// unit literal (`()`).
676 /// **Why is this bad?** This is likely the result of an accidental semicolon.
678 /// **Known problems:** None.
689 "passing unit to a function"
692 declare_lint_pass!(UnitArg => [UNIT_ARG]);
694 impl<'tcx> LateLintPass<'tcx> for UnitArg {
695 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
696 if expr.span.from_expansion() {
700 // apparently stuff in the desugaring of `?` can trigger this
701 // so check for that here
702 // only the calls to `Try::from_error` is marked as desugared,
703 // so we need to check both the current Expr and its parent.
704 if is_questionmark_desugar_marked_call(expr) {
708 let map = &cx.tcx.hir();
709 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
710 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
711 if is_questionmark_desugar_marked_call(parent_expr);
718 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => {
719 let args_to_recover = args
722 if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) {
725 ExprKind::Match(.., MatchSource::TryDesugar) | ExprKind::Path(..)
731 .collect::<Vec<_>>();
732 if !args_to_recover.is_empty() {
733 lint_unit_args(cx, expr, &args_to_recover);
741 fn fmt_stmts_and_call(
742 cx: &LateContext<'_>,
743 call_expr: &Expr<'_>,
745 args_snippets: &[impl AsRef<str>],
746 non_empty_block_args_snippets: &[impl AsRef<str>],
748 let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
749 let call_snippet_with_replacements = args_snippets
751 .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
753 let mut stmts_and_call = non_empty_block_args_snippets
755 .map(|it| it.as_ref().to_owned())
756 .collect::<Vec<_>>();
757 stmts_and_call.push(call_snippet_with_replacements);
758 stmts_and_call = stmts_and_call
760 .map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
763 let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
764 // expr is not in a block statement or result expression position, wrap in a block
765 let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
766 if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
767 let block_indent = call_expr_indent + 4;
768 stmts_and_call_snippet =
769 reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
770 stmts_and_call_snippet = format!(
772 " ".repeat(block_indent),
773 &stmts_and_call_snippet,
774 " ".repeat(call_expr_indent)
777 stmts_and_call_snippet
780 fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
781 let mut applicability = Applicability::MachineApplicable;
782 let (singular, plural) = if args_to_recover.len() > 1 {
791 &format!("passing {}unit value{} to a function", singular, plural),
798 if let ExprKind::Block(block, _) = arg.kind;
799 if block.expr.is_none();
800 if let Some(last_stmt) = block.stmts.iter().last();
801 if let StmtKind::Semi(last_expr) = last_stmt.kind;
802 if let Some(snip) = snippet_opt(cx, last_expr.span);
814 .for_each(|(span, sugg)| {
817 "remove the semicolon from the last statement in the block",
819 Applicability::MaybeIncorrect,
822 applicability = Applicability::MaybeIncorrect;
825 let arg_snippets: Vec<String> = args_to_recover
827 .filter_map(|arg| snippet_opt(cx, arg.span))
829 let arg_snippets_without_empty_blocks: Vec<String> = args_to_recover
831 .filter(|arg| !is_empty_block(arg))
832 .filter_map(|arg| snippet_opt(cx, arg.span))
835 if let Some(call_snippet) = snippet_opt(cx, expr.span) {
836 let sugg = fmt_stmts_and_call(
841 &arg_snippets_without_empty_blocks,
844 if arg_snippets_without_empty_blocks.is_empty() {
845 db.multipart_suggestion(
846 &format!("use {}unit literal{} instead", singular, plural),
849 .map(|arg| (arg.span, "()".to_string()))
850 .collect::<Vec<_>>(),
854 let plural = arg_snippets_without_empty_blocks.len() > 1;
855 let empty_or_s = if plural { "s" } else { "" };
856 let it_or_them = if plural { "them" } else { "it" };
860 "{}move the expression{} in front of the call and replace {} with the unit literal `()`",
861 or, empty_or_s, it_or_them
872 fn is_empty_block(expr: &Expr<'_>) -> bool {
886 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
887 use rustc_span::hygiene::DesugaringKind;
888 if let ExprKind::Call(ref callee, _) = expr.kind {
889 callee.span.is_desugaring(DesugaringKind::QuestionMark)
895 fn is_unit(ty: Ty<'_>) -> bool {
896 matches!(ty.kind(), ty::Tuple(slice) if slice.is_empty())
899 fn is_unit_literal(expr: &Expr<'_>) -> bool {
900 matches!(expr.kind, ExprKind::Tup(ref slice) if slice.is_empty())
903 declare_clippy_lint! {
904 /// **What it does:** Checks for casts from any numerical to a float type where
905 /// the receiving type cannot store all values from the original type without
906 /// rounding errors. This possible rounding is to be expected, so this lint is
907 /// `Allow` by default.
909 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
910 /// or any 64-bit integer to `f64`.
912 /// **Why is this bad?** It's not bad at all. But in some applications it can be
913 /// helpful to know where precision loss can take place. This lint can help find
914 /// those places in the code.
916 /// **Known problems:** None.
920 /// let x = u64::MAX;
923 pub CAST_PRECISION_LOSS,
925 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
928 declare_clippy_lint! {
929 /// **What it does:** Checks for casts from a signed to an unsigned numerical
930 /// type. In this case, negative values wrap around to large positive values,
931 /// which can be quite surprising in practice. However, as the cast works as
932 /// defined, this lint is `Allow` by default.
934 /// **Why is this bad?** Possibly surprising results. You can activate this lint
935 /// as a one-time check to see where numerical wrapping can arise.
937 /// **Known problems:** None.
942 /// y as u128; // will return 18446744073709551615
946 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
949 declare_clippy_lint! {
950 /// **What it does:** Checks for casts between numerical types that may
951 /// truncate large values. This is expected behavior, so the cast is `Allow` by
954 /// **Why is this bad?** In some problem domains, it is good practice to avoid
955 /// truncation. This lint can be activated to help assess where additional
956 /// checks could be beneficial.
958 /// **Known problems:** None.
962 /// fn as_u8(x: u64) -> u8 {
966 pub CAST_POSSIBLE_TRUNCATION,
968 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
971 declare_clippy_lint! {
972 /// **What it does:** Checks for casts from an unsigned type to a signed type of
973 /// the same size. Performing such a cast is a 'no-op' for the compiler,
974 /// i.e., nothing is changed at the bit level, and the binary representation of
975 /// the value is reinterpreted. This can cause wrapping if the value is too big
976 /// for the target signed type. However, the cast works as defined, so this lint
977 /// is `Allow` by default.
979 /// **Why is this bad?** While such a cast is not bad in itself, the results can
980 /// be surprising when this is not the intended behavior, as demonstrated by the
983 /// **Known problems:** None.
987 /// u32::MAX as i32; // will yield a value of `-1`
989 pub CAST_POSSIBLE_WRAP,
991 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
994 declare_clippy_lint! {
995 /// **What it does:** Checks for casts between numerical types that may
996 /// be replaced by safe conversion functions.
998 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
999 /// conversions, including silently lossy conversions. Conversion functions such
1000 /// as `i32::from` will only perform lossless conversions. Using the conversion
1001 /// functions prevents conversions from turning into silent lossy conversions if
1002 /// the types of the input expressions ever change, and make it easier for
1003 /// people reading the code to know that the conversion is lossless.
1005 /// **Known problems:** None.
1009 /// fn as_u64(x: u8) -> u64 {
1014 /// Using `::from` would look like this:
1017 /// fn as_u64(x: u8) -> u64 {
1023 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
1026 declare_clippy_lint! {
1027 /// **What it does:** Checks for casts to the same type, casts of int literals to integer types
1028 /// and casts of float literals to float types.
1030 /// **Why is this bad?** It's just unnecessary.
1032 /// **Known problems:** None.
1036 /// let _ = 2i32 as i32;
1037 /// let _ = 0.5 as f32;
1044 /// let _ = 0.5_f32;
1046 pub UNNECESSARY_CAST,
1048 "cast to the same type, e.g., `x as i32` where `x: i32`"
1051 declare_clippy_lint! {
1052 /// **What it does:** Checks for casts, using `as` or `pointer::cast`,
1053 /// from a less-strictly-aligned pointer to a more-strictly-aligned pointer
1055 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
1058 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
1059 /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
1060 /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
1064 /// let _ = (&1u8 as *const u8) as *const u16;
1065 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
1067 /// (&1u8 as *const u8).cast::<u16>();
1068 /// (&mut 1u8 as *mut u8).cast::<u16>();
1070 pub CAST_PTR_ALIGNMENT,
1072 "cast from a pointer to a more-strictly-aligned pointer"
1075 declare_clippy_lint! {
1076 /// **What it does:** Checks for casts of function pointers to something other than usize
1078 /// **Why is this bad?**
1079 /// Casting a function pointer to anything other than usize/isize is not portable across
1080 /// architectures, because you end up losing bits if the target type is too small or end up with a
1081 /// bunch of extra bits that waste space and add more instructions to the final binary than
1082 /// strictly necessary for the problem
1084 /// Casting to isize also doesn't make sense since there are no signed addresses.
1090 /// fn fun() -> i32 { 1 }
1091 /// let a = fun as i64;
1094 /// fn fun2() -> i32 { 1 }
1095 /// let a = fun2 as usize;
1097 pub FN_TO_NUMERIC_CAST,
1099 "casting a function pointer to a numeric type other than usize"
1102 declare_clippy_lint! {
1103 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1106 /// **Why is this bad?**
1107 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1108 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1109 /// a comment) to perform the truncation.
1115 /// fn fn1() -> i16 {
1118 /// let _ = fn1 as i32;
1120 /// // Better: Cast to usize first, then comment with the reason for the truncation
1121 /// fn fn2() -> i16 {
1124 /// let fn_ptr = fn2 as usize;
1125 /// let fn_ptr_truncated = fn_ptr as i32;
1127 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1129 "casting a function pointer to a numeric type not wide enough to store the address"
1132 /// Returns the size in bits of an integral type.
1133 /// Will return 0 if the type is not an int or uint variant
1134 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1136 ty::Int(i) => match i {
1137 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1144 ty::Uint(i) => match i {
1145 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1150 UintTy::U128 => 128,
1156 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1157 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
1160 fn span_precision_loss_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1161 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1162 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1163 let arch_dependent_str = "on targets with 64-bit wide pointers ";
1164 let from_nbits_str = if arch_dependent {
1166 } else if is_isize_or_usize(cast_from) {
1167 "32 or 64".to_owned()
1169 int_ty_to_nbits(cast_from, cx.tcx).to_string()
1173 CAST_PRECISION_LOSS,
1176 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1177 but `{1}`'s mantissa is only {4} bits wide)",
1179 if cast_to_f64 { "f64" } else { "f32" },
1180 if arch_dependent { arch_dependent_str } else { "" },
1187 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1188 if let ExprKind::Binary(_, _, _) = op.kind {
1189 if snip.starts_with('(') && snip.ends_with(')') {
1196 fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1197 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1198 if in_constant(cx, expr.hir_id) {
1201 // The suggestion is to use a function call, so if the original expression
1202 // has parens on the outside, they are no longer needed.
1203 let mut applicability = Applicability::MachineApplicable;
1204 let opt = snippet_opt(cx, op.span);
1205 let sugg = opt.as_ref().map_or_else(
1207 applicability = Applicability::HasPlaceholders;
1211 if should_strip_parens(op, snip) {
1212 &snip[1..snip.len() - 1]
1224 "casting `{}` to `{}` may become silently lossy if you later change the type",
1228 format!("{}::from({})", cast_to, sugg),
1239 fn check_loss_of_sign(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1240 if !cast_from.is_signed() || cast_to.is_signed() {
1244 // don't lint for positive constants
1245 let const_val = constant(cx, &cx.typeck_results(), op);
1247 if let Some((Constant::Int(n), _)) = const_val;
1248 if let ty::Int(ity) = *cast_from.kind();
1249 if sext(cx.tcx, n, ity) >= 0;
1255 // don't lint for the result of methods that always return non-negative values
1256 if let ExprKind::MethodCall(ref path, _, _, _) = op.kind {
1257 let mut method_name = path.ident.name.as_str();
1258 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1261 if method_name == "unwrap";
1262 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1263 if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
1265 method_name = inner_path.ident.name.as_str();
1269 if allowed_methods.iter().any(|&name| method_name == name) {
1279 "casting `{}` to `{}` may lose the sign of the value",
1285 fn check_truncation_and_wrapping(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1286 let arch_64_suffix = " on targets with 64-bit wide pointers";
1287 let arch_32_suffix = " on targets with 32-bit wide pointers";
1288 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1289 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1290 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1291 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1292 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1293 (true, true) | (false, false) => (
1294 to_nbits < from_nbits,
1296 to_nbits == from_nbits && cast_unsigned_to_signed,
1306 to_nbits <= 32 && cast_unsigned_to_signed,
1312 cast_unsigned_to_signed,
1313 if from_nbits == 64 {
1320 if span_truncation {
1323 CAST_POSSIBLE_TRUNCATION,
1326 "casting `{}` to `{}` may truncate the value{}",
1329 match suffix_truncation {
1330 ArchSuffix::_32 => arch_32_suffix,
1331 ArchSuffix::_64 => arch_64_suffix,
1332 ArchSuffix::None => "",
1343 "casting `{}` to `{}` may wrap around the value{}",
1347 ArchSuffix::_32 => arch_32_suffix,
1348 ArchSuffix::_64 => arch_64_suffix,
1349 ArchSuffix::None => "",
1356 fn check_lossless(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1357 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1358 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1359 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1360 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1362 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1366 declare_lint_pass!(Casts => [
1367 CAST_PRECISION_LOSS,
1369 CAST_POSSIBLE_TRUNCATION,
1375 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1378 // Check if the given type is either `core::ffi::c_void` or
1379 // one of the platform specific `libc::<platform>::c_void` of libc.
1380 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
1381 if let ty::Adt(adt, _) = ty.kind() {
1382 let names = cx.get_def_path(adt.did);
1384 if names.is_empty() {
1387 if names[0] == sym::libc || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1394 /// Returns the mantissa bits wide of a fp type.
1395 /// Will return 0 if the type is not a fp
1396 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1398 ty::Float(FloatTy::F32) => 23,
1399 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1404 impl<'tcx> LateLintPass<'tcx> for Casts {
1405 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1406 if expr.span.from_expansion() {
1409 if let ExprKind::Cast(ref ex, cast_to) = expr.kind {
1410 if is_hir_ty_cfg_dependant(cx, cast_to) {
1413 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
1414 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1415 if let Some(lit) = get_numeric_literal(ex) {
1416 let literal_str = snippet_opt(cx, ex.span).unwrap_or_default();
1419 if let LitKind::Int(n, _) = lit.node;
1420 if let Some(src) = snippet_opt(cx, lit.span);
1421 if cast_to.is_floating_point();
1422 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1423 let from_nbits = 128 - n.leading_zeros();
1424 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1425 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1427 let literal_str = if is_unary_neg(ex) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
1428 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1434 LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
1435 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1437 LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
1438 show_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
1440 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1442 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
1448 "casting to the same type is unnecessary (`{}` -> `{}`)",
1456 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1457 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1460 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1461 } else if let ExprKind::MethodCall(method_path, _, args, _) = expr.kind {
1463 if method_path.ident.name == sym!(cast);
1464 if let Some(generic_args) = method_path.args;
1465 if let [GenericArg::Type(cast_to)] = generic_args.args;
1466 // There probably is no obvious reason to do this, just to be consistent with `as` cases.
1467 if !is_hir_ty_cfg_dependant(cx, cast_to);
1469 let (cast_from, cast_to) =
1470 (cx.typeck_results().expr_ty(&args[0]), cx.typeck_results().expr_ty(expr));
1471 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1478 fn is_unary_neg(expr: &Expr<'_>) -> bool {
1479 matches!(expr.kind, ExprKind::Unary(UnOp::Neg, _))
1482 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
1484 ExprKind::Lit(ref lit) => Some(lit),
1485 ExprKind::Unary(UnOp::Neg, e) => {
1486 if let ExprKind::Lit(ref lit) = e.kind {
1496 fn show_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1497 let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
1502 &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
1504 format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
1505 Applicability::MachineApplicable,
1509 fn lint_numeric_casts<'tcx>(
1510 cx: &LateContext<'tcx>,
1512 cast_expr: &Expr<'_>,
1513 cast_from: Ty<'tcx>,
1516 match (cast_from.is_integral(), cast_to.is_integral()) {
1518 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1519 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
1524 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1525 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1527 if from_nbits < to_nbits {
1528 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1534 CAST_POSSIBLE_TRUNCATION,
1536 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1538 if !cast_to.is_signed() {
1544 "casting `{}` to `{}` may lose the sign of the value",
1551 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1552 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1553 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1556 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
1559 CAST_POSSIBLE_TRUNCATION,
1561 "casting `f64` to `f32` may truncate the value",
1564 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
1565 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1571 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1573 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
1574 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
1575 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1576 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1577 if from_layout.align.abi < to_layout.align.abi;
1578 // with c_void, we inherently need to trust the user
1579 if !is_c_void(cx, from_ptr_ty.ty);
1580 // when casting from a ZST, we don't know enough to properly lint
1581 if !from_layout.is_zst();
1588 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1591 from_layout.align.abi.bytes(),
1592 to_layout.align.abi.bytes(),
1599 fn lint_fn_to_numeric_cast(
1600 cx: &LateContext<'_>,
1602 cast_expr: &Expr<'_>,
1606 // We only want to check casts to `ty::Uint` or `ty::Int`
1607 match cast_to.kind() {
1608 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1611 match cast_from.kind() {
1612 ty::FnDef(..) | ty::FnPtr(_) => {
1613 let mut applicability = Applicability::MaybeIncorrect;
1614 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1616 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1617 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1620 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1623 "casting function pointer `{}` to `{}`, which truncates the value",
1624 from_snippet, cast_to
1627 format!("{} as usize", from_snippet),
1630 } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
1635 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1637 format!("{} as usize", from_snippet),
1646 declare_clippy_lint! {
1647 /// **What it does:** Checks for types used in structs, parameters and `let`
1648 /// declarations above a certain complexity threshold.
1650 /// **Why is this bad?** Too complex types make the code less readable. Consider
1651 /// using a `type` definition to simplify them.
1653 /// **Known problems:** None.
1657 /// # use std::rc::Rc;
1659 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1662 pub TYPE_COMPLEXITY,
1664 "usage of very complex types that might be better factored into `type` definitions"
1667 pub struct TypeComplexity {
1671 impl TypeComplexity {
1673 pub fn new(threshold: u64) -> Self {
1678 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1680 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
1683 cx: &LateContext<'tcx>,
1685 decl: &'tcx FnDecl<'_>,
1690 self.check_fndecl(cx, decl);
1693 fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
1694 // enum variants are also struct fields now
1695 self.check_type(cx, &field.ty);
1698 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1700 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1701 // functions, enums, structs, impls and traits are covered
1706 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1708 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1709 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1710 // methods with default impl are covered by check_fn
1715 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
1717 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1718 // methods are covered by check_fn
1723 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
1724 if let Some(ref ty) = local.ty {
1725 self.check_type(cx, ty);
1730 impl<'tcx> TypeComplexity {
1731 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
1732 for arg in decl.inputs {
1733 self.check_type(cx, arg);
1735 if let FnRetTy::Return(ref ty) = decl.output {
1736 self.check_type(cx, ty);
1740 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
1741 if ty.span.from_expansion() {
1745 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1746 visitor.visit_ty(ty);
1750 if score > self.threshold {
1755 "very complex type used. Consider factoring parts into `type` definitions",
1761 /// Walks a type and assigns a complexity score to it.
1762 struct TypeComplexityVisitor {
1763 /// total complexity score of the type
1765 /// current nesting level
1769 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1770 type Map = Map<'tcx>;
1772 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1773 let (add_score, sub_nest) = match ty.kind {
1774 // _, &x and *x have only small overhead; don't mess with nesting level
1775 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1777 // the "normal" components of a type: named types, arrays/tuples
1778 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1780 // function types bring a lot of overhead
1781 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1783 TyKind::TraitObject(ref param_bounds, _) => {
1784 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1786 .bound_generic_params
1788 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
1790 if has_lifetime_parameters {
1791 // complex trait bounds like A<'a, 'b>
1794 // simple trait bounds like A + B
1801 self.score += add_score;
1802 self.nest += sub_nest;
1804 self.nest -= sub_nest;
1806 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1807 NestedVisitorMap::None
1811 declare_clippy_lint! {
1812 /// **What it does:** Checks for expressions where a character literal is cast
1813 /// to `u8` and suggests using a byte literal instead.
1815 /// **Why is this bad?** In general, casting values to smaller types is
1816 /// error-prone and should be avoided where possible. In the particular case of
1817 /// converting a character literal to u8, it is easy to avoid by just using a
1818 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1819 /// than `'a' as u8`.
1821 /// **Known problems:** None.
1828 /// A better version, using the byte literal:
1835 "casting a character literal to `u8` truncates"
1838 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1840 impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
1841 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1843 if !expr.span.from_expansion();
1844 if let ExprKind::Cast(e, _) = &expr.kind;
1845 if let ExprKind::Lit(l) = &e.kind;
1846 if let LitKind::Char(c) = l.node;
1847 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
1849 let mut applicability = Applicability::MachineApplicable;
1850 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
1856 "casting a character literal to `u8` truncates",
1858 diag.note("`char` is four bytes wide, but `u8` is a single byte");
1861 diag.span_suggestion(
1863 "use a byte literal instead",
1864 format!("b{}", snippet),
1874 declare_clippy_lint! {
1875 /// **What it does:** Checks for comparisons where one side of the relation is
1876 /// either the minimum or maximum value for its type and warns if it involves a
1877 /// case that is always true or always false. Only integer and boolean types are
1880 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1881 /// that it is possible for `x` to be less than the minimum. Expressions like
1882 /// `max < x` are probably mistakes.
1884 /// **Known problems:** For `usize` the size of the current compile target will
1885 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1886 /// a comparison to detect target pointer width will trigger this lint. One can
1887 /// use `mem::sizeof` and compare its value or conditional compilation
1889 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1894 /// let vec: Vec<isize> = Vec::new();
1895 /// if vec.len() <= 0 {}
1896 /// if 100 > i32::MAX {}
1898 pub ABSURD_EXTREME_COMPARISONS,
1900 "a comparison with a maximum or minimum value that is always true or false"
1903 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1910 struct ExtremeExpr<'a> {
1915 enum AbsurdComparisonResult {
1918 InequalityImpossible,
1921 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1922 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1923 let precast_ty = cx.typeck_results().expr_ty(cast_exp);
1924 let cast_ty = cx.typeck_results().expr_ty(expr);
1926 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1932 fn detect_absurd_comparison<'tcx>(
1933 cx: &LateContext<'tcx>,
1935 lhs: &'tcx Expr<'_>,
1936 rhs: &'tcx Expr<'_>,
1937 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1938 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
1939 use crate::types::ExtremeType::{Maximum, Minimum};
1940 use crate::utils::comparisons::{normalize_comparison, Rel};
1942 // absurd comparison only makes sense on primitive types
1943 // primitive types don't implement comparison operators with each other
1944 if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
1948 // comparisons between fix sized types and target sized types are considered unanalyzable
1949 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1953 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
1955 let lx = detect_extreme_expr(cx, normalized_lhs);
1956 let rx = detect_extreme_expr(cx, normalized_rhs);
1961 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1962 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1968 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1969 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1970 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1971 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1975 Rel::Ne | Rel::Eq => return None,
1979 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
1980 use crate::types::ExtremeType::{Maximum, Minimum};
1982 let ty = cx.typeck_results().expr_ty(expr);
1984 let cv = constant(cx, cx.typeck_results(), expr)?.0;
1986 let which = match (ty.kind(), cv) {
1987 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1988 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
1992 (&ty::Bool, Constant::Bool(true)) => Maximum,
1993 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
1996 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
2000 Some(ExtremeExpr { which, expr })
2003 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
2004 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2005 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2006 use crate::types::ExtremeType::{Maximum, Minimum};
2008 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2009 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
2010 if !expr.span.from_expansion() {
2011 let msg = "this comparison involving the minimum or maximum element for this \
2012 type contains a case that is always true or always false";
2014 let conclusion = match result {
2015 AlwaysFalse => "this comparison is always false".to_owned(),
2016 AlwaysTrue => "this comparison is always true".to_owned(),
2017 InequalityImpossible => format!(
2018 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
2020 snippet(cx, lhs.span, "lhs"),
2021 snippet(cx, rhs.span, "rhs")
2026 "because `{}` is the {} value for this type, {}",
2027 snippet(cx, culprit.expr.span, "x"),
2028 match culprit.which {
2029 Minimum => "minimum",
2030 Maximum => "maximum",
2035 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
2042 declare_clippy_lint! {
2043 /// **What it does:** Checks for comparisons where the relation is always either
2044 /// true or false, but where one side has been upcast so that the comparison is
2045 /// necessary. Only integer types are checked.
2047 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
2048 /// will mistakenly imply that it is possible for `x` to be outside the range of
2051 /// **Known problems:**
2052 /// https://github.com/rust-lang/rust-clippy/issues/886
2057 /// (x as u32) > 300;
2059 pub INVALID_UPCAST_COMPARISONS,
2061 "a comparison involving an upcast which is always true or false"
2064 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
2066 #[derive(Copy, Clone, Debug, Eq)]
2073 #[allow(clippy::cast_sign_loss)]
2075 fn cmp_s_u(s: i128, u: u128) -> Ordering {
2078 } else if u > (i128::MAX as u128) {
2086 impl PartialEq for FullInt {
2088 fn eq(&self, other: &Self) -> bool {
2089 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
2093 impl PartialOrd for FullInt {
2095 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2096 Some(match (self, other) {
2097 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
2098 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
2099 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
2100 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
2105 impl Ord for FullInt {
2107 fn cmp(&self, other: &Self) -> Ordering {
2108 self.partial_cmp(other)
2109 .expect("`partial_cmp` for FullInt can never return `None`")
2113 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
2114 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2115 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
2116 let cast_ty = cx.typeck_results().expr_ty(expr);
2117 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
2118 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
2121 match pre_cast_ty.kind() {
2122 ty::Int(int_ty) => Some(match int_ty {
2123 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
2124 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
2125 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
2126 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
2127 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
2128 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
2130 ty::Uint(uint_ty) => Some(match uint_ty {
2131 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
2132 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
2133 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
2134 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
2135 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
2136 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
2145 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2146 let val = constant(cx, cx.typeck_results(), expr)?.0;
2147 if let Constant::Int(const_int) = val {
2148 match *cx.typeck_results().expr_ty(expr).kind() {
2149 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2150 ty::Uint(_) => Some(FullInt::U(const_int)),
2158 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
2159 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2162 INVALID_UPCAST_COMPARISONS,
2165 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2166 snippet(cx, cast_val.span, "the expression"),
2167 if always { "true" } else { "false" },
2173 fn upcast_comparison_bounds_err<'tcx>(
2174 cx: &LateContext<'tcx>,
2176 rel: comparisons::Rel,
2177 lhs_bounds: Option<(FullInt, FullInt)>,
2178 lhs: &'tcx Expr<'_>,
2179 rhs: &'tcx Expr<'_>,
2182 use crate::utils::comparisons::Rel;
2184 if let Some((lb, ub)) = lhs_bounds {
2185 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2186 if rel == Rel::Eq || rel == Rel::Ne {
2187 if norm_rhs_val < lb || norm_rhs_val > ub {
2188 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2190 } else if match rel {
2205 Rel::Eq | Rel::Ne => unreachable!(),
2207 err_upcast_comparison(cx, span, lhs, true)
2208 } else if match rel {
2223 Rel::Eq | Rel::Ne => unreachable!(),
2225 err_upcast_comparison(cx, span, lhs, false)
2231 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
2232 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2233 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2234 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2235 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2241 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2242 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2244 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2245 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2250 declare_clippy_lint! {
2251 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2252 /// over different hashers and implicitly defaulting to the default hashing
2253 /// algorithm (`SipHash`).
2255 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2258 /// **Known problems:** Suggestions for replacing constructors can contain
2259 /// false-positives. Also applying suggestions can require modification of other
2260 /// pieces of code, possibly including external crates.
2264 /// # use std::collections::HashMap;
2265 /// # use std::hash::{Hash, BuildHasher};
2266 /// # trait Serialize {};
2267 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2269 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2271 /// could be rewritten as
2273 /// # use std::collections::HashMap;
2274 /// # use std::hash::{Hash, BuildHasher};
2275 /// # trait Serialize {};
2276 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2278 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2280 pub IMPLICIT_HASHER,
2282 "missing generalization over different hashers"
2285 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2287 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
2288 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2289 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
2290 use rustc_span::BytePos;
2292 fn suggestion<'tcx>(
2293 cx: &LateContext<'tcx>,
2294 diag: &mut DiagnosticBuilder<'_>,
2295 generics_span: Span,
2296 generics_suggestion_span: Span,
2297 target: &ImplicitHasherType<'_>,
2298 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2300 let generics_snip = snippet(cx, generics_span, "");
2302 let generics_snip = if generics_snip.is_empty() {
2305 &generics_snip[1..generics_snip.len() - 1]
2310 "consider adding a type parameter",
2313 generics_suggestion_span,
2315 "<{}{}S: ::std::hash::BuildHasher{}>",
2317 if generics_snip.is_empty() { "" } else { ", " },
2318 if vis.suggestions.is_empty() {
2321 // request users to add `Default` bound so that generic constructors can be used
2328 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2333 if !vis.suggestions.is_empty() {
2334 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
2338 if !cx.access_levels.is_exported(item.hir_id()) {
2343 ItemKind::Impl(ref impl_) => {
2344 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2345 vis.visit_ty(impl_.self_ty);
2347 for target in &vis.found {
2348 if differing_macro_contexts(item.span, target.span()) {
2352 let generics_suggestion_span = impl_.generics.span.substitute_dummy({
2353 let pos = snippet_opt(cx, item.span.until(target.span()))
2354 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2355 if let Some(pos) = pos {
2356 Span::new(pos, pos, item.span.data().ctxt)
2362 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2363 for item in impl_.items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2364 ctr_vis.visit_impl_item(item);
2372 "impl for `{}` should be generalized over different hashers",
2376 suggestion(cx, diag, impl_.generics.span, generics_suggestion_span, target, ctr_vis);
2381 ItemKind::Fn(ref sig, ref generics, body_id) => {
2382 let body = cx.tcx.hir().body(body_id);
2384 for ty in sig.decl.inputs {
2385 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2388 for target in &vis.found {
2389 if in_external_macro(cx.sess(), generics.span) {
2392 let generics_suggestion_span = generics.span.substitute_dummy({
2393 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2395 let i = snip.find("fn")?;
2396 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2398 .expect("failed to create span for type parameters");
2399 Span::new(pos, pos, item.span.data().ctxt)
2402 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2403 ctr_vis.visit_body(body);
2410 "parameter of type `{}` should be generalized over different hashers",
2414 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2425 enum ImplicitHasherType<'tcx> {
2426 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2427 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2430 impl<'tcx> ImplicitHasherType<'tcx> {
2431 /// Checks that `ty` is a target type without a `BuildHasher`.
2432 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2433 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2434 let params: Vec<_> = path
2442 .filter_map(|arg| match arg {
2443 GenericArg::Type(ty) => Some(ty),
2447 let params_len = params.len();
2449 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2451 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2452 Some(ImplicitHasherType::HashMap(
2455 snippet(cx, params[0].span, "K"),
2456 snippet(cx, params[1].span, "V"),
2458 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2459 Some(ImplicitHasherType::HashSet(
2462 snippet(cx, params[0].span, "T"),
2472 fn type_name(&self) -> &'static str {
2474 ImplicitHasherType::HashMap(..) => "HashMap",
2475 ImplicitHasherType::HashSet(..) => "HashSet",
2479 fn type_arguments(&self) -> String {
2481 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2482 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2486 fn ty(&self) -> Ty<'tcx> {
2488 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2492 fn span(&self) -> Span {
2494 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2499 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2500 cx: &'a LateContext<'tcx>,
2501 found: Vec<ImplicitHasherType<'tcx>>,
2504 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2505 fn new(cx: &'a LateContext<'tcx>) -> Self {
2506 Self { cx, found: vec![] }
2510 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2511 type Map = Map<'tcx>;
2513 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2514 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2515 self.found.push(target);
2521 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2522 NestedVisitorMap::None
2526 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2527 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2528 cx: &'a LateContext<'tcx>,
2529 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
2530 target: &'b ImplicitHasherType<'tcx>,
2531 suggestions: BTreeMap<Span, String>,
2534 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2535 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2538 maybe_typeck_results: cx.maybe_typeck_results(),
2540 suggestions: BTreeMap::new(),
2545 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2546 type Map = Map<'tcx>;
2548 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2549 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
2550 walk_body(self, body);
2551 self.maybe_typeck_results = old_maybe_typeck_results;
2554 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2556 if let ExprKind::Call(ref fun, ref args) = e.kind;
2557 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2558 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2560 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
2564 if match_path(ty_path, &paths::HASHMAP) {
2565 if method.ident.name == sym::new {
2567 .insert(e.span, "HashMap::default()".to_string());
2568 } else if method.ident.name == sym!(with_capacity) {
2569 self.suggestions.insert(
2572 "HashMap::with_capacity_and_hasher({}, Default::default())",
2573 snippet(self.cx, args[0].span, "capacity"),
2577 } else if match_path(ty_path, &paths::HASHSET) {
2578 if method.ident.name == sym::new {
2580 .insert(e.span, "HashSet::default()".to_string());
2581 } else if method.ident.name == sym!(with_capacity) {
2582 self.suggestions.insert(
2585 "HashSet::with_capacity_and_hasher({}, Default::default())",
2586 snippet(self.cx, args[0].span, "capacity"),
2597 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2598 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2602 declare_clippy_lint! {
2603 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2605 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2606 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2609 /// **Known problems:** None.
2615 /// *(r as *const _ as *mut _) += 1;
2620 /// Instead consider using interior mutability types.
2623 /// use std::cell::UnsafeCell;
2625 /// fn x(r: &UnsafeCell<i32>) {
2631 pub CAST_REF_TO_MUT,
2633 "a cast of reference to a mutable pointer"
2636 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2638 impl<'tcx> LateLintPass<'tcx> for RefToMut {
2639 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2641 if let ExprKind::Unary(UnOp::Deref, e) = &expr.kind;
2642 if let ExprKind::Cast(e, t) = &e.kind;
2643 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2644 if let ExprKind::Cast(e, t) = &e.kind;
2645 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2646 if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
2652 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",
2659 const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0);
2661 declare_clippy_lint! {
2662 /// **What it does:**
2663 /// Checks for `as` casts between raw pointers without changing its mutability,
2664 /// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
2666 /// **Why is this bad?**
2667 /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
2668 /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
2670 /// **Known problems:** None.
2675 /// let ptr: *const u32 = &42_u32;
2676 /// let mut_ptr: *mut u32 = &mut 42_u32;
2677 /// let _ = ptr as *const i32;
2678 /// let _ = mut_ptr as *mut i32;
2682 /// let ptr: *const u32 = &42_u32;
2683 /// let mut_ptr: *mut u32 = &mut 42_u32;
2684 /// let _ = ptr.cast::<i32>();
2685 /// let _ = mut_ptr.cast::<i32>();
2689 "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
2692 pub struct PtrAsPtr {
2693 msrv: Option<RustcVersion>,
2698 pub fn new(msrv: Option<RustcVersion>) -> Self {
2703 impl_lint_pass!(PtrAsPtr => [PTR_AS_PTR]);
2705 impl<'tcx> LateLintPass<'tcx> for PtrAsPtr {
2706 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2707 if !meets_msrv(self.msrv.as_ref(), &PTR_AS_PTR_MSRV) {
2711 if expr.span.from_expansion() {
2716 if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind;
2717 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr));
2718 if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind();
2719 if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind();
2720 if matches!((from_mutbl, to_mutbl),
2721 (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut));
2722 // The `U` in `pointer::cast` have to be `Sized`
2723 // as explained here: https://github.com/rust-lang/rust/issues/60602.
2724 if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env);
2726 let mut applicability = Applicability::MachineApplicable;
2727 let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability);
2728 let turbofish = match &cast_to_hir_ty.kind {
2729 TyKind::Infer => Cow::Borrowed(""),
2730 TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
2731 _ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
2737 "`as` casting between raw pointers without changing its mutability",
2738 "try `pointer::cast`, a safer alternative",
2739 format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
2746 extract_msrv_attr!(LateContext);