]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/empty_enum.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / empty_enum.rs
1 //! lint when there is an enum with no variants
2
3 use clippy_utils::diagnostics::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
10 /// Checks for `enum`s with no variants.
11 ///
12 /// As of this writing, the `never_type` is still a
13 /// nightly-only experimental API. Therefore, this lint is only triggered
14 /// if the `never_type` is enabled.
15 ///
16 /// ### Why is this bad?
17 /// If you want to introduce a type which
18 /// can't be instantiated, you should use `!` (the primitive type "never"),
19 /// or a wrapper around it, because `!` has more extensive
20 /// compiler support (type inference, etc...) and wrappers
21 /// around it are the conventional way to define an uninhabited type.
22 /// For further information visit [never type documentation](https://doc.rust-lang.org/std/primitive.never.html)
23 ///
24 ///
25 /// ### Example
26 /// ```rust
27 /// enum Test {}
28 /// ```
29 ///
30 /// Use instead:
31 /// ```rust
32 /// #![feature(never_type)]
33 ///
34 /// struct Test(!);
35 /// ```
36 #[clippy::version = "pre 1.29.0"]
37 pub EMPTY_ENUM,
38 pedantic,
39 "enum with no variants"
40 }
41
42 declare_lint_pass!(EmptyEnum => [EMPTY_ENUM]);
43
44 impl<'tcx> LateLintPass<'tcx> for EmptyEnum {
45 fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
46 // Only suggest the `never_type` if the feature is enabled
47 if !cx.tcx.features().never_type {
48 return;
49 }
50
51 if let ItemKind::Enum(..) = item.kind {
52 let ty = cx.tcx.type_of(item.owner_id).subst_identity();
53 let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
54 if adt.variants().is_empty() {
55 span_lint_and_help(
56 cx,
57 EMPTY_ENUM,
58 item.span,
59 "enum with no variants",
60 None,
61 "consider using the uninhabited type `!` (never type) or a wrapper \
62 around it to introduce a type which can't be instantiated",
63 );
64 }
65 }
66 }
67 }