]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/zero_sized_map_values.rs
deprecate `clippy::for_loops_over_fallibles`
[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_hir_analysis::hir_ty_to_ty;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::layout::LayoutOf as _;
8 use rustc_middle::ty::{Adt, Ty, TypeVisitable};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::sym;
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     #[clippy::version = "1.50.0"]
40     pub ZERO_SIZED_MAP_VALUES,
41     pedantic,
42     "usage of map with zero-sized value type"
43 }
44
45 declare_lint_pass!(ZeroSizedMapValues => [ZERO_SIZED_MAP_VALUES]);
46
47 impl LateLintPass<'_> for ZeroSizedMapValues {
48     fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
49         if_chain! {
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);
62             if layout.is_zst();
63             then {
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");
65             }
66         }
67     }
68 }
69
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.tcx.hir().get_parent_item(parent_id.into()).def_id;
73     if let Some(Node::Item(item)) = cx.tcx.hir().find_by_def_id(second_parent_id) {
74         if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
75             return true;
76         }
77     }
78     false
79 }
80
81 fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
82     cx.maybe_typeck_results()
83         .and_then(|results| {
84             if results.hir_owner == hir_ty.hir_id.owner {
85                 results.node_type_opt(hir_ty.hir_id)
86             } else {
87                 None
88             }
89         })
90         .unwrap_or_else(|| hir_ty_to_ty(cx.tcx, hir_ty))
91 }