1 #![allow(rustc::default_hash_types)]
4 use std::cmp::Ordering;
5 use std::collections::BTreeMap;
7 use if_chain::if_chain;
8 use rustc_ast::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy};
9 use rustc_errors::{Applicability, DiagnosticBuilder};
11 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
13 BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem,
14 ImplItemKind, Item, ItemKind, Lifetime, Local, MatchSource, MutTy, Mutability, Node, QPath, Stmt, StmtKind,
15 TraitFn, TraitItem, TraitItemKind, TyKind, UnOp,
17 use rustc_lint::{LateContext, LateLintPass, LintContext};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::lint::in_external_macro;
20 use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeckResults};
21 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
22 use rustc_span::hygiene::{ExpnKind, MacroKind};
23 use rustc_span::source_map::Span;
24 use rustc_span::symbol::sym;
25 use rustc_target::abi::LayoutOf;
26 use rustc_target::spec::abi::Abi;
27 use rustc_typeck::hir_ty_to_ty;
29 use crate::consts::{constant, Constant};
30 use crate::utils::paths;
32 clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item,
33 last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral,
34 qpath_res, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite,
35 span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
38 declare_clippy_lint! {
39 /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
40 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
42 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
43 /// the heap. So if you `Box` it, you just add another level of indirection
44 /// without any benefit whatsoever.
46 /// **Known problems:** None.
51 /// values: Box<Vec<Foo>>,
64 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
67 declare_clippy_lint! {
68 /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
69 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
71 /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
72 /// the heap. So if you `Box` its contents, you just add another level of indirection.
74 /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
80 /// values: Vec<Box<i32>>,
93 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
96 declare_clippy_lint! {
97 /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
100 /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
101 /// represents an optional optional value which is logically the same thing as an optional
102 /// value but has an unneeded extra level of wrapping.
104 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
105 /// consider a custom `enum` instead, with clear names for each case.
107 /// **Known problems:** None.
111 /// fn get_data() -> Option<Option<u32>> {
119 /// pub enum Contents {
120 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
121 /// NotYetFetched, // Was Some(None)
122 /// None, // Was None
125 /// fn get_data() -> Contents {
131 "usage of `Option<Option<T>>`"
134 declare_clippy_lint! {
135 /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
136 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
138 /// **Why is this bad?** Gankro says:
140 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
141 /// pointers and indirection.
142 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
144 /// > "only" amortized for push/pop, should be faster in the general case for
145 /// almost every possible
146 /// > workload, and isn't even amortized at all if you can predict the capacity
149 /// > `LinkedList`s are only really good if you're doing a lot of merging or
150 /// splitting of lists.
151 /// > This is because they can just mangle some pointers instead of actually
152 /// copying the data. Even
153 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
154 /// can still be better
155 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
157 /// **Known problems:** False positives – the instances where using a
158 /// `LinkedList` makes sense are few and far between, but they can still happen.
162 /// # use std::collections::LinkedList;
163 /// let x: LinkedList<usize> = LinkedList::new();
167 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
170 declare_clippy_lint! {
171 /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
172 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
174 /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
177 /// **Known problems:** None.
181 /// fn foo(bar: &Box<T>) { ... }
187 /// fn foo(bar: &T) { ... }
191 "a borrow of a boxed type"
194 declare_clippy_lint! {
195 /// **What it does:** Checks for use of redundant allocations anywhere in the code.
197 /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
198 /// add an unnecessary level of indirection.
200 /// **Known problems:** None.
204 /// # use std::rc::Rc;
205 /// fn foo(bar: Rc<&usize>) {}
211 /// fn foo(bar: &usize) {}
213 pub REDUNDANT_ALLOCATION,
215 "redundant allocation"
218 declare_clippy_lint! {
219 /// **What it does:** Checks for Rc<T> and Arc<T> when T is a mutable buffer type such as String or Vec
221 /// **Why is this bad?** Expressions such as Rc<String> have no advantage over Rc<str>, since
222 /// it is larger and involves an extra level of indirection, and doesn't implement Borrow<str>.
224 /// While mutating a buffer type would still be possible with Rc::get_mut(), it only
225 /// works if there are no additional references yet, which defeats the purpose of
226 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
227 /// type with an interior mutable container (such as RefCell or Mutex) would normally
230 /// **Known problems:** None.
234 /// # use std::rc::Rc;
235 /// fn foo(interned: Rc<String>) { ... }
241 /// fn foo(interned: Rc<str>) { ... }
245 "shared ownership of a buffer type"
249 vec_box_size_threshold: u64,
252 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER]);
254 impl<'tcx> LateLintPass<'tcx> for Types {
255 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
256 // Skip trait implementations; see issue #605.
257 if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
258 if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
263 self.check_fn_decl(cx, decl);
266 fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) {
267 self.check_ty(cx, &field.ty, false);
270 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
272 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
273 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
278 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
279 if let Some(ref ty) = local.ty {
280 self.check_ty(cx, ty, true);
285 /// Checks if `qpath` has last segment with type parameter matching `path`
286 fn match_type_parameter(cx: &LateContext<'_>, qpath: &QPath<'_>, path: &[&str]) -> Option<Span> {
287 let last = last_path_segment(qpath);
289 if let Some(ref params) = last.args;
290 if !params.parenthesized;
291 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
292 GenericArg::Type(ty) => Some(ty),
295 if let TyKind::Path(ref qpath) = ty.kind;
296 if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
297 if match_def_path(cx, did, path);
299 return Some(ty.span);
305 fn match_buffer_type(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<&'static str> {
306 if match_type_parameter(cx, qpath, &paths::STRING).is_some() {
309 if match_type_parameter(cx, qpath, &paths::OS_STRING).is_some() {
310 return Some("std::ffi::OsStr");
312 if match_type_parameter(cx, qpath, &paths::PATH_BUF).is_some() {
313 return Some("std::path::Path");
318 fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<Span> {
319 let last = last_path_segment(qpath);
321 if let Some(ref params) = last.args;
322 if !params.parenthesized;
323 if let Some(ty) = params.args.iter().find_map(|arg| match arg {
324 GenericArg::Type(ty) => Some(ty),
327 if let TyKind::Rptr(..) = ty.kind;
329 return Some(ty.span);
336 pub fn new(vec_box_size_threshold: u64) -> Self {
337 Self { vec_box_size_threshold }
340 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
341 for input in decl.inputs {
342 self.check_ty(cx, input, false);
345 if let FnRetTy::Return(ref ty) = decl.output {
346 self.check_ty(cx, ty, false);
350 /// Recursively check for `TypePass` lints in the given type. Stop at the first
353 /// The parameter `is_local` distinguishes the context of the type; types from
354 /// local bindings should only be checked for the `BORROWED_BOX` lint.
355 #[allow(clippy::too_many_lines)]
356 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
357 if hir_ty.span.from_expansion() {
361 TyKind::Path(ref qpath) if !is_local => {
362 let hir_id = hir_ty.hir_id;
363 let res = qpath_res(cx, qpath, hir_id);
364 if let Some(def_id) = res.opt_def_id() {
365 if Some(def_id) == cx.tcx.lang_items().owned_box() {
366 if let Some(span) = match_borrows_parameter(cx, qpath) {
367 let mut applicability = Applicability::MachineApplicable;
370 REDUNDANT_ALLOCATION,
372 "usage of `Box<&T>`",
374 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
377 return; // don't recurse into the type
379 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
384 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
386 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
388 return; // don't recurse into the type
390 } else if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
391 if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) {
392 let mut applicability = Applicability::MachineApplicable;
395 REDUNDANT_ALLOCATION,
397 "usage of `Rc<Rc<T>>`",
399 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
402 return; // don't recurse into the type
404 if match_type_parameter(cx, qpath, &paths::BOX).is_some() {
405 let box_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
406 GenericArg::Type(ty) => match &ty.kind {
407 TyKind::Path(qpath) => qpath,
412 let inner_span = match &last_path_segment(&box_ty).args.unwrap().args[0] {
413 GenericArg::Type(ty) => ty.span,
416 let mut applicability = Applicability::MachineApplicable;
419 REDUNDANT_ALLOCATION,
421 "usage of `Rc<Box<T>>`",
425 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
429 return; // don't recurse into the type
431 if let Some(alternate) = match_buffer_type(cx, qpath) {
436 "usage of `Rc<T>` when T is a buffer type",
438 format!("Rc<{}>", alternate),
439 Applicability::MachineApplicable,
441 return; // don't recurse into the type
443 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
444 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
445 GenericArg::Type(ty) => match &ty.kind {
446 TyKind::Path(qpath) => qpath,
451 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
452 GenericArg::Type(ty) => ty.span,
455 let mut applicability = Applicability::MachineApplicable;
460 "usage of `Rc<T>` when T is a buffer type",
464 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
466 Applicability::MachineApplicable,
468 return; // don't recurse into the type
470 if let Some(span) = match_borrows_parameter(cx, qpath) {
471 let mut applicability = Applicability::MachineApplicable;
474 REDUNDANT_ALLOCATION,
478 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
481 return; // don't recurse into the type
483 } else if cx.tcx.is_diagnostic_item(sym::Arc, def_id) {
484 if let Some(alternate) = match_buffer_type(cx, qpath) {
489 "usage of `Arc<T>` when T is a buffer type",
491 format!("Arc<{}>", alternate),
492 Applicability::MachineApplicable,
494 return; // don't recurse into the type
496 if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
497 let vec_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
498 GenericArg::Type(ty) => match &ty.kind {
499 TyKind::Path(qpath) => qpath,
504 let inner_span = match &last_path_segment(&vec_ty).args.unwrap().args[0] {
505 GenericArg::Type(ty) => ty.span,
508 let mut applicability = Applicability::MachineApplicable;
513 "usage of `Arc<T>` when T is a buffer type",
517 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
519 Applicability::MachineApplicable,
521 return; // don't recurse into the type
523 } else if cx.tcx.is_diagnostic_item(sym!(vec_type), def_id) {
525 // Get the _ part of Vec<_>
526 if let Some(ref last) = last_path_segment(qpath).args;
527 if let Some(ty) = last.args.iter().find_map(|arg| match arg {
528 GenericArg::Type(ty) => Some(ty),
531 // ty is now _ at this point
532 if let TyKind::Path(ref ty_qpath) = ty.kind;
533 let res = qpath_res(cx, ty_qpath, ty.hir_id);
534 if let Some(def_id) = res.opt_def_id();
535 if Some(def_id) == cx.tcx.lang_items().owned_box();
536 // At this point, we know ty is Box<T>, now get T
537 if let Some(ref last) = last_path_segment(ty_qpath).args;
538 if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
539 GenericArg::Type(ty) => Some(ty),
542 let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
543 if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env);
544 if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes());
545 if ty_ty_size <= self.vec_box_size_threshold;
551 "`Vec<T>` is already on the heap, the boxing is unnecessary.",
553 format!("Vec<{}>", ty_ty),
554 Applicability::MachineApplicable,
556 return; // don't recurse into the type
559 } else if cx.tcx.is_diagnostic_item(sym!(option_type), def_id) {
560 if match_type_parameter(cx, qpath, &paths::OPTION).is_some() {
565 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
566 enum if you need to distinguish all 3 cases",
568 return; // don't recurse into the type
570 } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
575 "I see you're using a LinkedList! Perhaps you meant some other data structure?",
577 "a `VecDeque` might work",
579 return; // don't recurse into the type
583 QPath::Resolved(Some(ref ty), ref p) => {
584 self.check_ty(cx, ty, is_local);
585 for ty in p.segments.iter().flat_map(|seg| {
588 .map_or_else(|| [].iter(), |params| params.args.iter())
589 .filter_map(|arg| match arg {
590 GenericArg::Type(ty) => Some(ty),
594 self.check_ty(cx, ty, is_local);
597 QPath::Resolved(None, ref p) => {
598 for ty in p.segments.iter().flat_map(|seg| {
601 .map_or_else(|| [].iter(), |params| params.args.iter())
602 .filter_map(|arg| match arg {
603 GenericArg::Type(ty) => Some(ty),
607 self.check_ty(cx, ty, is_local);
610 QPath::TypeRelative(ref ty, ref seg) => {
611 self.check_ty(cx, ty, is_local);
612 if let Some(ref params) = seg.args {
613 for ty in params.args.iter().filter_map(|arg| match arg {
614 GenericArg::Type(ty) => Some(ty),
617 self.check_ty(cx, ty, is_local);
621 QPath::LangItem(..) => {},
624 TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
626 TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
627 self.check_ty(cx, ty, is_local)
629 TyKind::Tup(tys) => {
631 self.check_ty(cx, ty, is_local);
640 cx: &LateContext<'_>,
641 hir_ty: &hir::Ty<'_>,
646 match mut_ty.ty.kind {
647 TyKind::Path(ref qpath) => {
648 let hir_id = mut_ty.ty.hir_id;
649 let def = qpath_res(cx, qpath, hir_id);
651 if let Some(def_id) = def.opt_def_id();
652 if Some(def_id) == cx.tcx.lang_items().owned_box();
653 if let QPath::Resolved(None, ref path) = *qpath;
654 if let [ref bx] = *path.segments;
655 if let Some(ref params) = bx.args;
656 if !params.parenthesized;
657 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
658 GenericArg::Type(ty) => Some(ty),
662 if is_any_trait(inner) {
663 // Ignore `Box<Any>` types; see issue #1884 for details.
667 let ltopt = if lt.is_elided() {
670 format!("{} ", lt.name.ident().as_str())
673 if mut_ty.mutbl == Mutability::Mut {
674 // Ignore `&mut Box<T>` types; see issue #2907 for
682 "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
687 &snippet(cx, inner.span, "..")
689 // To make this `MachineApplicable`, at least one needs to check if it isn't a trait item
690 // because the trait impls of it will break otherwise;
691 // and there may be other cases that result in invalid code.
692 // For example, type coercion doesn't work nicely.
693 Applicability::Unspecified,
695 return; // don't recurse into the type
698 self.check_ty(cx, &mut_ty.ty, is_local);
700 _ => self.check_ty(cx, &mut_ty.ty, is_local),
705 // Returns true if given type is `Any` trait.
706 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
708 if let TyKind::TraitObject(ref traits, _) = t.kind;
709 if !traits.is_empty();
710 // Only Send/Sync can be used as additional traits, so it is enough to
711 // check only the first trait.
712 if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
721 declare_clippy_lint! {
722 /// **What it does:** Checks for binding a unit value.
724 /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
725 /// binding one is kind of pointless.
727 /// **Known problems:** None.
737 "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
740 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
742 impl<'tcx> LateLintPass<'tcx> for LetUnitValue {
743 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
744 if let StmtKind::Local(ref local) = stmt.kind {
745 if is_unit(cx.typeck_results().pat_ty(&local.pat)) {
746 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
749 if higher::is_from_for_desugar(local) {
756 "this let-binding has unit value",
758 if let Some(expr) = &local.init {
759 let snip = snippet_with_macro_callsite(cx, expr.span, "()");
760 diag.span_suggestion(
762 "omit the `let` binding",
763 format!("{};", snip),
764 Applicability::MachineApplicable, // snippet
774 declare_clippy_lint! {
775 /// **What it does:** Checks for comparisons to unit. This includes all binary
776 /// comparisons (like `==` and `<`) and asserts.
778 /// **Why is this bad?** Unit is always equal to itself, and thus is just a
779 /// clumsily written constant. Mostly this happens when someone accidentally
780 /// adds semicolons at the end of the operands.
782 /// **Known problems:** None.
813 /// assert_eq!({ foo(); }, { bar(); });
815 /// will always succeed
818 "comparing unit values"
821 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
823 impl<'tcx> LateLintPass<'tcx> for UnitCmp {
824 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
825 if expr.span.from_expansion() {
826 if let Some(callee) = expr.span.source_callee() {
827 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
828 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
830 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
831 let result = match &*symbol.as_str() {
832 "assert_eq" | "debug_assert_eq" => "succeed",
833 "assert_ne" | "debug_assert_ne" => "fail",
841 "`{}` of unit values detected. This will always {}",
852 if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
854 if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
855 let result = match op {
856 BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
864 "{}-comparison of unit values detected. This will always be {}",
874 declare_clippy_lint! {
875 /// **What it does:** Checks for passing a unit value as an argument to a function without using a
876 /// unit literal (`()`).
878 /// **Why is this bad?** This is likely the result of an accidental semicolon.
880 /// **Known problems:** None.
891 "passing unit to a function"
894 declare_lint_pass!(UnitArg => [UNIT_ARG]);
896 impl<'tcx> LateLintPass<'tcx> for UnitArg {
897 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
898 if expr.span.from_expansion() {
902 // apparently stuff in the desugaring of `?` can trigger this
903 // so check for that here
904 // only the calls to `Try::from_error` is marked as desugared,
905 // so we need to check both the current Expr and its parent.
906 if is_questionmark_desugar_marked_call(expr) {
910 let map = &cx.tcx.hir();
911 let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
912 if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
913 if is_questionmark_desugar_marked_call(parent_expr);
920 ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => {
921 let args_to_recover = args
924 if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) {
925 !matches!(&arg.kind, ExprKind::Match(.., MatchSource::TryDesugar))
930 .collect::<Vec<_>>();
931 if !args_to_recover.is_empty() {
932 lint_unit_args(cx, expr, &args_to_recover);
940 fn fmt_stmts_and_call(
941 cx: &LateContext<'_>,
942 call_expr: &Expr<'_>,
944 args_snippets: &[impl AsRef<str>],
945 non_empty_block_args_snippets: &[impl AsRef<str>],
947 let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
948 let call_snippet_with_replacements = args_snippets
950 .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
952 let mut stmts_and_call = non_empty_block_args_snippets
954 .map(|it| it.as_ref().to_owned())
955 .collect::<Vec<_>>();
956 stmts_and_call.push(call_snippet_with_replacements);
957 stmts_and_call = stmts_and_call
959 .map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
962 let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
963 // expr is not in a block statement or result expression position, wrap in a block
964 let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
965 if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
966 let block_indent = call_expr_indent + 4;
967 stmts_and_call_snippet =
968 reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
969 stmts_and_call_snippet = format!(
971 " ".repeat(block_indent),
972 &stmts_and_call_snippet,
973 " ".repeat(call_expr_indent)
976 stmts_and_call_snippet
979 fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
980 let mut applicability = Applicability::MachineApplicable;
981 let (singular, plural) = if args_to_recover.len() > 1 {
990 &format!("passing {}unit value{} to a function", singular, plural),
997 if let ExprKind::Block(block, _) = arg.kind;
998 if block.expr.is_none();
999 if let Some(last_stmt) = block.stmts.iter().last();
1000 if let StmtKind::Semi(last_expr) = last_stmt.kind;
1001 if let Some(snip) = snippet_opt(cx, last_expr.span);
1013 .for_each(|(span, sugg)| {
1016 "remove the semicolon from the last statement in the block",
1018 Applicability::MaybeIncorrect,
1021 applicability = Applicability::MaybeIncorrect;
1024 let arg_snippets: Vec<String> = args_to_recover
1026 .filter_map(|arg| snippet_opt(cx, arg.span))
1028 let arg_snippets_without_empty_blocks: Vec<String> = args_to_recover
1030 .filter(|arg| !is_empty_block(arg))
1031 .filter_map(|arg| snippet_opt(cx, arg.span))
1034 if let Some(call_snippet) = snippet_opt(cx, expr.span) {
1035 let sugg = fmt_stmts_and_call(
1040 &arg_snippets_without_empty_blocks,
1043 if arg_snippets_without_empty_blocks.is_empty() {
1044 db.multipart_suggestion(
1045 &format!("use {}unit literal{} instead", singular, plural),
1048 .map(|arg| (arg.span, "()".to_string()))
1049 .collect::<Vec<_>>(),
1053 let plural = arg_snippets_without_empty_blocks.len() > 1;
1054 let empty_or_s = if plural { "s" } else { "" };
1055 let it_or_them = if plural { "them" } else { "it" };
1059 "{}move the expression{} in front of the call and replace {} with the unit literal `()`",
1060 or, empty_or_s, it_or_them
1071 fn is_empty_block(expr: &Expr<'_>) -> bool {
1076 stmts: &[], expr: None, ..
1083 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
1084 use rustc_span::hygiene::DesugaringKind;
1085 if let ExprKind::Call(ref callee, _) = expr.kind {
1086 callee.span.is_desugaring(DesugaringKind::QuestionMark)
1092 fn is_unit(ty: Ty<'_>) -> bool {
1093 matches!(ty.kind(), ty::Tuple(slice) if slice.is_empty())
1096 fn is_unit_literal(expr: &Expr<'_>) -> bool {
1097 matches!(expr.kind, ExprKind::Tup(ref slice) if slice.is_empty())
1100 declare_clippy_lint! {
1101 /// **What it does:** Checks for casts from any numerical to a float type where
1102 /// the receiving type cannot store all values from the original type without
1103 /// rounding errors. This possible rounding is to be expected, so this lint is
1104 /// `Allow` by default.
1106 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
1107 /// or any 64-bit integer to `f64`.
1109 /// **Why is this bad?** It's not bad at all. But in some applications it can be
1110 /// helpful to know where precision loss can take place. This lint can help find
1111 /// those places in the code.
1113 /// **Known problems:** None.
1117 /// let x = u64::MAX;
1120 pub CAST_PRECISION_LOSS,
1122 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
1125 declare_clippy_lint! {
1126 /// **What it does:** Checks for casts from a signed to an unsigned numerical
1127 /// type. In this case, negative values wrap around to large positive values,
1128 /// which can be quite surprising in practice. However, as the cast works as
1129 /// defined, this lint is `Allow` by default.
1131 /// **Why is this bad?** Possibly surprising results. You can activate this lint
1132 /// as a one-time check to see where numerical wrapping can arise.
1134 /// **Known problems:** None.
1139 /// y as u128; // will return 18446744073709551615
1143 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
1146 declare_clippy_lint! {
1147 /// **What it does:** Checks for casts between numerical types that may
1148 /// truncate large values. This is expected behavior, so the cast is `Allow` by
1151 /// **Why is this bad?** In some problem domains, it is good practice to avoid
1152 /// truncation. This lint can be activated to help assess where additional
1153 /// checks could be beneficial.
1155 /// **Known problems:** None.
1159 /// fn as_u8(x: u64) -> u8 {
1163 pub CAST_POSSIBLE_TRUNCATION,
1165 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
1168 declare_clippy_lint! {
1169 /// **What it does:** Checks for casts from an unsigned type to a signed type of
1170 /// the same size. Performing such a cast is a 'no-op' for the compiler,
1171 /// i.e., nothing is changed at the bit level, and the binary representation of
1172 /// the value is reinterpreted. This can cause wrapping if the value is too big
1173 /// for the target signed type. However, the cast works as defined, so this lint
1174 /// is `Allow` by default.
1176 /// **Why is this bad?** While such a cast is not bad in itself, the results can
1177 /// be surprising when this is not the intended behavior, as demonstrated by the
1180 /// **Known problems:** None.
1184 /// u32::MAX as i32; // will yield a value of `-1`
1186 pub CAST_POSSIBLE_WRAP,
1188 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
1191 declare_clippy_lint! {
1192 /// **What it does:** Checks for casts between numerical types that may
1193 /// be replaced by safe conversion functions.
1195 /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
1196 /// conversions, including silently lossy conversions. Conversion functions such
1197 /// as `i32::from` will only perform lossless conversions. Using the conversion
1198 /// functions prevents conversions from turning into silent lossy conversions if
1199 /// the types of the input expressions ever change, and make it easier for
1200 /// people reading the code to know that the conversion is lossless.
1202 /// **Known problems:** None.
1206 /// fn as_u64(x: u8) -> u64 {
1211 /// Using `::from` would look like this:
1214 /// fn as_u64(x: u8) -> u64 {
1220 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
1223 declare_clippy_lint! {
1224 /// **What it does:** Checks for casts to the same type.
1226 /// **Why is this bad?** It's just unnecessary.
1228 /// **Known problems:** None.
1232 /// let _ = 2i32 as i32;
1234 pub UNNECESSARY_CAST,
1236 "cast to the same type, e.g., `x as i32` where `x: i32`"
1239 declare_clippy_lint! {
1240 /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
1241 /// more-strictly-aligned pointer
1243 /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
1246 /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
1247 /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
1248 /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
1252 /// let _ = (&1u8 as *const u8) as *const u16;
1253 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
1255 pub CAST_PTR_ALIGNMENT,
1257 "cast from a pointer to a more-strictly-aligned pointer"
1260 declare_clippy_lint! {
1261 /// **What it does:** Checks for casts of function pointers to something other than usize
1263 /// **Why is this bad?**
1264 /// Casting a function pointer to anything other than usize/isize is not portable across
1265 /// architectures, because you end up losing bits if the target type is too small or end up with a
1266 /// bunch of extra bits that waste space and add more instructions to the final binary than
1267 /// strictly necessary for the problem
1269 /// Casting to isize also doesn't make sense since there are no signed addresses.
1275 /// fn fun() -> i32 { 1 }
1276 /// let a = fun as i64;
1279 /// fn fun2() -> i32 { 1 }
1280 /// let a = fun2 as usize;
1282 pub FN_TO_NUMERIC_CAST,
1284 "casting a function pointer to a numeric type other than usize"
1287 declare_clippy_lint! {
1288 /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1291 /// **Why is this bad?**
1292 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1293 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1294 /// a comment) to perform the truncation.
1300 /// fn fn1() -> i16 {
1303 /// let _ = fn1 as i32;
1305 /// // Better: Cast to usize first, then comment with the reason for the truncation
1306 /// fn fn2() -> i16 {
1309 /// let fn_ptr = fn2 as usize;
1310 /// let fn_ptr_truncated = fn_ptr as i32;
1312 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1314 "casting a function pointer to a numeric type not wide enough to store the address"
1317 /// Returns the size in bits of an integral type.
1318 /// Will return 0 if the type is not an int or uint variant
1319 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1321 ty::Int(i) => match i {
1322 IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1329 ty::Uint(i) => match i {
1330 UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1335 UintTy::U128 => 128,
1341 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1342 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
1345 fn span_precision_loss_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1346 let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1347 let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1348 let arch_dependent_str = "on targets with 64-bit wide pointers ";
1349 let from_nbits_str = if arch_dependent {
1351 } else if is_isize_or_usize(cast_from) {
1352 "32 or 64".to_owned()
1354 int_ty_to_nbits(cast_from, cx.tcx).to_string()
1358 CAST_PRECISION_LOSS,
1361 "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1362 but `{1}`'s mantissa is only {4} bits wide)",
1364 if cast_to_f64 { "f64" } else { "f32" },
1365 if arch_dependent { arch_dependent_str } else { "" },
1372 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1373 if let ExprKind::Binary(_, _, _) = op.kind {
1374 if snip.starts_with('(') && snip.ends_with(')') {
1381 fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1382 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1383 if in_constant(cx, expr.hir_id) {
1386 // The suggestion is to use a function call, so if the original expression
1387 // has parens on the outside, they are no longer needed.
1388 let mut applicability = Applicability::MachineApplicable;
1389 let opt = snippet_opt(cx, op.span);
1390 let sugg = opt.as_ref().map_or_else(
1392 applicability = Applicability::HasPlaceholders;
1396 if should_strip_parens(op, snip) {
1397 &snip[1..snip.len() - 1]
1409 "casting `{}` to `{}` may become silently lossy if you later change the type",
1413 format!("{}::from({})", cast_to, sugg),
1424 fn check_loss_of_sign(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1425 if !cast_from.is_signed() || cast_to.is_signed() {
1429 // don't lint for positive constants
1430 let const_val = constant(cx, &cx.typeck_results(), op);
1432 if let Some((const_val, _)) = const_val;
1433 if let Constant::Int(n) = const_val;
1434 if let ty::Int(ity) = *cast_from.kind();
1435 if sext(cx.tcx, n, ity) >= 0;
1441 // don't lint for the result of methods that always return non-negative values
1442 if let ExprKind::MethodCall(ref path, _, _, _) = op.kind {
1443 let mut method_name = path.ident.name.as_str();
1444 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1447 if method_name == "unwrap";
1448 if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1449 if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
1451 method_name = inner_path.ident.name.as_str();
1455 if allowed_methods.iter().any(|&name| method_name == name) {
1465 "casting `{}` to `{}` may lose the sign of the value",
1471 fn check_truncation_and_wrapping(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1472 let arch_64_suffix = " on targets with 64-bit wide pointers";
1473 let arch_32_suffix = " on targets with 32-bit wide pointers";
1474 let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1475 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1476 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1477 let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1478 match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1479 (true, true) | (false, false) => (
1480 to_nbits < from_nbits,
1482 to_nbits == from_nbits && cast_unsigned_to_signed,
1492 to_nbits <= 32 && cast_unsigned_to_signed,
1498 cast_unsigned_to_signed,
1499 if from_nbits == 64 {
1506 if span_truncation {
1509 CAST_POSSIBLE_TRUNCATION,
1512 "casting `{}` to `{}` may truncate the value{}",
1515 match suffix_truncation {
1516 ArchSuffix::_32 => arch_32_suffix,
1517 ArchSuffix::_64 => arch_64_suffix,
1518 ArchSuffix::None => "",
1529 "casting `{}` to `{}` may wrap around the value{}",
1533 ArchSuffix::_32 => arch_32_suffix,
1534 ArchSuffix::_64 => arch_64_suffix,
1535 ArchSuffix::None => "",
1542 fn check_lossless(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1543 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1544 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1545 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1546 if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1548 span_lossless_lint(cx, expr, op, cast_from, cast_to);
1552 declare_lint_pass!(Casts => [
1553 CAST_PRECISION_LOSS,
1555 CAST_POSSIBLE_TRUNCATION,
1561 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1564 // Check if the given type is either `core::ffi::c_void` or
1565 // one of the platform specific `libc::<platform>::c_void` of libc.
1566 fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
1567 if let ty::Adt(adt, _) = ty.kind() {
1568 let names = cx.get_def_path(adt.did);
1570 if names.is_empty() {
1573 if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1580 /// Returns the mantissa bits wide of a fp type.
1581 /// Will return 0 if the type is not a fp
1582 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1584 ty::Float(FloatTy::F32) => 23,
1585 ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1590 impl<'tcx> LateLintPass<'tcx> for Casts {
1591 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1592 if expr.span.from_expansion() {
1595 if let ExprKind::Cast(ref ex, _) = expr.kind {
1596 let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
1597 lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1598 if let ExprKind::Lit(ref lit) = ex.kind {
1600 if let LitKind::Int(n, _) = lit.node;
1601 if let Some(src) = snippet_opt(cx, lit.span);
1602 if cast_to.is_floating_point();
1603 if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1604 let from_nbits = 128 - n.leading_zeros();
1605 let to_nbits = fp_ty_mantissa_nbits(cast_to);
1606 if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1612 &format!("casting integer literal to `{}` is unnecessary", cast_to),
1614 format!("{}_{}", n, cast_to),
1615 Applicability::MachineApplicable,
1621 LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1623 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
1629 "casting to the same type is unnecessary (`{}` -> `{}`)",
1637 if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1638 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1641 lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1646 fn lint_numeric_casts<'tcx>(
1647 cx: &LateContext<'tcx>,
1649 cast_expr: &Expr<'_>,
1650 cast_from: Ty<'tcx>,
1653 match (cast_from.is_integral(), cast_to.is_integral()) {
1655 let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1656 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
1661 if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1662 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1664 if from_nbits < to_nbits {
1665 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1671 CAST_POSSIBLE_TRUNCATION,
1673 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1675 if !cast_to.is_signed() {
1681 "casting `{}` to `{}` may lose the sign of the value",
1688 check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1689 check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1690 check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1693 if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
1696 CAST_POSSIBLE_TRUNCATION,
1698 "casting `f64` to `f32` may truncate the value",
1701 if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
1702 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1708 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1710 if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
1711 if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
1712 if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1713 if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1714 if from_layout.align.abi < to_layout.align.abi;
1715 // with c_void, we inherently need to trust the user
1716 if !is_c_void(cx, from_ptr_ty.ty);
1717 // when casting from a ZST, we don't know enough to properly lint
1718 if !from_layout.is_zst();
1725 "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1728 from_layout.align.abi.bytes(),
1729 to_layout.align.abi.bytes(),
1736 fn lint_fn_to_numeric_cast(
1737 cx: &LateContext<'_>,
1739 cast_expr: &Expr<'_>,
1743 // We only want to check casts to `ty::Uint` or `ty::Int`
1744 match cast_to.kind() {
1745 ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1748 match cast_from.kind() {
1749 ty::FnDef(..) | ty::FnPtr(_) => {
1750 let mut applicability = Applicability::MaybeIncorrect;
1751 let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1753 let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1754 if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1757 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1760 "casting function pointer `{}` to `{}`, which truncates the value",
1761 from_snippet, cast_to
1764 format!("{} as usize", from_snippet),
1767 } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
1772 &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1774 format!("{} as usize", from_snippet),
1783 declare_clippy_lint! {
1784 /// **What it does:** Checks for types used in structs, parameters and `let`
1785 /// declarations above a certain complexity threshold.
1787 /// **Why is this bad?** Too complex types make the code less readable. Consider
1788 /// using a `type` definition to simplify them.
1790 /// **Known problems:** None.
1794 /// # use std::rc::Rc;
1796 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1799 pub TYPE_COMPLEXITY,
1801 "usage of very complex types that might be better factored into `type` definitions"
1804 pub struct TypeComplexity {
1808 impl TypeComplexity {
1810 pub fn new(threshold: u64) -> Self {
1815 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1817 impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
1820 cx: &LateContext<'tcx>,
1822 decl: &'tcx FnDecl<'_>,
1827 self.check_fndecl(cx, decl);
1830 fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
1831 // enum variants are also struct fields now
1832 self.check_type(cx, &field.ty);
1835 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1837 ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1838 // functions, enums, structs, impls and traits are covered
1843 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1845 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1846 TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1847 // methods with default impl are covered by check_fn
1852 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
1854 ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1855 // methods are covered by check_fn
1860 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
1861 if let Some(ref ty) = local.ty {
1862 self.check_type(cx, ty);
1867 impl<'tcx> TypeComplexity {
1868 fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
1869 for arg in decl.inputs {
1870 self.check_type(cx, arg);
1872 if let FnRetTy::Return(ref ty) = decl.output {
1873 self.check_type(cx, ty);
1877 fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
1878 if ty.span.from_expansion() {
1882 let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1883 visitor.visit_ty(ty);
1887 if score > self.threshold {
1892 "very complex type used. Consider factoring parts into `type` definitions",
1898 /// Walks a type and assigns a complexity score to it.
1899 struct TypeComplexityVisitor {
1900 /// total complexity score of the type
1902 /// current nesting level
1906 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1907 type Map = Map<'tcx>;
1909 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1910 let (add_score, sub_nest) = match ty.kind {
1911 // _, &x and *x have only small overhead; don't mess with nesting level
1912 TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1914 // the "normal" components of a type: named types, arrays/tuples
1915 TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1917 // function types bring a lot of overhead
1918 TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1920 TyKind::TraitObject(ref param_bounds, _) => {
1921 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1923 .bound_generic_params
1925 .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
1927 if has_lifetime_parameters {
1928 // complex trait bounds like A<'a, 'b>
1931 // simple trait bounds like A + B
1938 self.score += add_score;
1939 self.nest += sub_nest;
1941 self.nest -= sub_nest;
1943 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1944 NestedVisitorMap::None
1948 declare_clippy_lint! {
1949 /// **What it does:** Checks for expressions where a character literal is cast
1950 /// to `u8` and suggests using a byte literal instead.
1952 /// **Why is this bad?** In general, casting values to smaller types is
1953 /// error-prone and should be avoided where possible. In the particular case of
1954 /// converting a character literal to u8, it is easy to avoid by just using a
1955 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1956 /// than `'a' as u8`.
1958 /// **Known problems:** None.
1965 /// A better version, using the byte literal:
1972 "casting a character literal to `u8` truncates"
1975 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1977 impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
1978 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1980 if !expr.span.from_expansion();
1981 if let ExprKind::Cast(e, _) = &expr.kind;
1982 if let ExprKind::Lit(l) = &e.kind;
1983 if let LitKind::Char(c) = l.node;
1984 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
1986 let mut applicability = Applicability::MachineApplicable;
1987 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
1993 "casting a character literal to `u8` truncates",
1995 diag.note("`char` is four bytes wide, but `u8` is a single byte");
1998 diag.span_suggestion(
2000 "use a byte literal instead",
2001 format!("b{}", snippet),
2011 declare_clippy_lint! {
2012 /// **What it does:** Checks for comparisons where one side of the relation is
2013 /// either the minimum or maximum value for its type and warns if it involves a
2014 /// case that is always true or always false. Only integer and boolean types are
2017 /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
2018 /// that it is possible for `x` to be less than the minimum. Expressions like
2019 /// `max < x` are probably mistakes.
2021 /// **Known problems:** For `usize` the size of the current compile target will
2022 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
2023 /// a comparison to detect target pointer width will trigger this lint. One can
2024 /// use `mem::sizeof` and compare its value or conditional compilation
2026 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
2031 /// let vec: Vec<isize> = Vec::new();
2032 /// if vec.len() <= 0 {}
2033 /// if 100 > i32::MAX {}
2035 pub ABSURD_EXTREME_COMPARISONS,
2037 "a comparison with a maximum or minimum value that is always true or false"
2040 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
2047 struct ExtremeExpr<'a> {
2052 enum AbsurdComparisonResult {
2055 InequalityImpossible,
2058 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
2059 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2060 let precast_ty = cx.typeck_results().expr_ty(cast_exp);
2061 let cast_ty = cx.typeck_results().expr_ty(expr);
2063 return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
2069 fn detect_absurd_comparison<'tcx>(
2070 cx: &LateContext<'tcx>,
2072 lhs: &'tcx Expr<'_>,
2073 rhs: &'tcx Expr<'_>,
2074 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
2075 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2076 use crate::types::ExtremeType::{Maximum, Minimum};
2077 use crate::utils::comparisons::{normalize_comparison, Rel};
2079 // absurd comparison only makes sense on primitive types
2080 // primitive types don't implement comparison operators with each other
2081 if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
2085 // comparisons between fix sized types and target sized types are considered unanalyzable
2086 if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
2090 let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
2092 let lx = detect_extreme_expr(cx, normalized_lhs);
2093 let rx = detect_extreme_expr(cx, normalized_rhs);
2098 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
2099 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
2105 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
2106 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
2107 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
2108 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
2112 Rel::Ne | Rel::Eq => return None,
2116 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
2117 use crate::types::ExtremeType::{Maximum, Minimum};
2119 let ty = cx.typeck_results().expr_ty(expr);
2121 let cv = constant(cx, cx.typeck_results(), expr)?.0;
2123 let which = match (ty.kind(), cv) {
2124 (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
2125 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
2129 (&ty::Bool, Constant::Bool(true)) => Maximum,
2130 (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
2133 (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
2137 Some(ExtremeExpr { which, expr })
2140 impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
2141 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2142 use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
2143 use crate::types::ExtremeType::{Maximum, Minimum};
2145 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2146 if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
2147 if !expr.span.from_expansion() {
2148 let msg = "this comparison involving the minimum or maximum element for this \
2149 type contains a case that is always true or always false";
2151 let conclusion = match result {
2152 AlwaysFalse => "this comparison is always false".to_owned(),
2153 AlwaysTrue => "this comparison is always true".to_owned(),
2154 InequalityImpossible => format!(
2155 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
2157 snippet(cx, lhs.span, "lhs"),
2158 snippet(cx, rhs.span, "rhs")
2163 "because `{}` is the {} value for this type, {}",
2164 snippet(cx, culprit.expr.span, "x"),
2165 match culprit.which {
2166 Minimum => "minimum",
2167 Maximum => "maximum",
2172 span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
2179 declare_clippy_lint! {
2180 /// **What it does:** Checks for comparisons where the relation is always either
2181 /// true or false, but where one side has been upcast so that the comparison is
2182 /// necessary. Only integer types are checked.
2184 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
2185 /// will mistakenly imply that it is possible for `x` to be outside the range of
2188 /// **Known problems:**
2189 /// https://github.com/rust-lang/rust-clippy/issues/886
2194 /// (x as u32) > 300;
2196 pub INVALID_UPCAST_COMPARISONS,
2198 "a comparison involving an upcast which is always true or false"
2201 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
2203 #[derive(Copy, Clone, Debug, Eq)]
2210 #[allow(clippy::cast_sign_loss)]
2212 fn cmp_s_u(s: i128, u: u128) -> Ordering {
2215 } else if u > (i128::MAX as u128) {
2223 impl PartialEq for FullInt {
2225 fn eq(&self, other: &Self) -> bool {
2226 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
2230 impl PartialOrd for FullInt {
2232 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2233 Some(match (self, other) {
2234 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
2235 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
2236 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
2237 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
2242 impl Ord for FullInt {
2244 fn cmp(&self, other: &Self) -> Ordering {
2245 self.partial_cmp(other)
2246 .expect("`partial_cmp` for FullInt can never return `None`")
2250 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
2251 if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
2252 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
2253 let cast_ty = cx.typeck_results().expr_ty(expr);
2254 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
2255 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
2258 match pre_cast_ty.kind() {
2259 ty::Int(int_ty) => Some(match int_ty {
2260 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
2261 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
2262 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
2263 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
2264 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
2265 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
2267 ty::Uint(uint_ty) => Some(match uint_ty {
2268 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
2269 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
2270 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
2271 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
2272 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
2273 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
2282 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2283 let val = constant(cx, cx.typeck_results(), expr)?.0;
2284 if let Constant::Int(const_int) = val {
2285 match *cx.typeck_results().expr_ty(expr).kind() {
2286 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2287 ty::Uint(_) => Some(FullInt::U(const_int)),
2295 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
2296 if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2299 INVALID_UPCAST_COMPARISONS,
2302 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2303 snippet(cx, cast_val.span, "the expression"),
2304 if always { "true" } else { "false" },
2310 fn upcast_comparison_bounds_err<'tcx>(
2311 cx: &LateContext<'tcx>,
2313 rel: comparisons::Rel,
2314 lhs_bounds: Option<(FullInt, FullInt)>,
2315 lhs: &'tcx Expr<'_>,
2316 rhs: &'tcx Expr<'_>,
2319 use crate::utils::comparisons::Rel;
2321 if let Some((lb, ub)) = lhs_bounds {
2322 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2323 if rel == Rel::Eq || rel == Rel::Ne {
2324 if norm_rhs_val < lb || norm_rhs_val > ub {
2325 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2327 } else if match rel {
2342 Rel::Eq | Rel::Ne => unreachable!(),
2344 err_upcast_comparison(cx, span, lhs, true)
2345 } else if match rel {
2360 Rel::Eq | Rel::Ne => unreachable!(),
2362 err_upcast_comparison(cx, span, lhs, false)
2368 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
2369 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2370 if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2371 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2372 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2378 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2379 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2381 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2382 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2387 declare_clippy_lint! {
2388 /// **What it does:** Checks for public `impl` or `fn` missing generalization
2389 /// over different hashers and implicitly defaulting to the default hashing
2390 /// algorithm (`SipHash`).
2392 /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2395 /// **Known problems:** Suggestions for replacing constructors can contain
2396 /// false-positives. Also applying suggestions can require modification of other
2397 /// pieces of code, possibly including external crates.
2401 /// # use std::collections::HashMap;
2402 /// # use std::hash::{Hash, BuildHasher};
2403 /// # trait Serialize {};
2404 /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2406 /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2408 /// could be rewritten as
2410 /// # use std::collections::HashMap;
2411 /// # use std::hash::{Hash, BuildHasher};
2412 /// # trait Serialize {};
2413 /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2415 /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2417 pub IMPLICIT_HASHER,
2419 "missing generalization over different hashers"
2422 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2424 impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
2425 #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2426 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
2427 use rustc_span::BytePos;
2429 fn suggestion<'tcx>(
2430 cx: &LateContext<'tcx>,
2431 diag: &mut DiagnosticBuilder<'_>,
2432 generics_span: Span,
2433 generics_suggestion_span: Span,
2434 target: &ImplicitHasherType<'_>,
2435 vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2437 let generics_snip = snippet(cx, generics_span, "");
2439 let generics_snip = if generics_snip.is_empty() {
2442 &generics_snip[1..generics_snip.len() - 1]
2447 "consider adding a type parameter",
2450 generics_suggestion_span,
2452 "<{}{}S: ::std::hash::BuildHasher{}>",
2454 if generics_snip.is_empty() { "" } else { ", " },
2455 if vis.suggestions.is_empty() {
2458 // request users to add `Default` bound so that generic constructors can be used
2465 format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2470 if !vis.suggestions.is_empty() {
2471 multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
2475 if !cx.access_levels.is_exported(item.hir_id) {
2486 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2489 for target in &vis.found {
2490 if differing_macro_contexts(item.span, target.span()) {
2494 let generics_suggestion_span = generics.span.substitute_dummy({
2495 let pos = snippet_opt(cx, item.span.until(target.span()))
2496 .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2497 if let Some(pos) = pos {
2498 Span::new(pos, pos, item.span.data().ctxt)
2504 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2505 for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2506 ctr_vis.visit_impl_item(item);
2514 "impl for `{}` should be generalized over different hashers",
2518 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2523 ItemKind::Fn(ref sig, ref generics, body_id) => {
2524 let body = cx.tcx.hir().body(body_id);
2526 for ty in sig.decl.inputs {
2527 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2530 for target in &vis.found {
2531 if in_external_macro(cx.sess(), generics.span) {
2534 let generics_suggestion_span = generics.span.substitute_dummy({
2535 let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2537 let i = snip.find("fn")?;
2538 Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2540 .expect("failed to create span for type parameters");
2541 Span::new(pos, pos, item.span.data().ctxt)
2544 let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2545 ctr_vis.visit_body(body);
2552 "parameter of type `{}` should be generalized over different hashers",
2556 suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
2567 enum ImplicitHasherType<'tcx> {
2568 HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2569 HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2572 impl<'tcx> ImplicitHasherType<'tcx> {
2573 /// Checks that `ty` is a target type without a `BuildHasher`.
2574 fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2575 if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2576 let params: Vec<_> = path
2584 .filter_map(|arg| match arg {
2585 GenericArg::Type(ty) => Some(ty),
2589 let params_len = params.len();
2591 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2593 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
2594 Some(ImplicitHasherType::HashMap(
2597 snippet(cx, params[0].span, "K"),
2598 snippet(cx, params[1].span, "V"),
2600 } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
2601 Some(ImplicitHasherType::HashSet(
2604 snippet(cx, params[0].span, "T"),
2614 fn type_name(&self) -> &'static str {
2616 ImplicitHasherType::HashMap(..) => "HashMap",
2617 ImplicitHasherType::HashSet(..) => "HashSet",
2621 fn type_arguments(&self) -> String {
2623 ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2624 ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2628 fn ty(&self) -> Ty<'tcx> {
2630 ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2634 fn span(&self) -> Span {
2636 ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2641 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2642 cx: &'a LateContext<'tcx>,
2643 found: Vec<ImplicitHasherType<'tcx>>,
2646 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2647 fn new(cx: &'a LateContext<'tcx>) -> Self {
2648 Self { cx, found: vec![] }
2652 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2653 type Map = Map<'tcx>;
2655 fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2656 if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2657 self.found.push(target);
2663 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2664 NestedVisitorMap::None
2668 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2669 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2670 cx: &'a LateContext<'tcx>,
2671 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
2672 target: &'b ImplicitHasherType<'tcx>,
2673 suggestions: BTreeMap<Span, String>,
2676 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2677 fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2680 maybe_typeck_results: cx.maybe_typeck_results(),
2682 suggestions: BTreeMap::new(),
2687 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2688 type Map = Map<'tcx>;
2690 fn visit_body(&mut self, body: &'tcx Body<'_>) {
2691 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
2692 walk_body(self, body);
2693 self.maybe_typeck_results = old_maybe_typeck_results;
2696 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2698 if let ExprKind::Call(ref fun, ref args) = e.kind;
2699 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2700 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
2702 if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
2706 if match_path(ty_path, &paths::HASHMAP) {
2707 if method.ident.name == sym!(new) {
2709 .insert(e.span, "HashMap::default()".to_string());
2710 } else if method.ident.name == sym!(with_capacity) {
2711 self.suggestions.insert(
2714 "HashMap::with_capacity_and_hasher({}, Default::default())",
2715 snippet(self.cx, args[0].span, "capacity"),
2719 } else if match_path(ty_path, &paths::HASHSET) {
2720 if method.ident.name == sym!(new) {
2722 .insert(e.span, "HashSet::default()".to_string());
2723 } else if method.ident.name == sym!(with_capacity) {
2724 self.suggestions.insert(
2727 "HashSet::with_capacity_and_hasher({}, Default::default())",
2728 snippet(self.cx, args[0].span, "capacity"),
2739 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2740 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2744 declare_clippy_lint! {
2745 /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2747 /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2748 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2751 /// **Known problems:** None.
2757 /// *(r as *const _ as *mut _) += 1;
2762 /// Instead consider using interior mutability types.
2765 /// use std::cell::UnsafeCell;
2767 /// fn x(r: &UnsafeCell<i32>) {
2773 pub CAST_REF_TO_MUT,
2775 "a cast of reference to a mutable pointer"
2778 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2780 impl<'tcx> LateLintPass<'tcx> for RefToMut {
2781 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2783 if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2784 if let ExprKind::Cast(e, t) = &e.kind;
2785 if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2786 if let ExprKind::Cast(e, t) = &e.kind;
2787 if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2788 if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
2794 "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",