Skip to content

Commit

Permalink
Enable clippy::undocumented_unsafe_blocks warning across the worksp…
Browse files Browse the repository at this point in the history
…ace (#10646)

# Objective

Enables warning on `clippy::undocumented_unsafe_blocks` across the
workspace rather than only in `bevy_ecs`, `bevy_transform` and
`bevy_utils`. This adds a little awkwardness in a few areas of code that
have trivial safety or explain safety for multiple unsafe blocks with
one comment however automatically prevents these comments from being
missed.

## Solution

This adds `undocumented_unsafe_blocks = "warn"` to the workspace
`Cargo.toml` and fixes / adds a few missed safety comments. I also added
`#[allow(clippy::undocumented_unsafe_blocks)]` where the safety is
explained somewhere above.

There are a couple of safety comments I added I'm not 100% sure about in
`bevy_animation` and `bevy_render/src/view` and I'm not sure about the
use of `#[allow(clippy::undocumented_unsafe_blocks)]` compared to adding
comments like `// SAFETY: See above`.
  • Loading branch information
13ros27 authored Nov 21, 2023
1 parent 897b13b commit e67cfdf
Show file tree
Hide file tree
Showing 13 changed files with 28 additions and 16 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ members = [
[workspace.lints.clippy]
type_complexity = "allow"
doc_markdown = "warn"
undocumented_unsafe_blocks = "warn"

[lints]
workspace = true
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_animation/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,7 @@ fn apply_animation(
let Ok(mut transform) = (unsafe { transforms.get_unchecked(target) }) else {
continue;
};
// SAFETY: As above, there can't be other AnimationPlayers with this target so this fetch can't alias
let mut morphs = unsafe { morphs.get_unchecked(target) };
for curve in curves {
// Some curves have only one keyframe used to set a transform
Expand Down
1 change: 0 additions & 1 deletion crates/bevy_ecs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#![warn(clippy::undocumented_unsafe_blocks)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]

Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_mikktspace/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![allow(clippy::all)]
#![allow(clippy::all, clippy::undocumented_unsafe_blocks)]

use glam::{Vec2, Vec3};

Expand Down
8 changes: 4 additions & 4 deletions crates/bevy_ptr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,14 +244,14 @@ impl<'a, A: IsAligned> PtrMut<'a, A> {
/// Gets a [`PtrMut`] from this with a smaller lifetime.
#[inline]
pub fn reborrow(&mut self) -> PtrMut<'_, A> {
// SAFE: the ptrmut we're borrowing from is assumed to be valid
// SAFETY: the ptrmut we're borrowing from is assumed to be valid
unsafe { PtrMut::new(self.0) }
}

/// Gets an immutable reference from this mutable reference
#[inline]
pub fn as_ref(&self) -> Ptr<'_, A> {
// SAFE: The `PtrMut` type's guarantees about the validity of this pointer are a superset of `Ptr` s guarantees
// SAFETY: The `PtrMut` type's guarantees about the validity of this pointer are a superset of `Ptr` s guarantees
unsafe { Ptr::new(self.0) }
}
}
Expand Down Expand Up @@ -327,14 +327,14 @@ impl<'a, A: IsAligned> OwningPtr<'a, A> {
/// Gets an immutable pointer from this owned pointer.
#[inline]
pub fn as_ref(&self) -> Ptr<'_, A> {
// SAFE: The `Owning` type's guarantees about the validity of this pointer are a superset of `Ptr` s guarantees
// SAFETY: The `Owning` type's guarantees about the validity of this pointer are a superset of `Ptr` s guarantees
unsafe { Ptr::new(self.0) }
}

/// Gets a mutable pointer from this owned pointer.
#[inline]
pub fn as_mut(&mut self) -> PtrMut<'_, A> {
// SAFE: The `Owning` type's guarantees about the validity of this pointer are a superset of `Ptr` s guarantees
// SAFETY: The `Owning` type's guarantees about the validity of this pointer are a superset of `Ptr` s guarantees
unsafe { PtrMut::new(self.0) }
}
}
Expand Down
6 changes: 4 additions & 2 deletions crates/bevy_render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ impl Plugin for RenderPlugin {
app.insert_resource(FutureRendererResources(
future_renderer_resources_wrapper.clone(),
));
// SAFETY: Plugins should be set up on the main thread.
unsafe { initialize_render_app(app) };
}
RenderCreation::Automatic(render_creation) => {
Expand All @@ -271,8 +272,8 @@ impl Plugin for RenderPlugin {
backends,
dx12_shader_compiler: settings.dx12_shader_compiler.clone(),
});
// SAFETY: Plugins should be set up on the main thread.
let surface = primary_window.map(|wrapper| unsafe {
// SAFETY: Plugins should be set up on the main thread.
let handle = wrapper.get_handle();
instance
.create_surface(&handle)
Expand Down Expand Up @@ -313,6 +314,7 @@ impl Plugin for RenderPlugin {
#[cfg(not(target_arch = "wasm32"))]
futures_lite::future::block_on(async_renderer);

// SAFETY: Plugins should be set up on the main thread.
unsafe { initialize_render_app(app) };
}
}
Expand Down Expand Up @@ -453,7 +455,7 @@ unsafe fn initialize_render_app(app: &mut App) {
"An entity was spawned after the entity list was cleared last frame and before the extract schedule began. This is not supported",
);

// This is safe given the clear_entities call in the past frame and the assert above
// SAFETY: This is safe given the clear_entities call in the past frame and the assert above
unsafe {
render_app
.world
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_render/src/render_resource/resource_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ macro_rules! render_resource_wrapper {
// If in future there is a case where a wrapper is required for a non-send/sync type
// we can implement a macro variant that omits these manual Send + Sync impls
unsafe impl Send for $wrapper_type {}
// SAFETY: As explained above, we ensure correctness by checking that $wgpu_type implements Send and Sync.
unsafe impl Sync for $wrapper_type {}
const _: () = {
trait AssertSendSyncBound: Send + Sync {}
Expand Down
15 changes: 9 additions & 6 deletions crates/bevy_render/src/view/window/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,15 @@ pub fn prepare_windows(
let surface_data = window_surfaces
.surfaces
.entry(window.entity)
.or_insert_with(|| unsafe {
// NOTE: On some OSes this MUST be called from the main thread.
// As of wgpu 0.15, only fallible if the given window is a HTML canvas and obtaining a WebGPU or WebGL2 context fails.
let surface = render_instance
.create_surface(&window.handle.get_handle())
.expect("Failed to create wgpu surface");
.or_insert_with(|| {
// SAFETY: The window handles in ExtractedWindows will always be valid objects to create surfaces on
let surface = unsafe {
// NOTE: On some OSes this MUST be called from the main thread.
// As of wgpu 0.15, only fallible if the given window is a HTML canvas and obtaining a WebGPU or WebGL2 context fails.
render_instance
.create_surface(&window.handle.get_handle())
.expect("Failed to create wgpu surface")
};
let caps = surface.get_capabilities(&render_adapter);
let formats = caps.formats;
// For future HDR output support, we'll need to request a format that supports HDR,
Expand Down
5 changes: 5 additions & 0 deletions crates/bevy_tasks/src/task_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,12 +353,16 @@ impl TaskPool {
// Any usages of the references passed into `Scope` must be accessed through
// the transmuted reference for the rest of this function.
let executor: &async_executor::Executor = &self.executor;
// SAFETY: As above, all futures must complete in this function so we can change the lifetime
let executor: &'env async_executor::Executor = unsafe { mem::transmute(executor) };
// SAFETY: As above, all futures must complete in this function so we can change the lifetime
let external_executor: &'env ThreadExecutor<'env> =
unsafe { mem::transmute(external_executor) };
// SAFETY: As above, all futures must complete in this function so we can change the lifetime
let scope_executor: &'env ThreadExecutor<'env> = unsafe { mem::transmute(scope_executor) };
let spawned: ConcurrentQueue<FallibleTask<T>> = ConcurrentQueue::unbounded();
// shadow the variable so that the owned value cannot be used for the rest of the function
// SAFETY: As above, all futures must complete in this function so we can change the lifetime
let spawned: &'env ConcurrentQueue<
FallibleTask<Result<T, Box<(dyn std::any::Any + Send)>>>,
> = unsafe { mem::transmute(&spawned) };
Expand All @@ -373,6 +377,7 @@ impl TaskPool {
};

// shadow the variable so that the owned value cannot be used for the rest of the function
// SAFETY: As above, all futures must complete in this function so we can change the lifetime
let scope: &'env Scope<'_, 'env, T> = unsafe { mem::transmute(&scope) };

f(scope);
Expand Down
1 change: 0 additions & 1 deletion crates/bevy_transform/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#![warn(missing_docs)]
#![warn(clippy::undocumented_unsafe_blocks)]
#![doc = include_str!("../README.md")]

pub mod commands;
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_ui/src/ui_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,7 @@ pub struct GridPlacement {
impl GridPlacement {
pub const DEFAULT: Self = Self {
start: None,
// SAFETY: This is trivially safe as 1 is non-zero.
span: Some(unsafe { NonZeroU16::new_unchecked(1) }),
end: None,
};
Expand Down
1 change: 0 additions & 1 deletion crates/bevy_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//!

#![warn(missing_docs)]
#![warn(clippy::undocumented_unsafe_blocks)]

#[allow(missing_docs)]
pub mod prelude {
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_window/src/raw_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ impl RawHandleWrapper {
// A recommendation for this pattern (and more context) is available here:
// https://github.com/rust-windowing/raw-window-handle/issues/59
unsafe impl Send for RawHandleWrapper {}
// SAFETY: This is safe for the same reasons as the Send impl above.
unsafe impl Sync for RawHandleWrapper {}

/// A [`RawHandleWrapper`] that cannot be sent across threads.
Expand Down

0 comments on commit e67cfdf

Please sign in to comment.