Repository: bevyengine/bevy
File: crates/bevy_ecs/src/query/state.rs (Rust)

Code before:
    pub fn transmute_filtered<'a, NewD: QueryData, NewF: QueryFilter>(
        &self,
        world: impl Into<UnsafeWorldCell<'a>>,
    ) -> QueryState<NewD, NewF> {
        let world = world.into();
        self.validate_world(world.id());

        let mut component_access = FilteredAccess::default();
        let mut fetch_state = NewD::get_state(world.components()).expect("Could not create fetch_state, Please initialize all referenced components before transmuting.");
        let filter_state = NewF::get_state(world.components()).expect("Could not create filter_state, Please initialize all referenced components before transmuting.");

        NewD::set_access(&mut fetch_state, &self.component_access);
        NewD::update_component_access(&fetch_state, &mut component_access);

        let mut filter_component_access = FilteredAccess::default();
        NewF::update_component_access(&filter_state, &mut filter_component_access);

        component_access.extend(&filter_component_access);
        assert!(
            component_access.is_subset(&self.component_access),
            "Transmuted state for {} attempts to access terms that are not allowed by original state {}.",
            core::any::type_name::<(NewD, NewF)>(), core::any::type_name::<(D, F)>()
        );

        // For transmuted queries, the dense-ness of the query is equal to the dense-ness of the original query.
        // The check for `required` in `component_access.is_subset()` should ensure that this is always sound:
        // Any `WorldQuery` implementations that rely on a query being sparse for soundness,
        // including `&`, `&mut`, `Ref`, and `Mut`, will add a sparse component to the `required` set.
        // If the original query has the component in the `required` set, then it must also have been sparse.
        // That's even true for dynamic queries, since any `required` component will appear in the filters.
        let is_dense = self.is_dense;

        QueryState {
            world_id: self.world_id,
            archetype_generation: self.archetype_generation,
            matched_storage_ids: self.matched_storage_ids.clone(),
            is_dense,
            fetch_state,
            filter_state,
            component_access: self.component_access.clone(),
            matched_tables: self.matched_tables.clone(),
            matched_archetypes: self.matched_archetypes.clone(),
            #[cfg(feature = "trace")]
            par_iter_span: tracing::info_span!(
                "par_for_each",
                query = core::any::type_name::<NewD>(),
                filter = core::any::type_name::<NewF>(),
            ),
        }
    }


Review comment (suggestion):
I don't find that part super straightforward; how does knowing that the `Lens`'s required is a subset of the `Query`'s required enough to determine that this is sound?

Is it because `dense-ness` only depends on required components (as for those components we need to iterate only through archetypes that have that component)? 
And for optional components we can just always just iterate through the tables.

I think this might be key point that i'm missing

Code after:

    /// Use this to transform a [`QueryState`] into a more generic [`QueryState`].
    /// This can be useful for passing to another function that might take the more general form.
    /// See [`Query::transmute_lens`](crate::system::Query::transmute_lens) for more details.
    ///
    /// You should not call [`update_archetypes`](Self::update_archetypes) on the returned [`QueryState`] as the result will be unpredictable.
    /// You might end up with a mix of archetypes that only matched the original query + archetypes that only match
    /// the new [`QueryState`]. Most of the safe methods on [`QueryState`] call [`QueryState::update_archetypes`] internally, so this
    /// best used through a [`Query`]
    pub fn transmute<'a, NewD: QueryData>(
        &self,
        world: impl Into<UnsafeWorldCell<'a>>,
    ) -> QueryState<NewD> {
        self.transmute_filtered::<NewD, ()>(world.into())
    }

    /// Creates a new [`QueryState`] with the same underlying [`FilteredAccess`], matched tables and archetypes
    /// as self but with a new type signature.
    ///
    /// Panics if `NewD` or `NewF` require accesses that this query does not have.
    pub fn transmute_filtered<'a, NewD: QueryData, NewF: QueryFilter>(
        &self,
        world: impl Into<UnsafeWorldCell<'a>>,
    ) -> QueryState<NewD, NewF> {
        let world = world.into();
        self.validate_world(world.id());

        let mut component_access = FilteredAccess::default();
        let mut fetch_state = NewD::get_state(world.components()).expect("Could not create fetch_state, Please initialize all referenced components before transmuting.");
        let filter_state = NewF::get_state(world.components()).expect("Could not create filter_state, Please initialize all referenced components before transmuting.");

        let mut self_access = self.component_access.clone();
        if D::IS_READ_ONLY {
            // The current state was transmuted from a mutable
            // `QueryData` to a read-only one.
            // Ignore any write access in the current state.
            self_access.access_mut().clear_writes();
        }

        NewD::update_component_access(&fetch_state, &mut component_access);
        NewD::provide_extra_access(
            &mut fetch_state,
            component_access.access_mut(),
            self_access.access(),
        );

        let mut filter_component_access = FilteredAccess::default();
        NewF::update_component_access(&filter_state, &mut filter_component_access);

        component_access.extend(&filter_component_access);
        assert!(