diff --git a/CHANGELOG.md b/CHANGELOG.md index afc5cc932..d10c05503 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,12 @@ Bottom level categories: - Add `BufferBinding::buffer`, a public read accessor for the bound buffer, which was previously inaccessible to out-of-tree `wgpu_hal::Api` implementations. By @danlehmann in [#9820](https://github.com/gfx-rs/wgpu/pull/9820). +### Changes + +#### naga + +- `naga::valid::ValidationError` is now always returned boxed, to avoid `clippy::large_result_err` warning. By @beicause in [#9612](https://github.com/gfx-rs/wgpu/pull/9612) + ### Bug Fixes #### GLES diff --git a/clippy.toml b/clippy.toml index 670bd498b..1ef30a54a 100644 --- a/clippy.toml +++ b/clippy.toml @@ -5,10 +5,6 @@ disallowed-types = [ { path = "std::collections::HashSet", reason = "use hashbrown::HashSet instead" }, ] -# The default large-error-threshold is 128. We have a bunch of complex error -# types that are slightly larger than that. -large-error-threshold = 192 - # This relatively small stack frame limit is set to avoid problems in several deeply # recursive functions in naga. If your function has a genuine need for a larger stack frame, # and is not at risk of deep recursion based on shader structure, it is okay to waive the diff --git a/naga/src/back/pipeline_constants.rs b/naga/src/back/pipeline_constants.rs index b9e429cf3..312135ae1 100644 --- a/naga/src/back/pipeline_constants.rs +++ b/naga/src/back/pipeline_constants.rs @@ -1,5 +1,6 @@ use alloc::{ borrow::Cow, + boxed::Box, string::{String, ToString}, vec::Vec, }; @@ -40,7 +41,7 @@ pub enum PipelineConstantError { #[error(transparent)] ConstantEvaluatorError(#[from] ConstantEvaluatorError), #[error(transparent)] - ValidationError(#[from] WithSpan), + ValidationError(#[from] Box>), #[error("workgroup_size override isn't strictly positive")] NegativeWorkgroupSize, #[error("max vertices or max primitives is negative")] diff --git a/naga/src/valid/expression.rs b/naga/src/valid/expression.rs index 6f206bae3..18188200e 100644 --- a/naga/src/valid/expression.rs +++ b/naga/src/valid/expression.rs @@ -6,6 +6,9 @@ use crate::{ proc::{IndexableLengthError, ResolveError}, }; +#[cfg(test)] +use alloc::boxed::Box; + #[derive(Clone, Debug, thiserror::Error)] #[cfg_attr(test, derive(PartialEq))] pub enum ExpressionError { @@ -1487,7 +1490,7 @@ pub const fn check_literal_value(literal: crate::Literal) -> Result<(), LiteralE fn validate_with_expression( expr: crate::Expression, caps: super::Capabilities, -) -> Result> { +) -> Result>> { use crate::span::Span; let mut function = crate::Function::default(); @@ -1510,7 +1513,7 @@ fn validate_with_expression( fn validate_with_const_expression( expr: crate::Expression, caps: super::Capabilities, -) -> Result> { +) -> Result>> { use crate::span::Span; let mut module = crate::Module::default(); diff --git a/naga/src/valid/handles.rs b/naga/src/valid/handles.rs index 93af8a69d..88c1bf4b6 100644 --- a/naga/src/valid/handles.rs +++ b/naga/src/valid/handles.rs @@ -1,5 +1,6 @@ //! Implementation of `Validator::validate_module_handles`. +use alloc::boxed::Box; use core::{convert::TryInto, hash::Hash}; use super::{TypeError, ValidationError}; @@ -30,7 +31,9 @@ impl super::Validator { /// Errors returned by this method are intentionally sparse, for simplicity of implementation. /// It is expected that only buggy frontends or fuzzers should ever emit IR that fails this /// validation pass. - pub(super) fn validate_module_handles(module: &crate::Module) -> Result<(), ValidationError> { + pub(super) fn validate_module_handles( + module: &crate::Module, + ) -> Result<(), Box> { let &crate::Module { ref constants, ref overrides, @@ -312,14 +315,14 @@ impl super::Validator { _ => { // TODO: internal error ? We should never get here. // If entering there, it's probably that we forgot to adjust a handle in the compact phase. - return Err(ValidationError::Type { + return Err(Box::new(ValidationError::Type { handle: ty, name: struct_type .name .as_ref() .map_or_else(|| "Unknown".to_string(), |name| name.to_string()), source: TypeError::InvalidData(ty), - }); + })); } } for (&function, _) in doc_comments_for_functions.iter() { @@ -885,21 +888,27 @@ impl super::Validator { } } -impl From for ValidationError { +impl From for Box { fn from(source: BadHandle) -> Self { - Self::InvalidHandle(source.into()) + Box::new(ValidationError::InvalidHandle(source.into())) } } -impl From for ValidationError { +impl From for Box { fn from(source: FwdDepError) -> Self { - Self::InvalidHandle(source.into()) + Box::new(ValidationError::InvalidHandle(source.into())) } } -impl From for ValidationError { +impl From for Box { fn from(source: BadRangeError) -> Self { - Self::InvalidHandle(source.into()) + Box::new(ValidationError::InvalidHandle(source.into())) + } +} + +impl From for Box { + fn from(source: InvalidHandleError) -> Self { + Box::new(ValidationError::InvalidHandle(source)) } } diff --git a/naga/src/valid/mod.rs b/naga/src/valid/mod.rs index 8dc549f2f..b92422f95 100644 --- a/naga/src/valid/mod.rs +++ b/naga/src/valid/mod.rs @@ -733,7 +733,7 @@ impl Validator { pub fn validate( &mut self, module: &crate::Module, - ) -> Result> { + ) -> Result>> { self.overrides_resolved = false; self.validate_impl(module) } @@ -748,7 +748,7 @@ impl Validator { pub fn validate_resolved_overrides( &mut self, module: &crate::Module, - ) -> Result> { + ) -> Result>> { self.overrides_resolved = true; self.validate_impl(module) } @@ -756,11 +756,11 @@ impl Validator { fn validate_impl( &mut self, module: &crate::Module, - ) -> Result> { + ) -> Result>> { self.reset(); self.reset_types(module.types.len()); - Self::validate_module_handles(module).map_err(|e| e.with_span())?; + Self::validate_module_handles(module).map_err(|e| Box::new((*e).with_span()))?; self.layouter.update(module.to_ctx()).map_err(|e| { let handle = e.ty; @@ -870,14 +870,14 @@ impl Validator { match self.validate_function(fun, module, &mod_info, false) { Ok(info) => mod_info.functions.push(info), Err(error) => { - return Err(error.and_then(|source| { + return Err(Box::new(error.and_then(|source| { ValidationError::Function { handle, name: fun.name.clone().unwrap_or_default(), source, } .with_span_handle(handle, &module.functions) - })) + }))) } } } @@ -885,25 +885,27 @@ impl Validator { let mut ep_map = FastHashSet::default(); for ep in module.entry_points.iter() { if !ep_map.insert((ep.stage, &ep.name)) { - return Err(ValidationError::EntryPoint { - stage: ep.stage, - name: ep.name.clone(), - source: EntryPointError::Conflict, - } - .with_span()); // TODO: keep some EP span information? + return Err(Box::new( + ValidationError::EntryPoint { + stage: ep.stage, + name: ep.name.clone(), + source: EntryPointError::Conflict, + } + .with_span(), + )); // TODO: keep some EP span information? } match self.validate_entry_point(ep, module, &mod_info) { Ok(info) => mod_info.entry_points.push(info), Err(error) => { - return Err(error.and_then(|source| { + return Err(Box::new(error.and_then(|source| { ValidationError::EntryPoint { stage: ep.stage, name: ep.name.clone(), source, } .with_span() - })); + }))); } } } diff --git a/naga/tests/naga/validation.rs b/naga/tests/naga/validation.rs index b3e41e2e0..bb22b70ad 100644 --- a/naga/tests/naga/validation.rs +++ b/naga/tests/naga/validation.rs @@ -87,7 +87,7 @@ fn populate_atomic_result() { // the differences between the test cases. fn try_variant( variant: Variant, - ) -> Result> { + ) -> Result>> { let span = naga::Span::default(); let mut module = Module::default(); let ty_u32 = module.types.insert( @@ -189,7 +189,7 @@ fn populate_call_result() { // the differences between the test cases. fn try_variant( variant: Variant, - ) -> Result> { + ) -> Result>> { let span = naga::Span::default(); let mut module = Module::default(); let ty_u32 = module.types.insert( @@ -265,7 +265,9 @@ fn emit_workgroup_uniform_load_result() { // // Looking at uses of the `wg_load` makes it easy to identify the // differences between the two variants. - fn variant(wg_load: bool) -> Result> { + fn variant( + wg_load: bool, + ) -> Result>> { let span = naga::Span::default(); let mut module = Module::default(); let ty_u32 = module.types.insert( @@ -337,7 +339,7 @@ fn builtin_cross_product_args() { fn variant( size: VectorSize, arity: usize, - ) -> Result> { + ) -> Result>> { let span = naga::Span::default(); let mut module = Module::default(); let ty_vec3f = module.types.insert( @@ -754,7 +756,7 @@ error: Function [1] 'main' is invalid #[test] fn bad_texture_dimensions_level() { - fn validate(level: &str) -> Result { + fn validate(level: &str) -> Result> { let source = format!( r#" @group(0) @binding(0) @@ -767,12 +769,12 @@ fn bad_texture_dimensions_level() { let module = naga::front::wgsl::parse_str(&source).expect("module should parse"); valid::Validator::new(Default::default(), valid::Capabilities::all()) .validate(&module) - .map_err(|err| err.into_inner()) // discard spans + .map_err(|err| Box::new(err.into_inner())) // discard spans } - fn is_bad_level_error(result: Result) -> bool { + fn is_bad_level_error(result: Result>) -> bool { matches!( - result, + result.map_err(|e| *e), Err(naga::valid::ValidationError::Function { handle: _, name: _, @@ -1203,7 +1205,7 @@ fn arity_check() { use naga::Span; let _ = env_logger::builder().is_test(true).try_init(); - type Result = core::result::Result; + type Result = core::result::Result>; fn validate(fun: ir::MathFunction, args: &[usize]) -> Result { let nowhere = Span::default(); @@ -1244,7 +1246,7 @@ fn arity_check() { module.functions.append(f, nowhere); valid::Validator::new(Default::default(), valid::Capabilities::all()) .validate(&module) - .map_err(|err| err.into_inner()) // discard spans + .map_err(|err| Box::new(err.into_inner())) // discard spans } assert!(validate(Mf::Sin, &[]).is_ok()); diff --git a/naga/tests/naga/wgsl_errors.rs b/naga/tests/naga/wgsl_errors.rs index 67d1ffcbf..1543ee702 100644 --- a/naga/tests/naga/wgsl_errors.rs +++ b/naga/tests/naga/wgsl_errors.rs @@ -1145,10 +1145,10 @@ macro_rules! check_extension_validation { // Don't check with explicitly allowed caps, as certain things (currently just // `acceleration_structure`s) can be enabled by multiple extensions let error = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), !(caps | other_caps)) - .validate(&module) - .map_err(|e| e.into_inner()); // TODO(https://github.com/gfx-rs/wgpu/issues/8153): Add tests for spans + .validate(&module).map_err(|e|e.into_inner()); + let error = error.as_ref(); // TODO(https://github.com/gfx-rs/wgpu/issues/8153): Add tests for spans #[allow(clippy::redundant_pattern_matching)] - if !matches!(&error, $val_err_pat) { + if !matches!(error, $val_err_pat) { eprintln!( concat!( "validation error without {:?} does not match pattern:\n", @@ -1212,6 +1212,16 @@ macro_rules! check_validation { } } +#[cfg_attr( + not(target_pointer_width = "32"), + expect( + clippy::result_large_err, + reason = "`ValidationError` is large enough that it should usually be boxed, \ + but this is only a test, and it makes the `match` expressions \ + in the callers a bit cleaner. \ + This lint does not trigger on 32-bit builds." + ) +)] #[track_caller] fn validation_error( source: &str, @@ -5078,7 +5088,7 @@ fn binding_array_requires_capability() { check_validation! { r#" - enable wgpu_binding_array; + enable wgpu_binding_array; struct Buffer { data: u32 } @group(0) @binding(0) var uniform_array: binding_array; diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index 6405108ab..67a1d81d4 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -80,6 +80,7 @@ index format changes. use alloc::{ borrow::{Cow, ToOwned as _}, + boxed::Box, string::String, string::ToString as _, sync::Arc, @@ -1896,13 +1897,12 @@ where pub struct RenderBundleError { pub scope: PassErrorScope, #[source] - inner: RenderBundleErrorInner, + inner: Box, } impl WebGpuError for RenderBundleError { fn webgpu_error_type(&self) -> ErrorType { - let Self { scope: _, inner } = self; - match inner { + match self.inner.as_ref() { RenderBundleErrorInner::Create(e) => e.webgpu_error_type(), RenderBundleErrorInner::Device(e) => e.webgpu_error_type(), RenderBundleErrorInner::RenderCommand(e) => e.webgpu_error_type(), @@ -1918,7 +1918,7 @@ impl RenderBundleError { pub fn from_device_error(e: DeviceError) -> Self { Self { scope: PassErrorScope::Bundle, - inner: e.into(), + inner: Box::new(e.into()), } } } @@ -1930,7 +1930,7 @@ where fn map_pass_err(self, scope: PassErrorScope) -> RenderBundleError { RenderBundleError { scope, - inner: self.into(), + inner: Box::new(self.into()), } } } diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index 7fd7c158e..fa0b9ec9b 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -1701,23 +1701,18 @@ impl CommandEncoderError { inner: ComputePassErrorInner::DestroyedResource(_), .. }) - | Self::RenderPass(RenderPassError { - inner: RenderPassErrorInner::DestroyedResource(_), - .. - }) - | Self::RenderPass(RenderPassError { - inner: RenderPassErrorInner::RenderCommand( - RenderCommandError::DestroyedResource(_) - ), - .. - }) - | Self::RenderPass(RenderPassError { - inner: RenderPassErrorInner::RenderCommand(RenderCommandError::BindingError( - BindingError::DestroyedResource(_) - )), - .. - }) - ) + ) || if let Self::RenderPass(pass_error) = self { + matches!( + pass_error.inner.as_ref(), + RenderPassErrorInner::DestroyedResource(_) + | RenderPassErrorInner::RenderCommand(RenderCommandError::DestroyedResource(_)) + | RenderPassErrorInner::RenderCommand(RenderCommandError::BindingError( + BindingError::DestroyedResource(_), + )) + ) + } else { + false + } } } diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 14b4784fc..9747fc945 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -1,4 +1,4 @@ -use alloc::{borrow::Cow, sync::Arc, vec::Vec}; +use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec}; use core::{convert::Infallible, fmt, num::NonZeroU32, ops::Range, str}; use parking_lot::Mutex; use smallvec::SmallVec; @@ -1071,22 +1071,21 @@ impl From for RenderPassErrorInner { pub struct RenderPassError { pub scope: PassErrorScope, #[source] - pub(super) inner: RenderPassErrorInner, + pub(super) inner: Box, } impl> MapPassErr for E { fn map_pass_err(self, scope: PassErrorScope) -> RenderPassError { RenderPassError { scope, - inner: self.into(), + inner: Box::new(self.into()), } } } impl WebGpuError for RenderPassError { fn webgpu_error_type(&self) -> ErrorType { - let Self { scope: _, inner } = self; - match inner { + match self.inner.as_ref() { RenderPassErrorInner::Device(e) => e.webgpu_error_type(), RenderPassErrorInner::ColorAttachment(e) => e.webgpu_error_type(), RenderPassErrorInner::EncoderState(e) => e.webgpu_error_type(), @@ -2165,21 +2164,19 @@ impl RenderPass { let base = self.base.take(); - if let Err(RenderPassError { - inner: - RenderPassErrorInner::EncoderState( - err @ (EncoderStateError::Locked | EncoderStateError::Ended), - ), - scope: _, - }) = base - { - // Most encoding errors are detected and raised within `finish()`. - // - // However, we raise a validation error here if the pass was opened - // within another pass, or on a finished encoder. The latter is - // particularly important, because in that case reporting errors via - // `CommandEncoder::finish` is not possible. - return Err(err.clone()); + if let Err(RenderPassError { inner, scope: _ }) = &base { + if let RenderPassErrorInner::EncoderState( + err @ (EncoderStateError::Locked | EncoderStateError::Ended), + ) = inner.as_ref() + { + // Most encoding errors are detected and raised within `finish()`. + // + // However, we raise a validation error here if the pass was opened + // within another pass, or on a finished encoder. The latter is + // particularly important, because in that case reporting errors via + // `CommandEncoder::finish` is not possible. + return Err(err.clone()); + } } cmd_buf_data.push_with(|| -> Result<_, RenderPassError> { @@ -2294,21 +2291,19 @@ impl Global { let base = pass.base.take(); - if let Err(RenderPassError { - inner: - RenderPassErrorInner::EncoderState( - err @ (EncoderStateError::Locked | EncoderStateError::Ended), - ), - scope: _, - }) = base - { - // Most encoding errors are detected and raised within `finish()`. - // - // However, we raise a validation error here if the pass was opened - // within another pass, or on a finished encoder. The latter is - // particularly important, because in that case reporting errors via - // `CommandEncoder::finish` is not possible. - return Err(err.clone()); + if let Err(RenderPassError { inner, scope: _ }) = &base { + if let RenderPassErrorInner::EncoderState( + err @ (EncoderStateError::Locked | EncoderStateError::Ended), + ) = inner.as_ref() + { + // Most encoding errors are detected and raised within `finish()`. + // + // However, we raise a validation error here if the pass was opened + // within another pass, or on a finished encoder. The latter is + // particularly important, because in that case reporting errors via + // `CommandEncoder::finish` is not possible. + return Err(err.clone()); + } } cmd_buf_data.push_with(|| -> Result<_, RenderPassError> { diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 6fd429f66..56bb3bee1 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -2761,7 +2761,7 @@ impl Device { pipeline::CreateShaderModuleError::Validation(naga::error::ShaderError { source, label: desc.label.as_ref().map(|l| l.to_string()), - inner: Box::new(inner), + inner, }) })?; diff --git a/wgpu-core/src/indirect_validation/dispatch.rs b/wgpu-core/src/indirect_validation/dispatch.rs index 06002e3d5..da87c4b4d 100644 --- a/wgpu-core/src/indirect_validation/dispatch.rs +++ b/wgpu-core/src/indirect_validation/dispatch.rs @@ -102,7 +102,7 @@ impl Dispatch { CreateShaderModuleError::Validation(naga::error::ShaderError { source: src, label: None, - inner: Box::new(inner), + inner, }) })?; let hal_shader = hal::ShaderInput::Naga(hal::NagaShader { diff --git a/wgpu-core/src/indirect_validation/draw.rs b/wgpu-core/src/indirect_validation/draw.rs index df22818df..550d322b4 100644 --- a/wgpu-core/src/indirect_validation/draw.rs +++ b/wgpu-core/src/indirect_validation/draw.rs @@ -547,7 +547,7 @@ fn create_validation_module( CreateShaderModuleError::Validation(naga::error::ShaderError { source: src.to_string(), label: None, - inner: Box::new(inner), + inner, }) })?; let hal_shader = hal::ShaderInput::Naga(hal::NagaShader { diff --git a/wgpu-core/src/timestamp_normalization/mod.rs b/wgpu-core/src/timestamp_normalization/mod.rs index 34be348b5..d2ac8c520 100644 --- a/wgpu-core/src/timestamp_normalization/mod.rs +++ b/wgpu-core/src/timestamp_normalization/mod.rs @@ -160,7 +160,7 @@ impl TimestampNormalizer { TimestampNormalizerInitError::ValidateWgsl(naga::error::ShaderError { source: preprocessed_src.clone(), label: None, - inner: Box::new(inner), + inner, }) })?; let hal_shader = hal::ShaderInput::Naga(hal::NagaShader { diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index 8fe0d5fba..ac6d88282 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -2007,7 +2007,7 @@ impl dispatch::DeviceInterface for WebDevice { crate::CompilationInfo::from(naga::error::ShaderError { source: source.to_string(), label: desc.label.map(|s| s.to_string()), - inner: Box::new(err), + inner: err, }) })?;