bevy_lint/lints/restriction/
missing_reflect.rs

1//! Checks for components, resources, and events that do not implement `Reflect`.
2//!
3//! # Motivation
4//!
5//! Reflection lets programs inspect type information at runtime. It is commonly used by tools to
6//! view and edit ECS information while the program is running. Reflection is opt-in, however, and
7//! easy to forget since you need to `#[derive(Reflect)]` for each type that uses it.
8//!
9//! # Known issues
10//!
11//! This lint will suggest `#[derive(Reflect)]` even if it cannot be applied. (E.g. if one of the
12//! fields does not implement `Reflect`.) For more information, please see [#141].
13//!
14//! [#141]: https://github.com/TheBevyFlock/bevy_cli/issues/141
15//!
16//! # Example
17//!
18//! ```
19//! # use bevy::prelude::*;
20//! #
21//! #[derive(Component)]
22//! struct MyComponent;
23//! ```
24//!
25//! Use instead:
26//!
27//! ```
28//! # use bevy::prelude::*;
29//! #
30//! // Remember to also register this component in the `App` type registry.
31//! #[derive(Component, Reflect)]
32//! struct MyComponent;
33//! ```
34//!
35//! Often you'll only want to enable this lint for a specific module:
36//!
37//! <!-- We currently ignore this doc test because any reference to `bevy_lint` causes it to be
38//! linked, which raises a compile error due to the linter's use of `rustc_private`. -->
39//!
40//! ```ignore
41//! mod types {
42//!     #![cfg_attr(bevy_lint, warn(bevy::missing_reflect))]
43//! #
44//! #   use bevy::prelude::*;
45//!
46//!     #[derive(Resource, Reflect)]
47//!     struct Score(u32);
48//!
49//!     #[derive(Component, Reflect)]
50//!     struct Happiness(i8);
51//! }
52//! ```
53//!
54//! For more information, please see [Toggling Lints in
55//! Code](../../index.html#toggling-lints-in-code).
56
57use clippy_utils::{
58    diagnostics::span_lint_hir_and_then,
59    paths::PathLookup,
60    sugg::DiagExt,
61    ty::{implements_trait, ty_from_hir_ty},
62};
63use rustc_errors::Applicability;
64use rustc_hir::{HirId, Item, ItemKind, Node, OwnerId, QPath, TyKind, def::DefKind};
65use rustc_lint::{LateContext, LateLintPass};
66use rustc_span::Span;
67
68use crate::{declare_bevy_lint, declare_bevy_lint_pass, span_unreachable};
69
70declare_bevy_lint! {
71    pub(crate) MISSING_REFLECT,
72    super::Restriction,
73    "defined a component, resource, or event without a `Reflect` implementation",
74    // We only override `check_crate()`.
75    @crate_level_only = true,
76}
77
78declare_bevy_lint_pass! {
79    pub(crate) MissingReflect => [MISSING_REFLECT],
80}
81
82impl<'tcx> LateLintPass<'tcx> for MissingReflect {
83    fn check_crate(&mut self, cx: &LateContext<'tcx>) {
84        // Finds all types that implement `Reflect` in this crate.
85        let reflected: Vec<TraitType> =
86            TraitType::from_local_crate(cx, &crate::paths::REFLECT).collect();
87
88        // Finds all non-`Reflect` types that implement `Event` in this crate.
89        let events: Vec<TraitType> = TraitType::from_local_crate(cx, &crate::paths::EVENT)
90            .filter(|trait_type| !reflected.contains(trait_type))
91            .collect();
92
93        // Finds all non-`Reflect` types that implement `Component` and *not* `Event` in this
94        // crate. Because events are also components, we need to deduplicate the two to avoid
95        // emitting multiple diagnostics for the same type.
96        let components: Vec<TraitType> = TraitType::from_local_crate(cx, &crate::paths::COMPONENT)
97            .filter(|trait_type| !(reflected.contains(trait_type) || events.contains(trait_type)))
98            .collect();
99
100        // Finds all non-`Reflect` types that implement `Resource` in this crate.
101        let resources: Vec<TraitType> = TraitType::from_local_crate(cx, &crate::paths::RESOURCE)
102            .filter(|trait_type| !reflected.contains(trait_type))
103            .collect();
104
105        let reflect_trait_def_ids = crate::paths::PARTIAL_REFLECT.get(cx);
106
107        // Emit diagnostics for each of these types.
108        for (checked_trait, trait_name, message_phrase) in [
109            (events, "Event", "an event"),
110            (components, "Component", "a component"),
111            (resources, "Resource", "a resource"),
112        ] {
113            for without_reflect in checked_trait {
114                // Skip if a types originates from a foreign crate's macro
115                if without_reflect
116                    .item_span
117                    .in_external_macro(cx.tcx.sess.source_map())
118                {
119                    continue;
120                }
121
122                // This lint is machine applicable unless any of the struct's fields do not
123                // implement `PartialReflect`.
124                let mut applicability = Applicability::MachineApplicable;
125
126                // Find the `Item` definition of the struct missing `#[derive(Reflect)]`. We can use
127                // `expect_owner()` because the HIR ID was originally created from a `LocalDefId`,
128                // and we can use `expect_item()` because `TraitType::from_local_crate()` only
129                // returns items.
130                let without_reflect_item = cx
131                    .tcx
132                    .hir_expect_item(without_reflect.hir_id.expect_owner().def_id);
133
134                // Extract a list of all fields within the structure definition.
135                let fields = match without_reflect_item.kind {
136                    ItemKind::Struct(_, _, data) => data.fields().to_vec(),
137                    ItemKind::Enum(_, _, enum_def) => enum_def
138                        .variants
139                        .iter()
140                        .flat_map(|variant| variant.data.fields())
141                        .copied()
142                        .collect(),
143                    // Unions are explicitly unsupported by `#[derive(Reflect)]`, so we don't even
144                    // both checking the fields and just set the applicability to "maybe incorrect".
145                    ItemKind::Union(..) => {
146                        applicability = Applicability::MaybeIncorrect;
147                        Vec::new()
148                    }
149                    // This shouldn't be possible, as only structs, enums, and unions can implement
150                    // traits, so panic if this branch is reached.
151                    _ => span_unreachable!(
152                        without_reflect.item_span,
153                        "found a type that implements `Event`, `Component`, or `Resource` but is not a struct, enum, or union",
154                    ),
155                };
156
157                for field in fields {
158                    let ty = ty_from_hir_ty(cx, field.ty);
159
160                    // Check if the field's type implements the `PartialReflect` trait. If it does
161                    // not, change the `Applicability` level to `MaybeIncorrect` because `Reflect`
162                    // cannot be automatically derived.
163                    if !reflect_trait_def_ids
164                        .iter()
165                        .any(|&trait_id| implements_trait(cx, ty, trait_id, &[]))
166                    {
167                        applicability = Applicability::MaybeIncorrect;
168                        break;
169                    }
170                }
171
172                span_lint_hir_and_then(
173                    cx,
174                    MISSING_REFLECT,
175                    // This tells `rustc` where to search for `#[allow(...)]` attributes.
176                    without_reflect.hir_id,
177                    without_reflect.item_span,
178                    format!("defined {message_phrase} without a `Reflect` implementation"),
179                    |diag| {
180                        diag.span_note(
181                            without_reflect.impl_span,
182                            format!("`{trait_name}` implemented here"),
183                        )
184                        .suggest_item_with_attr(
185                            cx,
186                            without_reflect.item_span,
187                            "`Reflect` can be automatically derived",
188                            "#[derive(Reflect)]",
189                            // This suggestion may result in two consecutive
190                            // `#[derive(...)]` attributes, but `rustfmt` merges them
191                            // afterwards.
192                            applicability,
193                        );
194                    },
195                );
196            }
197        }
198    }
199}
200
201/// Represents a type that implements a specific trait.
202#[derive(Debug)]
203struct TraitType {
204    /// The [`HirId`] pointing to the type item declaration.
205    hir_id: HirId,
206    /// The span where the type was declared.
207    item_span: Span,
208    /// The span where the trait was implemented.
209    impl_span: Span,
210}
211
212impl TraitType {
213    fn from_local_crate<'tcx, 'a>(
214        cx: &'a LateContext<'tcx>,
215        trait_path: &'a PathLookup,
216    ) -> impl Iterator<Item = Self> + use<'tcx, 'a> {
217        // Find the `DefId` of the trait. There may be multiple if there are multiple versions of
218        // the same crate.
219        let trait_def_ids = trait_path
220            .get(cx)
221            .iter()
222            .filter(|&def_id| cx.tcx.def_kind(def_id) == DefKind::Trait);
223
224        // Find a map of all trait `impl` items within the current crate. The key is the `DefId` of
225        // the trait, and the value is a `Vec<LocalDefId>` for all `impl` items.
226        let all_trait_impls = cx.tcx.all_local_trait_impls(());
227
228        // Find all `impl` items for the specific trait.
229        let trait_impls = trait_def_ids
230            .filter_map(|def_id| all_trait_impls.get(def_id))
231            .flatten()
232            .copied();
233
234        // Map the `DefId`s of `impl` items to `TraitType`s. Sometimes this conversion can fail, so
235        // we use `filter_map()` to skip errors.
236        trait_impls.filter_map(move |local_def_id| {
237            // Retrieve the node of the `impl` item from its `DefId`.
238            let node = cx.tcx.hir_node_by_def_id(local_def_id);
239
240            // Verify that it's an `impl` item and not something else.
241            let Node::Item(Item {
242                kind: ItemKind::Impl(impl_),
243                span: impl_span,
244                ..
245            }) = node
246            else {
247                return None;
248            };
249
250            // Find where `T` in `impl T` was originally defined, after peeling away all references
251            // `&`. This was adapted from `clippy_utils::path_res()` in order to avoid passing
252            // `LateContext` to this function.
253            let def_id = match impl_.self_ty.peel_refs().kind {
254                TyKind::Path(QPath::Resolved(_, path)) => path.res.opt_def_id()?,
255                _ => return None,
256            };
257
258            // Tries to convert the `DefId` to a `LocalDefId`, exiting early if it cannot be done.
259            // This will only work if `T` in `impl T` is defined within the same crate.
260            //
261            // In most cases this will succeed due to Rust's orphan rule, but it notably fails
262            // within `bevy_reflect` itself, since that crate implements `Reflect` for `std` types
263            // such as `String`.
264            let local_def_id = def_id.as_local()?;
265
266            // Find the `HirId` from the `LocalDefId`. This is like a `DefId`, but with further
267            // constraints on what it can represent.
268            let hir_id = OwnerId {
269                def_id: local_def_id,
270            }
271            .into();
272
273            // Find the span where the type was declared. This is guaranteed to be an item, so we
274            // can safely call `expect_item()` without it panicking.
275            let item_span = cx.tcx.hir_node(hir_id).expect_item().span;
276
277            Some(TraitType {
278                hir_id,
279                item_span,
280                impl_span: *impl_span,
281            })
282        })
283    }
284}
285
286/// A custom equality implementation that just checks the [`HirId`] of the [`TraitType`], and skips
287/// the other values.
288///
289/// [`TraitType`]s with equal [`HirId`]s are guaranteed to be equal in all other fields, so this
290/// takes advantage of that fact.
291impl PartialEq for TraitType {
292    fn eq(&self, other: &Self) -> bool {
293        self.hir_id == other.hir_id
294    }
295}