]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/zero_sized_map_values.rs
Auto merge of #88214 - notriddle:notriddle/for-loop-span-drop-temps-mut, r=nagisa
[rust.git] / clippy_lints / src / zero_sized_map_values.rs
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};
9 use rustc_span::sym;
10 use rustc_typeck::hir_ty_to_ty;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for maps with zero-sized value types anywhere in the code.
15     ///
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.
20     ///
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
24     ///
25     /// ### Example
26     /// ```rust
27     /// # use std::collections::HashMap;
28     /// fn unique_words(text: &str) -> HashMap<&str, ()> {
29     ///     todo!();
30     /// }
31     /// ```
32     /// Use instead:
33     /// ```rust
34     /// # use std::collections::HashSet;
35     /// fn unique_words(text: &str) -> HashSet<&str> {
36     ///     todo!();
37     /// }
38     /// ```
39     pub ZERO_SIZED_MAP_VALUES,
40     pedantic,
41     "usage of map with zero-sized value type"
42 }
43
44 declare_lint_pass!(ZeroSizedMapValues => [ZERO_SIZED_MAP_VALUES]);
45
46 impl LateLintPass<'_> for ZeroSizedMapValues {
47     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
48         if_chain! {
49             if !hir_ty.span.from_expansion();
50             if !in_trait_impl(cx, hir_ty.hir_id);
51             let ty = ty_from_hir_ty(cx, hir_ty);
52             if is_type_diagnostic_item(cx, ty, sym::hashmap_type) || is_type_diagnostic_item(cx, ty, sym::BTreeMap);
53             if let Adt(_, substs) = ty.kind();
54             let ty = substs.type_at(1);
55             // Fixes https://github.com/rust-lang/rust-clippy/issues/7447 because of
56             // https://github.com/rust-lang/rust/blob/master/compiler/rustc_middle/src/ty/sty.rs#L968
57             if !ty.has_escaping_bound_vars();
58             // Do this to prevent `layout_of` crashing, being unable to fully normalize `ty`.
59             if is_normalizable(cx, cx.param_env, ty);
60             if let Ok(layout) = cx.layout_of(ty);
61             if layout.is_zst();
62             then {
63                 span_lint_and_help(cx, ZERO_SIZED_MAP_VALUES, hir_ty.span, "map with zero-sized value type", None, "consider using a set instead");
64             }
65         }
66     }
67 }
68
69 fn in_trait_impl(cx: &LateContext<'_>, hir_id: HirId) -> bool {
70     let parent_id = cx.tcx.hir().get_parent_item(hir_id);
71     if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(parent_id)) {
72         if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
73             return true;
74         }
75     }
76     false
77 }
78
79 fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
80     cx.maybe_typeck_results()
81         .and_then(|results| {
82             if results.hir_owner == hir_ty.hir_id.owner {
83                 results.node_type_opt(hir_ty.hir_id)
84             } else {
85                 None
86             }
87         })
88         .unwrap_or_else(|| hir_ty_to_ty(cx.tcx, hir_ty))
89 }