]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/empty_enum.rs
Rollup merge of #71677 - Mark-Simulacrum:hasher-docs, r=Amanieu
[rust.git] / src / tools / clippy / clippy_lints / src / empty_enum.rs
1 //! lint when there is an enum with no variants
2
3 use crate::utils::span_lint_and_help;
4 use rustc_hir::{Item, ItemKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for `enum`s with no variants.
10     ///
11     /// **Why is this bad?** If you want to introduce a type which
12     /// can't be instantiated, you should use `!` (the never type),
13     /// or a wrapper around it, because `!` has more extensive
14     /// compiler support (type inference, etc...) and wrappers
15     /// around it are the conventional way to define an uninhabited type.
16     /// For further information visit [never type documentation](https://doc.rust-lang.org/std/primitive.never.html)
17     ///
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     ///
23     /// Bad:
24     /// ```rust
25     /// enum Test {}
26     /// ```
27     ///
28     /// Good:
29     /// ```rust
30     /// #![feature(never_type)]
31     ///
32     /// struct Test(!);
33     /// ```
34     pub EMPTY_ENUM,
35     pedantic,
36     "enum with no variants"
37 }
38
39 declare_lint_pass!(EmptyEnum => [EMPTY_ENUM]);
40
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EmptyEnum {
42     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item<'_>) {
43         let did = cx.tcx.hir().local_def_id(item.hir_id);
44         if let ItemKind::Enum(..) = item.kind {
45             let ty = cx.tcx.type_of(did);
46             let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
47             if adt.variants.is_empty() {
48                 span_lint_and_help(
49                     cx,
50                     EMPTY_ENUM,
51                     item.span,
52                     "enum with no variants",
53                     None,
54                     "consider using the uninhabited type `!` (never type) or a wrapper \
55                     around it to introduce a type which can't be instantiated",
56                 );
57             }
58         }
59     }
60 }