1mod analyzer;
6mod compose;
7mod expression;
8mod function;
9mod handles;
10pub(crate) mod immediates;
11mod interface;
12mod r#type;
13
14use alloc::{boxed::Box, string::String, vec, vec::Vec};
15use core::ops;
16
17use bit_set::BitSet;
18
19use crate::{
20 arena::{Handle, HandleSet},
21 proc::{ExpressionKindTracker, LayoutError, Layouter, TypeResolution},
22 FastHashSet,
23};
24
25use crate::span::{AddSpan as _, WithSpan};
29pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements};
30pub use compose::ComposeError;
31pub use expression::{check_literal_value, LiteralError};
32pub use expression::{ConstExpressionError, ExpressionError};
33pub use function::{CallError, FunctionError, LocalVariableError, SubgroupError};
34pub use immediates::{ImmediateSlots, ImmediateSlotsOverflowError, ImmediateUsage};
35pub use interface::{EntryPointError, GlobalVariableError, VaryingError};
36pub use r#type::{Disalignment, ImmediateError, TypeError, TypeFlags, WidthError};
37
38use self::handles::InvalidHandleError;
39
40pub const MAX_TYPE_SIZE: u32 = i32::MAX as u32;
42
43bitflags::bitflags! {
44 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
58 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
59 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
60 pub struct ValidationFlags: u8 {
61 const EXPRESSIONS = 0x1;
63 const BLOCKS = 0x2;
65 const CONTROL_FLOW_UNIFORMITY = 0x4;
67 const STRUCT_LAYOUTS = 0x8;
69 const CONSTANTS = 0x10;
71 const BINDINGS = 0x20;
73 }
74}
75
76impl Default for ValidationFlags {
77 fn default() -> Self {
78 Self::all()
79 }
80}
81
82bitflags::bitflags! {
83 #[must_use]
85 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
86 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
87 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
88 pub struct Capabilities: u64 {
89 const IMMEDIATES = 1 << 0;
93 const FLOAT64 = 1 << 1;
95 const PRIMITIVE_INDEX = 1 << 2;
99 const TEXTURE_AND_SAMPLER_BINDING_ARRAY = 1 << 3;
101 const BUFFER_BINDING_ARRAY = 1 << 4;
103 const STORAGE_TEXTURE_BINDING_ARRAY = 1 << 5;
105 const STORAGE_BUFFER_BINDING_ARRAY = 1 << 6;
107 const CLIP_DISTANCES = 1 << 7;
111 const CULL_DISTANCE = 1 << 8;
115 const STORAGE_TEXTURE_16BIT_NORM_FORMATS = 1 << 9;
117 const MULTIVIEW = 1 << 10;
121 const EARLY_DEPTH_TEST = 1 << 11;
123 const MULTISAMPLED_SHADING = 1 << 12;
128 const RAY_QUERY = 1 << 13;
130 const DUAL_SOURCE_BLENDING = 1 << 14;
132 const CUBE_ARRAY_TEXTURES = 1 << 15;
134 const SHADER_INT64 = 1 << 16;
136 const SUBGROUP = 1 << 17;
147 const SUBGROUP_BARRIER = 1 << 18;
151 const SUBGROUP_VERTEX_STAGE = 1 << 19;
157 const SHADER_INT64_ATOMIC_MIN_MAX = 1 << 20;
167 const SHADER_INT64_ATOMIC_ALL_OPS = 1 << 21;
169 const SHADER_FLOAT32_ATOMIC = 1 << 22;
178 const TEXTURE_ATOMIC = 1 << 23;
180 const TEXTURE_INT64_ATOMIC = 1 << 24;
182 const RAY_HIT_VERTEX_POSITION = 1 << 25;
184 const SHADER_FLOAT16 = 1 << 26;
186 const TEXTURE_EXTERNAL = 1 << 27;
188 const SHADER_BARYCENTRICS = 1 << 29;
190 const MESH_SHADER = 1 << 30;
192 const MESH_SHADER_POINT_TOPOLOGY = 1 << 31;
194 const TEXTURE_AND_SAMPLER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 32;
196 const BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 33;
198 const STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 34;
200 const STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 35;
202 const COOPERATIVE_MATRIX = 1 << 36;
204 const PER_VERTEX = 1 << 37;
206 const RAY_TRACING_PIPELINE = 1 << 38;
208 const DRAW_INDEX = 1 << 39;
210 const ACCELERATION_STRUCTURE_BINDING_ARRAY = 1 << 40;
212 const MEMORY_DECORATION_COHERENT = 1 << 41;
214 const MEMORY_DECORATION_VOLATILE = 1 << 42;
216 const SHADER_INT16 = 1 << 43;
218 const LINEAR_INTERPOLATION = 1 << 44;
224 const DEBUG_PRINTF = 1 << 45;
226 const RAY_TRACING_INVOCATION_REORDER = 1 << 46;
232
233 }
235}
236
237impl Capabilities {
238 #[cfg(feature = "wgsl-in")]
242 #[doc(hidden)]
243 pub const fn extension(&self) -> Option<crate::front::wgsl::ImplementedEnableExtension> {
244 use crate::front::wgsl::ImplementedEnableExtension as Ext;
245 match *self {
246 Self::DUAL_SOURCE_BLENDING => Some(Ext::DualSourceBlending),
247 Self::SHADER_FLOAT16 => Some(Ext::F16),
249 Self::FLOAT64 => Some(Ext::WgpuF64),
250 Self::SHADER_INT16 => Some(Ext::WgpuInt16),
251 Self::CLIP_DISTANCES => Some(Ext::ClipDistances),
252 Self::MESH_SHADER => Some(Ext::WgpuMeshShader),
253 Self::RAY_QUERY => Some(Ext::WgpuRayQuery),
254 Self::RAY_HIT_VERTEX_POSITION => Some(Ext::WgpuRayQueryVertexReturn),
255 Self::COOPERATIVE_MATRIX => Some(Ext::WgpuCooperativeMatrix),
256 Self::RAY_TRACING_PIPELINE => Some(Ext::WgpuRayTracingPipeline),
257 Self::RAY_TRACING_INVOCATION_REORDER => Some(Ext::WgpuRayTracingInvocationReorder),
258 Self::PER_VERTEX => Some(Ext::WgpuPerVertex),
259 Self::BUFFER_BINDING_ARRAY
260 | Self::BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING
261 | Self::STORAGE_BUFFER_BINDING_ARRAY
262 | Self::STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING
263 | Self::STORAGE_TEXTURE_BINDING_ARRAY
264 | Self::STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING
265 | Self::TEXTURE_AND_SAMPLER_BINDING_ARRAY
266 | Self::TEXTURE_AND_SAMPLER_BINDING_ARRAY_NON_UNIFORM_INDEXING => {
267 Some(Ext::WgpuBindingArray)
268 }
269 Self::DEBUG_PRINTF => Some(Ext::WgpuDebugPrintf),
270 _ => None,
271 }
272 }
273}
274
275impl Default for Capabilities {
276 fn default() -> Self {
277 Self::MULTISAMPLED_SHADING | Self::CUBE_ARRAY_TEXTURES
278 }
279}
280
281bitflags::bitflags! {
282 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
284 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
285 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
286 pub struct SubgroupOperationSet: u8 {
287 const BASIC = 1 << 0;
293 const VOTE = 1 << 1;
295 const ARITHMETIC = 1 << 2;
297 const BALLOT = 1 << 3;
299 const SHUFFLE = 1 << 4;
301 const SHUFFLE_RELATIVE = 1 << 5;
303 const QUAD_FRAGMENT_COMPUTE = 1 << 7;
308 }
311}
312
313impl super::SubgroupOperation {
314 const fn required_operations(&self) -> SubgroupOperationSet {
315 use SubgroupOperationSet as S;
316 match *self {
317 Self::All | Self::Any => S::VOTE,
318 Self::Add | Self::Mul | Self::Min | Self::Max | Self::And | Self::Or | Self::Xor => {
319 S::ARITHMETIC
320 }
321 }
322 }
323}
324
325impl super::GatherMode {
326 const fn required_operations(&self) -> SubgroupOperationSet {
327 use SubgroupOperationSet as S;
328 match *self {
329 Self::BroadcastFirst | Self::Broadcast(_) => S::BALLOT,
330 Self::Shuffle(_) | Self::ShuffleXor(_) => S::SHUFFLE,
331 Self::ShuffleUp(_) | Self::ShuffleDown(_) => S::SHUFFLE_RELATIVE,
332 Self::QuadBroadcast(_) | Self::QuadSwap(_) => S::QUAD_FRAGMENT_COMPUTE,
333 }
334 }
335}
336
337bitflags::bitflags! {
338 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
340 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
341 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
342 pub struct ShaderStages: u16 {
343 const VERTEX = 0x1;
344 const FRAGMENT = 0x2;
345 const COMPUTE = 0x4;
346 const MESH = 0x8;
347 const TASK = 0x10;
348 const RAY_GENERATION = 0x20;
349 const ANY_HIT = 0x40;
350 const CLOSEST_HIT = 0x80;
351 const MISS = 0x100;
352 const COMPUTE_LIKE = Self::COMPUTE.bits() | Self::TASK.bits() | Self::MESH.bits();
353 }
354}
355
356#[derive(Debug, Clone, Default)]
357#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
358#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
359pub struct ModuleInfo {
360 type_flags: Vec<TypeFlags>,
361 functions: Vec<FunctionInfo>,
362 entry_points: Vec<FunctionInfo>,
363 const_expression_types: Box<[TypeResolution]>,
364}
365
366impl ops::Index<Handle<crate::Type>> for ModuleInfo {
367 type Output = TypeFlags;
368 fn index(&self, handle: Handle<crate::Type>) -> &Self::Output {
369 &self.type_flags[handle.index()]
370 }
371}
372
373impl ops::Index<Handle<crate::Function>> for ModuleInfo {
374 type Output = FunctionInfo;
375 fn index(&self, handle: Handle<crate::Function>) -> &Self::Output {
376 &self.functions[handle.index()]
377 }
378}
379
380impl ops::Index<Handle<crate::Expression>> for ModuleInfo {
381 type Output = TypeResolution;
382 fn index(&self, handle: Handle<crate::Expression>) -> &Self::Output {
383 &self.const_expression_types[handle.index()]
384 }
385}
386
387#[derive(Debug)]
388pub struct Validator {
389 flags: ValidationFlags,
390 capabilities: Capabilities,
391 subgroup_stages: ShaderStages,
392 subgroup_operations: SubgroupOperationSet,
393 types: Vec<r#type::TypeInfo>,
394 layouter: Layouter,
395 location_mask: BitSet,
396 ep_resource_bindings: FastHashSet<crate::ResourceBinding>,
397 switch_values: FastHashSet<crate::SwitchValue>,
398 valid_expression_list: Vec<Handle<crate::Expression>>,
399 valid_expression_set: HandleSet<crate::Expression>,
400 override_ids: FastHashSet<u16>,
401
402 overrides_resolved: bool,
405
406 needs_visit: HandleSet<crate::Expression>,
425
426 trace_rays_vertex_return: TraceRayVertexReturnState,
430
431 trace_rays_payload_type: Option<Handle<crate::Type>>,
434}
435
436#[derive(Debug)]
437enum TraceRayVertexReturnState {
438 NoTraceRays,
440 #[expect(
444 unused,
445 reason = "Don't yet have vertex return builtins to return this error for."
446 )]
447 NoVertexReturn(crate::Span),
448 VertexReturn,
452}
453
454#[derive(Clone, Debug, thiserror::Error)]
455#[cfg_attr(test, derive(PartialEq))]
456pub enum ConstantError {
457 #[error("Initializer must be a const-expression")]
458 InitializerExprType,
459 #[error("The type doesn't match the constant")]
460 InvalidType,
461 #[error("The type is not constructible")]
462 NonConstructibleType,
463}
464
465#[derive(Clone, Debug, thiserror::Error)]
466#[cfg_attr(test, derive(PartialEq))]
467pub enum OverrideError {
468 #[error("Override name and ID are missing")]
469 MissingNameAndID,
470 #[error("Override ID must be unique")]
471 DuplicateID,
472 #[error("Initializer must be a const-expression or override-expression")]
473 InitializerExprType,
474 #[error("The type doesn't match the override")]
475 InvalidType,
476 #[error("The type is not constructible")]
477 NonConstructibleType,
478 #[error("The type is not a scalar")]
479 TypeNotScalar,
480 #[error("Override declarations are not allowed")]
481 NotAllowed,
482 #[error("Override is uninitialized")]
483 UninitializedOverride,
484 #[error("Constant expression {handle:?} is invalid")]
485 ConstExpression {
486 handle: Handle<crate::Expression>,
487 source: ConstExpressionError,
488 },
489}
490
491#[derive(Clone, Debug, thiserror::Error)]
492#[cfg_attr(test, derive(PartialEq))]
493pub enum ValidationError {
494 #[error(transparent)]
495 InvalidHandle(#[from] InvalidHandleError),
496 #[error(transparent)]
497 Layouter(#[from] LayoutError),
498 #[error("Type {handle:?} '{name}' is invalid")]
499 Type {
500 handle: Handle<crate::Type>,
501 name: String,
502 source: TypeError,
503 },
504 #[error("Constant expression {handle:?} is invalid")]
505 ConstExpression {
506 handle: Handle<crate::Expression>,
507 source: ConstExpressionError,
508 },
509 #[error("Array size expression {handle:?} is not strictly positive")]
510 ArraySizeError { handle: Handle<crate::Expression> },
511 #[error("Constant {handle:?} '{name}' is invalid")]
512 Constant {
513 handle: Handle<crate::Constant>,
514 name: String,
515 source: ConstantError,
516 },
517 #[error("Override {handle:?} '{name}' is invalid")]
518 Override {
519 handle: Handle<crate::Override>,
520 name: String,
521 source: OverrideError,
522 },
523 #[error("Global variable {handle:?} '{name}' is invalid")]
524 GlobalVariable {
525 handle: Handle<crate::GlobalVariable>,
526 name: String,
527 source: GlobalVariableError,
528 },
529 #[error("Function {handle:?} '{name}' is invalid")]
530 Function {
531 handle: Handle<crate::Function>,
532 name: String,
533 source: FunctionError,
534 },
535 #[error("Entry point {name} at {stage:?} is invalid")]
536 EntryPoint {
537 stage: crate::ShaderStage,
538 name: String,
539 source: EntryPointError,
540 },
541 #[error("Module is corrupted")]
542 Corrupted,
543}
544
545impl crate::TypeInner {
546 const fn is_sized(&self) -> bool {
547 match *self {
548 Self::Scalar { .. }
549 | Self::Vector { .. }
550 | Self::Matrix { .. }
551 | Self::CooperativeMatrix { .. }
552 | Self::Array {
553 size: crate::ArraySize::Constant(_),
554 ..
555 }
556 | Self::Atomic { .. }
557 | Self::Pointer { .. }
558 | Self::ValuePointer { .. }
559 | Self::Struct { .. } => true,
560 Self::Array { .. }
561 | Self::Image { .. }
562 | Self::Sampler { .. }
563 | Self::AccelerationStructure { .. }
564 | Self::RayQuery { .. }
565 | Self::HitObject
566 | Self::BindingArray { .. } => false,
567 }
568 }
569
570 const fn image_storage_coordinates(&self) -> Option<crate::ImageDimension> {
572 match *self {
573 Self::Scalar(crate::Scalar {
574 kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
575 ..
576 }) => Some(crate::ImageDimension::D1),
577 Self::Vector {
578 size: crate::VectorSize::Bi,
579 scalar:
580 crate::Scalar {
581 kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
582 ..
583 },
584 } => Some(crate::ImageDimension::D2),
585 Self::Vector {
586 size: crate::VectorSize::Tri,
587 scalar:
588 crate::Scalar {
589 kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
590 ..
591 },
592 } => Some(crate::ImageDimension::D3),
593 _ => None,
594 }
595 }
596}
597
598impl Validator {
599 pub fn new(flags: ValidationFlags, capabilities: Capabilities) -> Self {
613 let subgroup_operations = if capabilities.contains(Capabilities::SUBGROUP) {
614 use SubgroupOperationSet as S;
615 S::BASIC
616 | S::VOTE
617 | S::ARITHMETIC
618 | S::BALLOT
619 | S::SHUFFLE
620 | S::SHUFFLE_RELATIVE
621 | S::QUAD_FRAGMENT_COMPUTE
622 } else {
623 SubgroupOperationSet::empty()
624 };
625 let subgroup_stages = {
626 let mut stages = ShaderStages::empty();
627 if capabilities.contains(Capabilities::SUBGROUP_VERTEX_STAGE) {
628 stages |= ShaderStages::VERTEX;
629 }
630 if capabilities.contains(Capabilities::SUBGROUP) {
631 stages |= ShaderStages::FRAGMENT | ShaderStages::COMPUTE_LIKE;
632 }
633 stages
634 };
635
636 Validator {
637 flags,
638 capabilities,
639 subgroup_stages,
640 subgroup_operations,
641 types: Vec::new(),
642 layouter: Layouter::default(),
643 location_mask: BitSet::new(),
644 ep_resource_bindings: FastHashSet::default(),
645 switch_values: FastHashSet::default(),
646 valid_expression_list: Vec::new(),
647 valid_expression_set: HandleSet::new(),
648 override_ids: FastHashSet::default(),
649 overrides_resolved: false,
650 needs_visit: HandleSet::new(),
651 trace_rays_vertex_return: TraceRayVertexReturnState::NoTraceRays,
652 trace_rays_payload_type: None,
653 }
654 }
655
656 pub const fn subgroup_stages(&mut self, stages: ShaderStages) -> &mut Self {
658 self.subgroup_stages = stages;
659 self
660 }
661
662 pub const fn subgroup_operations(&mut self, operations: SubgroupOperationSet) -> &mut Self {
664 self.subgroup_operations = operations;
665 self
666 }
667
668 pub fn reset(&mut self) {
670 self.types.clear();
671 self.layouter.clear();
672 self.location_mask.make_empty();
673 self.ep_resource_bindings.clear();
674 self.switch_values.clear();
675 self.valid_expression_list.clear();
676 self.valid_expression_set.clear();
677 self.override_ids.clear();
678 self.trace_rays_vertex_return = TraceRayVertexReturnState::NoTraceRays;
679 self.trace_rays_payload_type = None;
680 }
681
682 fn validate_constant(
683 &self,
684 handle: Handle<crate::Constant>,
685 gctx: crate::proc::GlobalCtx,
686 mod_info: &ModuleInfo,
687 global_expr_kind: &ExpressionKindTracker,
688 ) -> Result<(), ConstantError> {
689 let con = &gctx.constants[handle];
690
691 let type_info = &self.types[con.ty.index()];
692 if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
693 return Err(ConstantError::NonConstructibleType);
694 }
695
696 if !global_expr_kind.is_const(con.init) {
697 return Err(ConstantError::InitializerExprType);
698 }
699
700 if !gctx.compare_types(&TypeResolution::Handle(con.ty), &mod_info[con.init]) {
701 return Err(ConstantError::InvalidType);
702 }
703
704 Ok(())
705 }
706
707 fn validate_override(
708 &mut self,
709 handle: Handle<crate::Override>,
710 gctx: crate::proc::GlobalCtx,
711 mod_info: &ModuleInfo,
712 ) -> Result<(), OverrideError> {
713 let o = &gctx.overrides[handle];
714
715 if let Some(id) = o.id {
716 if !self.override_ids.insert(id) {
717 return Err(OverrideError::DuplicateID);
718 }
719 }
720
721 let type_info = &self.types[o.ty.index()];
722 if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
723 return Err(OverrideError::NonConstructibleType);
724 }
725
726 match gctx.types[o.ty].inner {
727 crate::TypeInner::Scalar(
728 crate::Scalar::BOOL
729 | crate::Scalar::I16
730 | crate::Scalar::U16
731 | crate::Scalar::I32
732 | crate::Scalar::U32
733 | crate::Scalar::F16
734 | crate::Scalar::F32
735 | crate::Scalar::F64,
736 ) => {}
737 _ => return Err(OverrideError::TypeNotScalar),
738 }
739
740 if let Some(init) = o.init {
741 if !gctx.compare_types(&TypeResolution::Handle(o.ty), &mod_info[init]) {
742 return Err(OverrideError::InvalidType);
743 }
744 } else if self.overrides_resolved {
745 return Err(OverrideError::UninitializedOverride);
746 }
747
748 Ok(())
749 }
750
751 pub fn validate(
753 &mut self,
754 module: &crate::Module,
755 ) -> Result<ModuleInfo, Box<WithSpan<ValidationError>>> {
756 self.overrides_resolved = false;
757 self.validate_impl(module)
758 }
759
760 pub fn validate_resolved_overrides(
768 &mut self,
769 module: &crate::Module,
770 ) -> Result<ModuleInfo, Box<WithSpan<ValidationError>>> {
771 self.overrides_resolved = true;
772 self.validate_impl(module)
773 }
774
775 fn validate_impl(
776 &mut self,
777 module: &crate::Module,
778 ) -> Result<ModuleInfo, Box<WithSpan<ValidationError>>> {
779 self.reset();
780 self.reset_types(module.types.len());
781
782 Self::validate_module_handles(module).map_err(|e| Box::new((*e).with_span()))?;
783
784 self.layouter.update(module.to_ctx()).map_err(|e| {
785 let handle = e.ty;
786 ValidationError::from(e).with_span_handle(handle, &module.types)
787 })?;
788
789 let placeholder = TypeResolution::Value(crate::TypeInner::Scalar(crate::Scalar {
791 kind: crate::ScalarKind::Bool,
792 width: 0,
793 }));
794
795 let mut mod_info = ModuleInfo {
796 type_flags: Vec::with_capacity(module.types.len()),
797 functions: Vec::with_capacity(module.functions.len()),
798 entry_points: Vec::with_capacity(module.entry_points.len()),
799 const_expression_types: vec![placeholder; module.global_expressions.len()]
800 .into_boxed_slice(),
801 };
802
803 for (handle, ty) in module.types.iter() {
804 let ty_info = self
805 .validate_type(handle, module.to_ctx())
806 .map_err(|source| {
807 ValidationError::Type {
808 handle,
809 name: ty.name.clone().unwrap_or_default(),
810 source,
811 }
812 .with_span_handle(handle, &module.types)
813 })?;
814 debug_assert!(
815 ty_info.flags.contains(TypeFlags::CONSTRUCTIBLE)
816 == module.types[handle].inner.is_constructible(&module.types)
817 );
818 mod_info.type_flags.push(ty_info.flags);
819 self.types[handle.index()] = ty_info;
820 }
821
822 {
823 let t = crate::Arena::new();
824 let resolve_context = crate::proc::ResolveContext::with_locals(module, &t, &[]);
825 for (handle, _) in module.global_expressions.iter() {
826 mod_info
827 .process_const_expression(handle, &resolve_context, module.to_ctx())
828 .map_err(|source| {
829 ValidationError::ConstExpression { handle, source }
830 .with_span_handle(handle, &module.global_expressions)
831 })?
832 }
833 }
834
835 let global_expr_kind = ExpressionKindTracker::from_arena(&module.global_expressions);
836
837 if self.flags.contains(ValidationFlags::CONSTANTS) {
838 for (handle, _) in module.global_expressions.iter() {
839 self.validate_const_expression(
840 handle,
841 module.to_ctx(),
842 &mod_info,
843 &global_expr_kind,
844 )
845 .map_err(|source| {
846 ValidationError::ConstExpression { handle, source }
847 .with_span_handle(handle, &module.global_expressions)
848 })?
849 }
850
851 for (handle, constant) in module.constants.iter() {
852 self.validate_constant(handle, module.to_ctx(), &mod_info, &global_expr_kind)
853 .map_err(|source| {
854 ValidationError::Constant {
855 handle,
856 name: constant.name.clone().unwrap_or_default(),
857 source,
858 }
859 .with_span_handle(handle, &module.constants)
860 })?
861 }
862
863 for (handle, r#override) in module.overrides.iter() {
864 self.validate_override(handle, module.to_ctx(), &mod_info)
865 .map_err(|source| {
866 ValidationError::Override {
867 handle,
868 name: r#override.name.clone().unwrap_or_default(),
869 source,
870 }
871 .with_span_handle(handle, &module.overrides)
872 })?;
873 }
874 }
875
876 for (var_handle, var) in module.global_variables.iter() {
877 self.validate_global_var(var, module.to_ctx(), &mod_info, &global_expr_kind)
878 .map_err(|source| {
879 ValidationError::GlobalVariable {
880 handle: var_handle,
881 name: var.name.clone().unwrap_or_default(),
882 source,
883 }
884 .with_span_handle(var_handle, &module.global_variables)
885 })?;
886 }
887
888 for (handle, fun) in module.functions.iter() {
889 match self.validate_function(fun, module, &mod_info, false) {
890 Ok(info) => mod_info.functions.push(info),
891 Err(error) => {
892 return Err(Box::new(error.and_then(|source| {
893 ValidationError::Function {
894 handle,
895 name: fun.name.clone().unwrap_or_default(),
896 source,
897 }
898 .with_span_handle(handle, &module.functions)
899 })))
900 }
901 }
902 }
903
904 let mut ep_map = FastHashSet::default();
905 for ep in module.entry_points.iter() {
906 if !ep_map.insert((ep.stage, &ep.name)) {
907 return Err(Box::new(
908 ValidationError::EntryPoint {
909 stage: ep.stage,
910 name: ep.name.clone(),
911 source: EntryPointError::Conflict,
912 }
913 .with_span(),
914 )); }
916
917 match self.validate_entry_point(ep, module, &mod_info) {
918 Ok(info) => {
919 mod_info.entry_points.push(info);
920 }
921 Err(error) => {
922 return Err(Box::new(error.and_then(|source| {
923 ValidationError::EntryPoint {
924 stage: ep.stage,
925 name: ep.name.clone(),
926 source,
927 }
928 .with_span()
929 })));
930 }
931 }
932 }
933
934 Ok(mod_info)
935 }
936}
937
938fn validate_atomic_compare_exchange_struct(
939 types: &crate::UniqueArena<crate::Type>,
940 members: &[crate::StructMember],
941 scalar_predicate: impl FnOnce(&crate::TypeInner) -> bool,
942) -> bool {
943 members.len() == 2
944 && members[0].name.as_deref() == Some("old_value")
945 && scalar_predicate(&types[members[0].ty].inner)
946 && members[1].name.as_deref() == Some("exchanged")
947 && types[members[1].ty].inner == crate::TypeInner::Scalar(crate::Scalar::BOOL)
948}