]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/zero_sized_map_values.rs
Auto merge of #79328 - c410-f3r:hir-if, r=matthewjasper
[rust.git] / clippy_lints / src / zero_sized_map_values.rs
1 use if_chain::if_chain;
2 use rustc_hir::{self as hir, HirId, ItemKind, Node};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_middle::ty::{Adt, Ty};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_target::abi::LayoutOf as _;
7 use rustc_typeck::hir_ty_to_ty;
8
9 use crate::utils::{is_type_diagnostic_item, match_type, paths, span_lint_and_help};
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for maps with zero-sized value types anywhere in the code.
13     ///
14     /// **Why is this bad?** Since there is only a single value for a zero-sized type, a map
15     /// containing zero sized values is effectively a set. Using a set in that case improves
16     /// readability and communicates intent more clearly.
17     ///
18     /// **Known problems:**
19     /// * A zero-sized type cannot be recovered later if it contains private fields.
20     /// * This lints the signature of public items
21     ///
22     /// **Example:**
23     ///
24     /// ```rust
25     /// # use std::collections::HashMap;
26     /// fn unique_words(text: &str) -> HashMap<&str, ()> {
27     ///     todo!();
28     /// }
29     /// ```
30     /// Use instead:
31     /// ```rust
32     /// # use std::collections::HashSet;
33     /// fn unique_words(text: &str) -> HashSet<&str> {
34     ///     todo!();
35     /// }
36     /// ```
37     pub ZERO_SIZED_MAP_VALUES,
38     pedantic,
39     "usage of map with zero-sized value type"
40 }
41
42 declare_lint_pass!(ZeroSizedMapValues => [ZERO_SIZED_MAP_VALUES]);
43
44 impl LateLintPass<'_> for ZeroSizedMapValues {
45     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
46         if_chain! {
47             if !hir_ty.span.from_expansion();
48             if !in_trait_impl(cx, hir_ty.hir_id);
49             let ty = ty_from_hir_ty(cx, hir_ty);
50             if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP);
51             if let Adt(_, ref substs) = ty.kind();
52             let ty = substs.type_at(1);
53             if let Ok(layout) = cx.layout_of(ty);
54             if layout.is_zst();
55             then {
56                 span_lint_and_help(cx, ZERO_SIZED_MAP_VALUES, hir_ty.span, "map with zero-sized value type", None, "consider using a set instead");
57             }
58         }
59     }
60 }
61
62 fn in_trait_impl(cx: &LateContext<'_>, hir_id: HirId) -> bool {
63     let parent_id = cx.tcx.hir().get_parent_item(hir_id);
64     if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(parent_id)) {
65         if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
66             return true;
67         }
68     }
69     false
70 }
71
72 fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
73     cx.maybe_typeck_results()
74         .and_then(|results| {
75             if results.hir_owner == hir_ty.hir_id.owner {
76                 results.node_type_opt(hir_ty.hir_id)
77             } else {
78                 None
79             }
80         })
81         .unwrap_or_else(|| hir_ty_to_ty(cx.tcx, hir_ty))
82 }