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