|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use rustc_hir::{Item, ItemKind}; |
| 3 | +use rustc_lint::{LateContext, LateLintPass}; |
| 4 | +use rustc_session::declare_lint_pass; |
| 5 | + |
| 6 | +declare_clippy_lint! { |
| 7 | + /// ### What it does |
| 8 | + /// |
| 9 | + /// Detects types with `Unsafe` in the name that are publically constructable. |
| 10 | + /// |
| 11 | + /// ### Why is this bad? |
| 12 | + /// |
| 13 | + /// `Unsafe` in the name of a type implies that there is some kind of safety invariant |
| 14 | + /// being held by constructing said type, however, this invariant may not be checked |
| 15 | + /// if a user can safely publically construct it. |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```no_run |
| 19 | + /// pub struct UnsafeToken {} |
| 20 | + /// ``` |
| 21 | + /// Use instead: |
| 22 | + /// ```no_run |
| 23 | + /// pub struct UnsafeToken { |
| 24 | + /// _private: () |
| 25 | + /// } |
| 26 | + /// ``` |
| 27 | + #[clippy::version = "1.84.0"] |
| 28 | + pub CONSTRUCTABLE_UNSAFE_TYPE, |
| 29 | + suspicious, |
| 30 | + "`Unsafe` types that are publically constructable" |
| 31 | +} |
| 32 | + |
| 33 | +declare_lint_pass!(ConstructableUnsafeType => [CONSTRUCTABLE_UNSAFE_TYPE]); |
| 34 | + |
| 35 | +impl LateLintPass<'_> for ConstructableUnsafeType { |
| 36 | + fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { |
| 37 | + if let ItemKind::Struct(variant, generics) = item.kind |
| 38 | + && item.ident.as_str().contains("Unsafe") |
| 39 | + && generics.params.is_empty() |
| 40 | + && cx.effective_visibilities.is_reachable(item.owner_id.def_id) |
| 41 | + && variant |
| 42 | + .fields() |
| 43 | + .iter() |
| 44 | + .all(|f| cx.effective_visibilities.is_exported(f.def_id)) |
| 45 | + { |
| 46 | + span_lint_and_help( |
| 47 | + cx, |
| 48 | + CONSTRUCTABLE_UNSAFE_TYPE, |
| 49 | + item.span, |
| 50 | + "`Unsafe` type is publically constructable", |
| 51 | + None, |
| 52 | + "give this type a private field, or make it private", |
| 53 | + ); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments