1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::ty::{is_normalizable, is_type_diagnostic_item};
3 use if_chain::if_chain;
4 use rustc_hir::{self as hir, HirId, ItemKind, Node};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::ty::layout::LayoutOf as _;
7 use rustc_middle::ty::{Adt, Ty, TypeFoldable};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_typeck::hir_ty_to_ty;
12 declare_clippy_lint! {
14 /// Checks for maps with zero-sized value types anywhere in the code.
16 /// ### Why is this bad?
17 /// Since there is only a single value for a zero-sized type, a map
18 /// containing zero sized values is effectively a set. Using a set in that case improves
19 /// readability and communicates intent more clearly.
21 /// ### Known problems
22 /// * A zero-sized type cannot be recovered later if it contains private fields.
23 /// * This lints the signature of public items
27 /// # use std::collections::HashMap;
28 /// fn unique_words(text: &str) -> HashMap<&str, ()> {
34 /// # use std::collections::HashSet;
35 /// fn unique_words(text: &str) -> HashSet<&str> {
39 #[clippy::version = "1.50.0"]
40 pub ZERO_SIZED_MAP_VALUES,
42 "usage of map with zero-sized value type"
45 declare_lint_pass!(ZeroSizedMapValues => [ZERO_SIZED_MAP_VALUES]);
47 impl LateLintPass<'_> for ZeroSizedMapValues {
48 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
50 if !hir_ty.span.from_expansion();
51 if !in_trait_impl(cx, hir_ty.hir_id);
52 let ty = ty_from_hir_ty(cx, hir_ty);
53 if is_type_diagnostic_item(cx, ty, sym::HashMap) || is_type_diagnostic_item(cx, ty, sym::BTreeMap);
54 if let Adt(_, substs) = ty.kind();
55 let ty = substs.type_at(1);
56 // Fixes https://github.com/rust-lang/rust-clippy/issues/7447 because of
57 // https://github.com/rust-lang/rust/blob/master/compiler/rustc_middle/src/ty/sty.rs#L968
58 if !ty.has_escaping_bound_vars();
59 // Do this to prevent `layout_of` crashing, being unable to fully normalize `ty`.
60 if is_normalizable(cx, cx.param_env, ty);
61 if let Ok(layout) = cx.layout_of(ty);
64 span_lint_and_help(cx, ZERO_SIZED_MAP_VALUES, hir_ty.span, "map with zero-sized value type", None, "consider using a set instead");
70 fn in_trait_impl(cx: &LateContext<'_>, hir_id: HirId) -> bool {
71 let parent_id = cx.tcx.hir().get_parent_item(hir_id);
72 let second_parent_id = cx
75 .get_parent_item(cx.tcx.hir().local_def_id_to_hir_id(parent_id));
76 if let Some(Node::Item(item)) = cx.tcx.hir().find_by_def_id(second_parent_id) {
77 if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
84 fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
85 cx.maybe_typeck_results()
87 if results.hir_owner == hir_ty.hir_id.owner {
88 results.node_type_opt(hir_ty.hir_id)
93 .unwrap_or_else(|| hir_ty_to_ty(cx.tcx, hir_ty))