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 sugg::DiagExt,
60 ty::{implements_trait, ty_from_hir_ty},
61};
62use rustc_errors::Applicability;
63use rustc_hir::ItemKind;
64use rustc_lint::{LateContext, LateLintPass};
65
66use crate::{
67 declare_bevy_lint, declare_bevy_lint_pass, span_unreachable, utils::traits::TraitType,
68};
69
70declare_bevy_lint! {
71 pub(crate) MISSING_REFLECT,
72 super::Restriction,
73 "defined a component, resource, or event without a `Reflect` implementation",
74}
75
76declare_bevy_lint_pass! {
77 pub(crate) MissingReflect => [MISSING_REFLECT],
78}
79
80impl<'tcx> LateLintPass<'tcx> for MissingReflect {
81 fn check_crate(&mut self, cx: &LateContext<'tcx>) {
82 // Finds all types that implement `Reflect` in this crate.
83 let reflected: Vec<TraitType> =
84 TraitType::from_local_crate(cx, &crate::paths::REFLECT).collect();
85
86 // Finds all non-`Reflect` types that implement `Event` in this crate.
87 let events: Vec<TraitType> = TraitType::from_local_crate(cx, &crate::paths::EVENT)
88 .filter(|trait_type| !reflected.contains(trait_type))
89 .collect();
90
91 // Finds all non-`Reflect` types that implement `Message` in this crate.
92 let messages: Vec<TraitType> = TraitType::from_local_crate(cx, &crate::paths::MESSAGE)
93 .filter(|trait_type| !reflected.contains(trait_type))
94 .collect();
95
96 // Finds all non-`Reflect` types that implement `Component` in this crate.
97 let components: Vec<TraitType> = TraitType::from_local_crate(cx, &crate::paths::COMPONENT)
98 .filter(|trait_type| !reflected.contains(trait_type))
99 .collect();
100
101 // Finds all non-`Reflect` types that implement `Resource` in this crate.
102 let resources: Vec<TraitType> = TraitType::from_local_crate(cx, &crate::paths::RESOURCE)
103 .filter(|trait_type| !reflected.contains(trait_type))
104 .collect();
105
106 let reflect_trait_def_ids = crate::paths::PARTIAL_REFLECT.get(cx);
107
108 // Emit diagnostics for each of these types.
109 for (checked_trait, trait_name, message_phrase) in [
110 (events, "Event", "an event"),
111 (messages, "Message", "a message"),
112 (components, "Component", "a component"),
113 (resources, "Resource", "a resource"),
114 ] {
115 for without_reflect in checked_trait {
116 // Skip if a types originates from a foreign crate's macro
117 if without_reflect
118 .item_span
119 .in_external_macro(cx.tcx.sess.source_map())
120 {
121 continue;
122 }
123
124 // This lint is machine applicable unless any of the struct's fields do not
125 // implement `PartialReflect`.
126 let mut applicability = Applicability::MachineApplicable;
127
128 // Find the `Item` definition of the struct missing `#[derive(Reflect)]`. We can use
129 // `expect_owner()` because the HIR ID was originally created from a `LocalDefId`,
130 // and we can use `expect_item()` because `TraitType::from_local_crate()` only
131 // returns items.
132 let without_reflect_item = cx
133 .tcx
134 .hir_expect_item(without_reflect.hir_id.expect_owner().def_id);
135
136 // Extract a list of all fields within the structure definition.
137 let fields = match without_reflect_item.kind {
138 ItemKind::Struct(_, _, data) => data.fields().to_vec(),
139 ItemKind::Enum(_, _, enum_def) => enum_def
140 .variants
141 .iter()
142 .flat_map(|variant| variant.data.fields())
143 .copied()
144 .collect(),
145 // Unions are explicitly unsupported by `#[derive(Reflect)]`, so we don't even
146 // both checking the fields and just set the applicability to "maybe incorrect".
147 ItemKind::Union(..) => {
148 applicability = Applicability::MaybeIncorrect;
149 Vec::new()
150 }
151 // This shouldn't be possible, as only structs, enums, and unions can implement
152 // traits, so panic if this branch is reached.
153 _ => span_unreachable!(
154 without_reflect.item_span,
155 "found a type that implements `Event`, `Component`, `Message`, or `Resource` but is not a struct, enum, or union",
156 ),
157 };
158
159 for field in fields {
160 let ty = ty_from_hir_ty(cx, field.ty);
161
162 // Check if the field's type implements the `PartialReflect` trait. If it does
163 // not, change the `Applicability` level to `MaybeIncorrect` because `Reflect`
164 // cannot be automatically derived.
165 if !reflect_trait_def_ids
166 .iter()
167 .any(|&trait_id| implements_trait(cx, ty, trait_id, &[]))
168 {
169 applicability = Applicability::MaybeIncorrect;
170 break;
171 }
172 }
173
174 span_lint_hir_and_then(
175 cx,
176 MISSING_REFLECT,
177 // This tells `rustc` where to search for `#[allow(...)]` attributes.
178 without_reflect.hir_id,
179 without_reflect.item_span,
180 format!("defined {message_phrase} without a `Reflect` implementation"),
181 |diag| {
182 diag.span_note(
183 without_reflect.impl_span,
184 format!("`{trait_name}` implemented here"),
185 )
186 .suggest_item_with_attr(
187 cx,
188 without_reflect.item_span,
189 "`Reflect` can be automatically derived",
190 "#[derive(Reflect)]",
191 // This suggestion may result in two consecutive
192 // `#[derive(...)]` attributes, but `rustfmt` merges them
193 // afterwards.
194 applicability,
195 );
196 },
197 );
198 }
199 }
200 }
201}