bevy_lint/lints/style/
unconventional_naming.rs

1//! Checks for types that implement certain Bevy traits but do not follow that trait's naming
2//! convention.
3//!
4//! This lint currently enforces the following conventions:
5//!
6//! |Trait|Convention|
7//! |-|-|
8//! |`Plugin`|Name ends in "Plugin"|
9//! |`SystemSet`|Name ends in "Systems"|
10//!
11//! # Motivation
12//!
13//! Bevy provides several traits, such as `Plugin` and `SystemSet`, that designate the primary
14//! purpose of a type. It is common for these types to follow certain naming conventions that
15//! *signal* how it should be used. This lint helps enforce these conventions to ensure consistency
16//! across the Bevy engine and ecosystem.
17//!
18//! # Example
19//!
20//! ```
21//! # use bevy::prelude::*;
22//! #
23//! struct Physics;
24//!
25//! impl Plugin for Physics {
26//! #     fn build(&self, app: &mut App) {}
27//! #
28//!     // ...
29//! }
30//!
31//! #[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
32//! struct MyAudio;
33//! ```
34//!
35//! Use instead:
36//!
37//! ```
38//! # use bevy::prelude::*;
39//! #
40//! struct PhysicsPlugin;
41//!
42//! impl Plugin for PhysicsPlugin {
43//! #     fn build(&self, app: &mut App) {}
44//! #
45//!     // ...
46//! }
47//!
48//! #[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
49//! struct MyAudioSystems;
50//! ```
51
52use clippy_utils::{diagnostics::span_lint_hir_and_then, path_res};
53use rustc_errors::Applicability;
54use rustc_hir::{HirId, Impl, Item, ItemKind, OwnerId};
55use rustc_lint::{LateContext, LateLintPass};
56use rustc_span::symbol::Ident;
57
58use crate::{declare_bevy_lint, declare_bevy_lint_pass, utils::hir_parse::impls_trait};
59
60declare_bevy_lint! {
61    pub UNCONVENTIONAL_NAMING,
62    super::Style,
63    "unconventional type name for a `Plugin` or `SystemSet`",
64}
65
66declare_bevy_lint_pass! {
67    pub UnconventionalNaming => [UNCONVENTIONAL_NAMING],
68}
69
70impl<'tcx> LateLintPass<'tcx> for UnconventionalNaming {
71    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &Item<'tcx>) {
72        // Find `impl` items...
73        if let ItemKind::Impl(impl_) = item.kind
74            && let Some(conventional_name_impl) = TraitConvention::try_from_impl(cx, impl_)
75        {
76            // Try to resolve where this type was originally defined. This will result in a `DefId`
77            // pointing to the original `struct Foo` definition, or `impl <T>` if it's a generic
78            // parameter.
79            let Some(struct_def_id) = path_res(cx, impl_.self_ty).opt_def_id() else {
80                return;
81            };
82
83            // If this type is a generic parameter, exit. Their names, such as `T`, cannot be
84            // referenced by others.
85            if impl_
86                .generics
87                .params
88                .iter()
89                .any(|param| param.def_id.to_def_id() == struct_def_id)
90            {
91                return;
92            }
93
94            // Find the original name and span of the type.
95            let Some(Ident {
96                name: struct_name,
97                span: struct_span,
98            }) = cx.tcx.opt_item_ident(struct_def_id)
99            else {
100                return;
101            };
102
103            // skip lint if the struct was defined in an external macro
104            if struct_span.in_external_macro(cx.tcx.sess.source_map()) {
105                return;
106            }
107
108            // If the type's name matches the given convention
109            if conventional_name_impl.matches_conventional_name(struct_name.as_str()) {
110                return;
111            }
112
113            // Convert the `DefId` of the structure to a `LocalDefId`. If it cannot be converted
114            // then the struct is from an external crate, in which case this lint should not be
115            // emitted. (The user cannot easily rename that struct if they didn't define it.)
116            let Some(struct_local_def_id) = struct_def_id.as_local() else {
117                return;
118            };
119
120            // Convert struct `LocalDefId` to an `HirId` so that we can emit the lint for the
121            // correct HIR node.
122            let struct_hir_id: HirId = OwnerId {
123                def_id: struct_local_def_id,
124            }
125            .into();
126            span_lint_hir_and_then(
127                cx,
128                UNCONVENTIONAL_NAMING,
129                struct_hir_id,
130                struct_span,
131                conventional_name_impl.lint_description(),
132                |diag| {
133                    diag.span_note(
134                        struct_span,
135                        format!(
136                            "structures that implement `{}` should end in `{}`",
137                            conventional_name_impl.name(),
138                            conventional_name_impl.suffix()
139                        ),
140                    );
141
142                    diag.span_suggestion(
143                        struct_span,
144                        format!("rename `{}`", struct_name.as_str()),
145                        conventional_name_impl.name_suggestion(struct_name.as_str()),
146                        Applicability::MaybeIncorrect,
147                    );
148
149                    diag.span_note(
150                        item.span,
151                        format!("`{}` implemented here", conventional_name_impl.name()),
152                    );
153                },
154            );
155        }
156    }
157}
158
159/// Collections of bevy traits where types that implement this trait should follow a specific naming
160/// convention
161enum TraitConvention {
162    SystemSet,
163    Plugin,
164}
165
166impl TraitConvention {
167    /// check if this `impl` block implements a Bevy trait that should follow a naming pattern
168    fn try_from_impl(cx: &LateContext, impl_: &Impl) -> Option<Self> {
169        if impls_trait(cx, impl_, &crate::paths::SYSTEM_SET) {
170            Some(TraitConvention::SystemSet)
171        } else if impls_trait(cx, impl_, &crate::paths::PLUGIN) {
172            Some(TraitConvention::Plugin)
173        } else {
174            None
175        }
176    }
177
178    fn name(&self) -> &'static str {
179        match self {
180            TraitConvention::SystemSet => "SystemSet",
181            TraitConvention::Plugin => "Plugin",
182        }
183    }
184
185    /// Returns the suffix that should be used when implementing this trait
186    fn suffix(&self) -> &'static str {
187        match self {
188            TraitConvention::SystemSet => "Systems",
189            TraitConvention::Plugin => "Plugin",
190        }
191    }
192
193    fn lint_description(&self) -> String {
194        format!("unconventional type name for a `{}`", self.name())
195    }
196
197    /// Test if the Structure name matches the naming convention
198    fn matches_conventional_name(&self, struct_name: &str) -> bool {
199        struct_name.ends_with(self.suffix())
200    }
201
202    /// Suggest a name for the Structure that matches the naming pattern
203    fn name_suggestion(&self, struct_name: &str) -> String {
204        match self {
205            TraitConvention::SystemSet => {
206                // There are several competing naming standards. These are a few that we specially
207                // check for.
208                const INCORRECT_SUFFIXES: [&str; 3] = ["System", "Set", "Steps"];
209
210                // If the name ends in one of the other suffixes, strip it out and replace it with
211                // "Systems". If a struct was originally named `FooSet`, this suggests `FooSystems`
212                // instead of `FooSetSystems`.
213                for incorrect_suffix in INCORRECT_SUFFIXES {
214                    if struct_name.ends_with(incorrect_suffix) {
215                        let stripped_name =
216                            &struct_name[0..(struct_name.len() - incorrect_suffix.len())];
217                        return format!("{stripped_name}{}", self.suffix());
218                    }
219                }
220                format!("{struct_name}{}", self.suffix())
221            }
222            TraitConvention::Plugin => format!("{struct_name}{}", self.suffix()),
223        }
224    }
225}