bevy/crates/bevy_ecs/src/system/exclusive_system_param.rs
Tau Gärtli aab1f8e435
Use #[doc(fake_variadic)] to improve docs readability (#14703)
# Objective

- Fixes #14697

## Solution

This PR modifies the existing `all_tuples!` macro to optionally accept a
`#[doc(fake_variadic)]` attribute in its input. If the attribute is
present, each invocation of the impl macro gets the correct attributes
(i.e. the first impl receives `#[doc(fake_variadic)]` while the other
impls are hidden using `#[doc(hidden)]`.
Impls for the empty tuple (unit type) are left untouched (that's what
the [standard
library](https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#impl-PartialEq-for-())
and
[serde](https://docs.rs/serde/latest/serde/trait.Serialize.html#impl-Serialize-for-())
do).

To work around https://github.com/rust-lang/cargo/issues/8811 and to get
impls on re-exports to correctly show up as variadic, `--cfg docsrs_dep`
is passed when building the docs for the toplevel `bevy` crate.

`#[doc(fake_variadic)]` only works on tuples and fn pointers, so impls
for structs like `AnyOf<(T1, T2, ..., Tn)>` are unchanged.

## Testing

I built the docs locally using `RUSTDOCFLAGS='--cfg docsrs'
RUSTFLAGS='--cfg docsrs_dep' cargo +nightly doc --no-deps --workspace`
and checked the documentation page of a trait both in its original crate
and the re-exported version in `bevy`.
The description should correctly mention for how many tuple items the
trait is implemented.

I added `rustc-args` for docs.rs to the `bevy` crate, I hope there
aren't any other notable crates that re-export `#[doc(fake_variadic)]`
traits.

---

## Showcase

`bevy_ecs::query::QueryData`:
<img width="1015" alt="Screenshot 2024-08-12 at 16 41 28"
src="https://github.com/user-attachments/assets/d40136ed-6731-475f-91a0-9df255cd24e3">

`bevy::ecs::query::QueryData` (re-export):
<img width="1005" alt="Screenshot 2024-08-12 at 16 42 57"
src="https://github.com/user-attachments/assets/71d44cf0-0ab0-48b0-9a51-5ce332594e12">

## Original Description

<details>

Resolves #14697

Submitting as a draft for now, very WIP.

Unfortunately, the docs don't show the variadics nicely when looking at
reexported items.
For example:

`bevy_ecs::bundle::Bundle` correctly shows the variadic impl:

![image](https://github.com/user-attachments/assets/90bf8af1-1d1f-4714-9143-cdd3d0199998)

while `bevy::ecs::bundle::Bundle` (the reexport) shows all the impls
(not good):

![image](https://github.com/user-attachments/assets/439c428e-f712-465b-bec2-481f7bf5870b)

Built using `RUSTDOCFLAGS='--cfg docsrs' cargo +nightly doc --workspace
--no-deps` (`--no-deps` because of wgpu-core).

Maybe I missed something or this is a limitation in the *totally not
private* `#[doc(fake_variadic)]` thingy. In any case I desperately need
some sleep now :))

</details>
2024-08-12 18:54:33 +00:00

159 lines
5.0 KiB
Rust

use crate::{
prelude::{FromWorld, QueryState},
query::{QueryData, QueryFilter},
system::{Local, SystemMeta, SystemParam, SystemState},
world::World,
};
use bevy_utils::all_tuples;
use bevy_utils::synccell::SyncCell;
use std::marker::PhantomData;
/// A parameter that can be used in an exclusive system (a system with an `&mut World` parameter).
/// Any parameters implementing this trait must come after the `&mut World` parameter.
#[diagnostic::on_unimplemented(
message = "`{Self}` can not be used as a parameter for an exclusive system",
label = "invalid system parameter"
)]
pub trait ExclusiveSystemParam: Sized {
/// Used to store data which persists across invocations of a system.
type State: Send + Sync + 'static;
/// The item type returned when constructing this system param.
/// See [`SystemParam::Item`].
type Item<'s>: ExclusiveSystemParam<State = Self::State>;
/// Creates a new instance of this param's [`State`](Self::State).
fn init(world: &mut World, system_meta: &mut SystemMeta) -> Self::State;
/// Creates a parameter to be passed into an [`ExclusiveSystemParamFunction`].
///
/// [`ExclusiveSystemParamFunction`]: super::ExclusiveSystemParamFunction
fn get_param<'s>(state: &'s mut Self::State, system_meta: &SystemMeta) -> Self::Item<'s>;
}
/// Shorthand way of accessing the associated type [`ExclusiveSystemParam::Item`]
/// for a given [`ExclusiveSystemParam`].
pub type ExclusiveSystemParamItem<'s, P> = <P as ExclusiveSystemParam>::Item<'s>;
impl<'a, D: QueryData + 'static, F: QueryFilter + 'static> ExclusiveSystemParam
for &'a mut QueryState<D, F>
{
type State = QueryState<D, F>;
type Item<'s> = &'s mut QueryState<D, F>;
fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
QueryState::new(world)
}
fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
state
}
}
impl<'a, P: SystemParam + 'static> ExclusiveSystemParam for &'a mut SystemState<P> {
type State = SystemState<P>;
type Item<'s> = &'s mut SystemState<P>;
fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
SystemState::new(world)
}
fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
state
}
}
impl<'_s, T: FromWorld + Send + 'static> ExclusiveSystemParam for Local<'_s, T> {
type State = SyncCell<T>;
type Item<'s> = Local<'s, T>;
fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
SyncCell::new(T::from_world(world))
}
fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
Local(state.get())
}
}
impl<S: ?Sized> ExclusiveSystemParam for PhantomData<S> {
type State = ();
type Item<'s> = PhantomData<S>;
fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {}
fn get_param<'s>(_state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
PhantomData
}
}
macro_rules! impl_exclusive_system_param_tuple {
($(#[$meta:meta])* $($param: ident),*) => {
#[allow(unused_variables)]
#[allow(non_snake_case)]
$(#[$meta])*
impl<$($param: ExclusiveSystemParam),*> ExclusiveSystemParam for ($($param,)*) {
type State = ($($param::State,)*);
type Item<'s> = ($($param::Item<'s>,)*);
#[inline]
fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
(($($param::init(_world, _system_meta),)*))
}
#[inline]
#[allow(clippy::unused_unit)]
fn get_param<'s>(
state: &'s mut Self::State,
system_meta: &SystemMeta,
) -> Self::Item<'s> {
let ($($param,)*) = state;
($($param::get_param($param, system_meta),)*)
}
}
};
}
all_tuples!(
#[doc(fake_variadic)]
impl_exclusive_system_param_tuple,
0,
16,
P
);
#[cfg(test)]
mod tests {
use crate as bevy_ecs;
use crate::schedule::Schedule;
use crate::system::Local;
use crate::world::World;
use bevy_ecs_macros::Resource;
use std::marker::PhantomData;
#[test]
fn test_exclusive_system_params() {
#[derive(Resource, Default)]
struct Res {
test_value: u32,
}
fn my_system(world: &mut World, mut local: Local<u32>, _phantom: PhantomData<Vec<u32>>) {
assert_eq!(world.resource::<Res>().test_value, *local);
*local += 1;
world.resource_mut::<Res>().test_value += 1;
}
let mut schedule = Schedule::default();
schedule.add_systems(my_system);
let mut world = World::default();
world.init_resource::<Res>();
schedule.run(&mut world);
schedule.run(&mut world);
assert_eq!(2, world.get_resource::<Res>().unwrap().test_value);
}
}