rust-clippy/clippy_lints/src/exhaustive_items.rs

70 lines
2.2 KiB
Rust
Raw Normal View History

2021-01-21 20:48:30 +00:00
use crate::utils::{snippet_opt, span_lint_and_help, span_lint_and_sugg};
use if_chain::if_chain;
2021-01-21 21:31:15 +00:00
use rustc_hir::{Item, ItemKind};
2021-01-21 20:48:30 +00:00
use rustc_errors::Applicability;
2021-01-21 21:31:15 +00:00
use rustc_lint::{LateContext, LateLintPass};
2021-01-21 20:48:30 +00:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// **What it does:** Warns on any exported `enum`s that are not tagged `#[non_exhaustive]`
2021-01-21 20:48:30 +00:00
///
/// **Why is this bad?** Exhaustive enums are typically fine, but a project which does
/// not wish to make a stability commitment around enums may wish to disable them by default.
///
/// **Known problems:** None.
///
/// **Example:**
///
/// ```rust
/// enum Foo {
/// Bar,
/// Baz
/// }
/// ```
/// Use instead:
/// ```rust
/// #[non_exhaustive]
/// enum Foo {
/// Bar,
/// Baz
/// } /// ```
pub EXHAUSTIVE_ENUMS,
restriction,
"default lint description"
}
2021-01-21 21:36:18 +00:00
declare_lint_pass!(ExhaustiveItems => [EXHAUSTIVE_ENUMS]);
2021-01-21 20:48:30 +00:00
2021-01-21 21:36:18 +00:00
impl LateLintPass<'_> for ExhaustiveItems {
2021-01-21 21:31:15 +00:00
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
2021-01-21 20:48:30 +00:00
if_chain! {
if let ItemKind::Enum(..) = item.kind;
if cx.access_levels.is_exported(item.hir_id);
2021-01-21 20:48:30 +00:00
if !item.attrs.iter().any(|a| a.has_name(sym::non_exhaustive));
then {
if let Some(snippet) = snippet_opt(cx, item.span) {
span_lint_and_sugg(
cx,
EXHAUSTIVE_ENUMS,
item.span,
"enums should not be exhaustive",
"try adding #[non_exhaustive]",
format!("#[non_exhaustive]\n{}", snippet),
Applicability::MaybeIncorrect,
);
} else {
span_lint_and_help(
cx,
EXHAUSTIVE_ENUMS,
item.span,
"enums should not be exhaustive",
None,
"try adding #[non_exhaustive]",
);
}
}
}
}
}