1use alloc::{format, string::String};
2
3use super::{
4 analyzer::{UniformityDisruptor, UniformityRequirements},
5 ExpressionError, FunctionInfo, ModuleInfo,
6};
7use crate::arena::{Arena, UniqueArena};
8use crate::arena::{Handle, HandleSet};
9use crate::proc::TypeResolution;
10use crate::span::WithSpan;
11use crate::span::{AddSpan as _, MapErrWithSpan as _};
12
13#[derive(Clone, Debug, thiserror::Error)]
14#[cfg_attr(test, derive(PartialEq))]
15pub enum CallError {
16 #[error("Argument {index} expression is invalid")]
17 Argument {
18 index: usize,
19 source: ExpressionError,
20 },
21 #[error("Result expression {0:?} has already been introduced earlier")]
22 ResultAlreadyInScope(Handle<crate::Expression>),
23 #[error("Result expression {0:?} is populated by multiple `Call` statements")]
24 ResultAlreadyPopulated(Handle<crate::Expression>),
25 #[error("Requires {required} arguments, but {seen} are provided")]
26 ArgumentCount { required: usize, seen: usize },
27 #[error("Argument {index} value {seen_expression:?} doesn't match the type {required:?}")]
28 ArgumentType {
29 index: usize,
30 required: Handle<crate::Type>,
31 seen_expression: Handle<crate::Expression>,
32 },
33 #[error("The emitted expression doesn't match the call")]
34 ExpressionMismatch(Option<Handle<crate::Expression>>),
35}
36
37#[derive(Clone, Debug, thiserror::Error)]
38#[cfg_attr(test, derive(PartialEq))]
39pub enum AtomicError {
40 #[error("Pointer {0:?} to atomic is invalid.")]
41 InvalidPointer(Handle<crate::Expression>),
42 #[error("Address space {0:?} is not supported.")]
43 InvalidAddressSpace(crate::AddressSpace),
44 #[error("Operand {0:?} has invalid type.")]
45 InvalidOperand(Handle<crate::Expression>),
46 #[error("Operator {0:?} is not supported.")]
47 InvalidOperator(crate::AtomicFunction),
48 #[error("Result expression {0:?} is not an `AtomicResult` expression")]
49 InvalidResultExpression(Handle<crate::Expression>),
50 #[error("Result expression {0:?} is marked as an `exchange`")]
51 ResultExpressionExchange(Handle<crate::Expression>),
52 #[error("Result expression {0:?} is not marked as an `exchange`")]
53 ResultExpressionNotExchange(Handle<crate::Expression>),
54 #[error("Result type for {0:?} doesn't match the statement")]
55 ResultTypeMismatch(Handle<crate::Expression>),
56 #[error("Exchange operations must return a value")]
57 MissingReturnValue,
58 #[error("Capability {0:?} is required")]
59 MissingCapability(super::Capabilities),
60 #[error("Result expression {0:?} is populated by multiple `Atomic` statements")]
61 ResultAlreadyPopulated(Handle<crate::Expression>),
62}
63
64#[derive(Clone, Debug, thiserror::Error)]
65#[cfg_attr(test, derive(PartialEq))]
66pub enum SubgroupError {
67 #[error("Operand {0:?} has invalid type.")]
68 InvalidOperand(Handle<crate::Expression>),
69 #[error("Result type for {0:?} doesn't match the statement")]
70 ResultTypeMismatch(Handle<crate::Expression>),
71 #[error("Support for subgroup operation {0:?} is required")]
72 UnsupportedOperation(super::SubgroupOperationSet),
73 #[error("Unknown operation")]
74 UnknownOperation,
75 #[error("Invocation ID must be a const-expression")]
76 InvalidInvocationIdExprType(Handle<crate::Expression>),
77}
78
79#[derive(Clone, Debug, thiserror::Error)]
80#[cfg_attr(test, derive(PartialEq))]
81pub enum LocalVariableError {
82 #[error("Local variable has a type {0:?} that can't be stored in a local variable.")]
83 InvalidType(Handle<crate::Type>),
84 #[error("Initializer doesn't match the variable type")]
85 InitializerType,
86 #[error("Initializer is not a const or override expression")]
87 NonConstOrOverrideInitializer,
88 #[error("Local variable has a type `ray_query` and so cannot be initialized.")]
89 RayQueryWithInitializeExpression,
90}
91
92#[derive(Clone, Debug, thiserror::Error)]
93#[cfg_attr(test, derive(PartialEq))]
94pub enum FunctionError {
95 #[error("Expression {handle:?} is invalid")]
96 Expression {
97 handle: Handle<crate::Expression>,
98 source: ExpressionError,
99 },
100 #[error("Expression {0:?} can't be introduced - it's already in scope")]
101 ExpressionAlreadyInScope(Handle<crate::Expression>),
102 #[error("Local variable {handle:?} '{name}' is invalid")]
103 LocalVariable {
104 handle: Handle<crate::LocalVariable>,
105 name: String,
106 source: LocalVariableError,
107 },
108 #[error("Argument '{name}' at index {index} has a type that can't be passed into functions.")]
109 InvalidArgumentType { index: usize, name: String },
110 #[error("The function's given return type cannot be returned from functions")]
111 NonConstructibleReturnType,
112 #[error("Argument '{name}' at index {index} is a pointer of space {space:?}, which can't be passed into functions.")]
113 InvalidArgumentPointerSpace {
114 index: usize,
115 name: String,
116 space: crate::AddressSpace,
117 },
118 #[error("The `break` is used outside of a `loop` or `switch` context")]
119 BreakOutsideOfLoopOrSwitch,
120 #[error("The `continue` is used outside of a `loop` context")]
121 ContinueOutsideOfLoop,
122 #[error("The `return` is called within a `continuing` block")]
123 InvalidReturnSpot,
124 #[error("The `return` expression {expression:?} does not match the declared return type {expected_ty:?}")]
125 InvalidReturnType {
126 expression: Option<Handle<crate::Expression>>,
127 expected_ty: Option<Handle<crate::Type>>,
128 },
129 #[error("The `if` condition {0:?} is not a boolean scalar")]
130 InvalidIfType(Handle<crate::Expression>),
131 #[error("The `switch` value {0:?} is not an integer scalar")]
132 InvalidSwitchType(Handle<crate::Expression>),
133 #[error("Multiple `switch` cases for {0:?} are present")]
134 ConflictingSwitchCase(crate::SwitchValue),
135 #[error("The `switch` contains cases with conflicting types")]
136 ConflictingCaseType,
137 #[error("The `switch` is missing a `default` case")]
138 MissingDefaultCase,
139 #[error("Multiple `default` cases are present")]
140 MultipleDefaultCases,
141 #[error("The last `switch` case contains a `fallthrough`")]
142 LastCaseFallTrough,
143 #[error("The pointer {0:?} doesn't relate to a valid destination for a store")]
144 InvalidStorePointer(Handle<crate::Expression>),
145 #[error("Image store texture parameter type mismatch")]
146 InvalidStoreTexture {
147 actual: Handle<crate::Expression>,
148 actual_ty: crate::TypeInner,
149 },
150 #[error("Image store value parameter type mismatch")]
151 InvalidStoreValue {
152 actual: Handle<crate::Expression>,
153 actual_ty: crate::TypeInner,
154 expected_ty: crate::TypeInner,
155 },
156 #[error("The type of {value:?} doesn't match the type stored in {pointer:?}")]
157 InvalidStoreTypes {
158 pointer: Handle<crate::Expression>,
159 value: Handle<crate::Expression>,
160 },
161 #[error("Image store parameters are invalid")]
162 InvalidImageStore(#[source] ExpressionError),
163 #[error("Image atomic parameters are invalid")]
164 InvalidImageAtomic(#[source] ExpressionError),
165 #[error("Image atomic function is invalid")]
166 InvalidImageAtomicFunction(crate::AtomicFunction),
167 #[error("Image atomic value is invalid")]
168 InvalidImageAtomicValue(Handle<crate::Expression>),
169 #[error("Call to {function:?} is invalid")]
170 InvalidCall {
171 function: Handle<crate::Function>,
172 #[source]
173 error: CallError,
174 },
175 #[error("Atomic operation is invalid")]
176 InvalidAtomic(#[from] AtomicError),
177 #[error("Ray Query {0:?} is not a local variable")]
178 InvalidRayQueryExpression(Handle<crate::Expression>),
179 #[error("Acceleration structure {0:?} is not a matching expression")]
180 InvalidAccelerationStructure(Handle<crate::Expression>),
181 #[error(
182 "Acceleration structure {0:?} is missing flag vertex_return while Ray Query {1:?} does"
183 )]
184 MissingAccelerationStructureVertexReturn(Handle<crate::Expression>, Handle<crate::Expression>),
185 #[error("Ray Query {0:?} is missing flag vertex_return")]
186 MissingRayQueryVertexReturn(Handle<crate::Expression>),
187 #[error("Ray descriptor {0:?} is not a matching expression")]
188 InvalidRayDescriptor(Handle<crate::Expression>),
189 #[error("Ray Query {0:?} does not have a matching type")]
190 InvalidRayQueryType(Handle<crate::Type>),
191 #[error("Hit distance {0:?} must be an f32")]
192 InvalidHitDistanceType(Handle<crate::Expression>),
193 #[error("Shader requires capability {0:?}")]
194 MissingCapability(super::Capabilities),
195 #[error(
196 "Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}"
197 )]
198 NonUniformControlFlow(
199 UniformityRequirements,
200 Handle<crate::Expression>,
201 UniformityDisruptor,
202 ),
203 #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their arguments: \"{name}\" has attributes")]
204 PipelineInputRegularFunction { name: String },
205 #[error("Functions that are not entry points cannot have `@location` or `@builtin` attributes on their return value types")]
206 PipelineOutputRegularFunction,
207 #[error("Required uniformity for WorkGroupUniformLoad is not fulfilled because of {0:?}")]
208 NonUniformWorkgroupUniformLoad(UniformityDisruptor),
210 #[error("The expression {0:?} for a WorkGroupUniformLoad isn't a WorkgroupUniformLoadResult")]
212 WorkgroupUniformLoadExpressionMismatch(Handle<crate::Expression>),
213 #[error("The expression {0:?} is not valid as a WorkGroupUniformLoad argument. It should be a Pointer in Workgroup address space")]
214 WorkgroupUniformLoadInvalidPointer(Handle<crate::Expression>),
215 #[error("Subgroup operation is invalid")]
216 InvalidSubgroup(#[from] SubgroupError),
217 #[error("Invalid target type for a cooperative store")]
218 InvalidCooperativeStoreTarget(Handle<crate::Expression>),
219 #[error("Cooperative load/store data pointer has invalid type")]
220 InvalidCooperativeDataPointer(Handle<crate::Expression>),
221 #[error("Emit statement should not cover \"result\" expressions like {0:?}")]
222 EmitResult(Handle<crate::Expression>),
223 #[error("Expression not visited by the appropriate statement")]
224 UnvisitedExpression(Handle<crate::Expression>),
225 #[error("Expression {0:?} in mesh shader intrinsic call should be `u32` (is the expression a signed integer?)")]
226 InvalidMeshFunctionCall(Handle<crate::Expression>),
227 #[error("Mesh output types differ from {0:?} to {1:?}")]
228 ConflictingMeshOutputTypes(Handle<crate::Expression>, Handle<crate::Expression>),
229 #[error("Task payload variables differ from {0:?} to {1:?}")]
230 ConflictingTaskPayloadVariables(Handle<crate::Expression>, Handle<crate::Expression>),
231 #[error("Mesh shader output at {0:?} is not a user-defined struct")]
232 InvalidMeshShaderOutputType(Handle<crate::Expression>),
233 #[error("The payload type passed to `traceRay` must be a pointer")]
234 InvalidPayloadType,
235 #[error("The payload type passed to `traceRay` must be a pointer with an address space of `ray_payload` or `incoming_ray_payload`, instead got {0:?}")]
236 InvalidPayloadAddressSpace(crate::AddressSpace),
237 #[error("The payload type ({0:?}) passed to `traceRay` does not match the previous one {1:?}")]
238 MismatchedPayloadType(Handle<crate::Type>, Handle<crate::Type>),
239 #[error("The payload passed to `traceRay` must be a pointer directly to a global variable")]
240 PayloadPointerNotGlobal,
241 #[error("Argument {0:?} for `debugPrintf` must be a supported scalar type")]
242 InvalidDebugPrintfArgument(Handle<crate::Expression>),
243 #[error("Tried to store to pointer {0:?} which is a ray query and so cannot be assigned to")]
244 RayQueryStore(Handle<crate::Expression>),
245}
246
247bitflags::bitflags! {
248 #[repr(transparent)]
249 #[derive(Clone, Copy)]
250 struct ControlFlowAbility: u8 {
251 const RETURN = 0x1;
253 const BREAK = 0x2;
255 const CONTINUE = 0x4;
257 }
258}
259
260struct BlockInfo {
261 stages: super::ShaderStages,
262}
263
264struct BlockContext<'a> {
265 abilities: ControlFlowAbility,
266 info: &'a FunctionInfo,
267 expressions: &'a Arena<crate::Expression>,
268 types: &'a UniqueArena<crate::Type>,
269 local_vars: &'a Arena<crate::LocalVariable>,
270 global_vars: &'a Arena<crate::GlobalVariable>,
271 functions: &'a Arena<crate::Function>,
272 special_types: &'a crate::SpecialTypes,
273 prev_infos: &'a [FunctionInfo],
274 return_type: Option<Handle<crate::Type>>,
275 local_expr_kind: &'a crate::proc::ExpressionKindTracker,
276}
277
278impl<'a> BlockContext<'a> {
279 fn new(
280 fun: &'a crate::Function,
281 module: &'a crate::Module,
282 info: &'a FunctionInfo,
283 prev_infos: &'a [FunctionInfo],
284 local_expr_kind: &'a crate::proc::ExpressionKindTracker,
285 ) -> Self {
286 Self {
287 abilities: ControlFlowAbility::RETURN,
288 info,
289 expressions: &fun.expressions,
290 types: &module.types,
291 local_vars: &fun.local_variables,
292 global_vars: &module.global_variables,
293 functions: &module.functions,
294 special_types: &module.special_types,
295 prev_infos,
296 return_type: fun.result.as_ref().map(|fr| fr.ty),
297 local_expr_kind,
298 }
299 }
300
301 const fn with_abilities(&self, abilities: ControlFlowAbility) -> Self {
302 BlockContext { abilities, ..*self }
303 }
304
305 fn get_expression(&self, handle: Handle<crate::Expression>) -> &'a crate::Expression {
306 &self.expressions[handle]
307 }
308
309 fn resolve_type_impl(
310 &self,
311 handle: Handle<crate::Expression>,
312 valid_expressions: &HandleSet<crate::Expression>,
313 ) -> Result<&TypeResolution, WithSpan<ExpressionError>> {
314 if !valid_expressions.contains(handle) {
315 Err(ExpressionError::NotInScope.with_span_handle(handle, self.expressions))
316 } else {
317 Ok(&self.info[handle].ty)
318 }
319 }
320
321 fn resolve_type(
322 &self,
323 handle: Handle<crate::Expression>,
324 valid_expressions: &HandleSet<crate::Expression>,
325 ) -> Result<&TypeResolution, WithSpan<FunctionError>> {
326 self.resolve_type_impl(handle, valid_expressions)
327 .map_err_inner(|source| FunctionError::Expression { handle, source }.with_span())
328 }
329
330 fn resolve_type_inner(
331 &self,
332 handle: Handle<crate::Expression>,
333 valid_expressions: &HandleSet<crate::Expression>,
334 ) -> Result<&crate::TypeInner, WithSpan<FunctionError>> {
335 self.resolve_type(handle, valid_expressions)
336 .map(|tr| tr.inner_with(self.types))
337 }
338
339 fn resolve_pointer_type(&self, handle: Handle<crate::Expression>) -> &crate::TypeInner {
340 self.info[handle].ty.inner_with(self.types)
341 }
342
343 fn compare_types(&self, lhs: &TypeResolution, rhs: &TypeResolution) -> bool {
344 crate::proc::compare_types(lhs, rhs, self.types)
345 }
346}
347
348impl super::Validator {
349 fn validate_call(
350 &mut self,
351 function: Handle<crate::Function>,
352 arguments: &[Handle<crate::Expression>],
353 result: Option<Handle<crate::Expression>>,
354 context: &BlockContext,
355 ) -> Result<super::ShaderStages, WithSpan<CallError>> {
356 let fun = &context.functions[function];
357 if fun.arguments.len() != arguments.len() {
358 return Err(CallError::ArgumentCount {
359 required: fun.arguments.len(),
360 seen: arguments.len(),
361 }
362 .with_span());
363 }
364 for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() {
365 let ty = context
366 .resolve_type_impl(expr, &self.valid_expression_set)
367 .map_err_inner(|source| {
368 CallError::Argument { index, source }
369 .with_span_handle(expr, context.expressions)
370 })?;
371 if !context.compare_types(&TypeResolution::Handle(arg.ty), ty) {
372 return Err(CallError::ArgumentType {
373 index,
374 required: arg.ty,
375 seen_expression: expr,
376 }
377 .with_span_handle(expr, context.expressions));
378 }
379 }
380
381 if let Some(expr) = result {
382 if self.valid_expression_set.insert(expr) {
383 self.valid_expression_list.push(expr);
384 } else {
385 return Err(CallError::ResultAlreadyInScope(expr)
386 .with_span_handle(expr, context.expressions));
387 }
388 match context.expressions[expr] {
389 crate::Expression::CallResult(callee)
390 if fun.result.is_some() && callee == function =>
391 {
392 if !self.needs_visit.remove(expr) {
393 return Err(CallError::ResultAlreadyPopulated(expr)
394 .with_span_handle(expr, context.expressions));
395 }
396 }
397 _ => {
398 return Err(CallError::ExpressionMismatch(result)
399 .with_span_handle(expr, context.expressions))
400 }
401 }
402 } else if fun.result.is_some() {
403 return Err(CallError::ExpressionMismatch(result).with_span());
404 }
405
406 let callee_info = &context.prev_infos[function.index()];
407 Ok(callee_info.available_stages)
408 }
409
410 fn emit_expression(
411 &mut self,
412 handle: Handle<crate::Expression>,
413 context: &BlockContext,
414 ) -> Result<(), WithSpan<FunctionError>> {
415 if self.valid_expression_set.insert(handle) {
416 self.valid_expression_list.push(handle);
417 Ok(())
418 } else {
419 Err(FunctionError::ExpressionAlreadyInScope(handle)
420 .with_span_handle(handle, context.expressions))
421 }
422 }
423
424 fn validate_atomic(
425 &mut self,
426 pointer: Handle<crate::Expression>,
427 fun: &crate::AtomicFunction,
428 value: Handle<crate::Expression>,
429 result: Option<Handle<crate::Expression>>,
430 span: crate::Span,
431 context: &BlockContext,
432 ) -> Result<(), WithSpan<FunctionError>> {
433 let pointer_inner = context.resolve_type_inner(pointer, &self.valid_expression_set)?;
435 let crate::TypeInner::Pointer {
436 base: pointer_base,
437 space: pointer_space,
438 } = *pointer_inner
439 else {
440 log::error!("Atomic operation on type {:?}", *pointer_inner);
441 return Err(AtomicError::InvalidPointer(pointer)
442 .with_span_handle(pointer, context.expressions)
443 .into_other());
444 };
445 let crate::TypeInner::Atomic(pointer_scalar) = context.types[pointer_base].inner else {
446 log::error!(
447 "Atomic pointer to type {:?}",
448 context.types[pointer_base].inner
449 );
450 return Err(AtomicError::InvalidPointer(pointer)
451 .with_span_handle(pointer, context.expressions)
452 .into_other());
453 };
454
455 let value_inner = context.resolve_type_inner(value, &self.valid_expression_set)?;
457 let crate::TypeInner::Scalar(value_scalar) = *value_inner else {
458 log::error!("Atomic operand type {:?}", *value_inner);
459 return Err(AtomicError::InvalidOperand(value)
460 .with_span_handle(value, context.expressions)
461 .into_other());
462 };
463 if pointer_scalar != value_scalar {
464 log::error!("Atomic operand type {:?}", *value_inner);
465 return Err(AtomicError::InvalidOperand(value)
466 .with_span_handle(value, context.expressions)
467 .into_other());
468 }
469
470 match pointer_scalar {
471 crate::Scalar::I64 | crate::Scalar::U64 => {
477 if self
480 .capabilities
481 .contains(super::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS)
482 {
483 } else {
485 if matches!(
488 *fun,
489 crate::AtomicFunction::Min | crate::AtomicFunction::Max
490 ) && matches!(pointer_space, crate::AddressSpace::Storage { .. })
491 && result.is_none()
492 {
493 if !self
494 .capabilities
495 .contains(super::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX)
496 {
497 log::error!("Int64 min-max atomic operations are not supported");
498 return Err(AtomicError::MissingCapability(
499 super::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX,
500 )
501 .with_span_handle(value, context.expressions)
502 .into_other());
503 }
504 } else {
505 log::error!("Int64 atomic operations are not supported");
507 return Err(AtomicError::MissingCapability(
508 super::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS,
509 )
510 .with_span_handle(value, context.expressions)
511 .into_other());
512 }
513 }
514 }
515 crate::Scalar::F32 => {
517 if !self
521 .capabilities
522 .contains(super::Capabilities::SHADER_FLOAT32_ATOMIC)
523 {
524 log::error!("Float32 atomic operations are not supported");
525 return Err(AtomicError::MissingCapability(
526 super::Capabilities::SHADER_FLOAT32_ATOMIC,
527 )
528 .with_span_handle(value, context.expressions)
529 .into_other());
530 }
531 if !matches!(
532 *fun,
533 crate::AtomicFunction::Add
534 | crate::AtomicFunction::Subtract
535 | crate::AtomicFunction::Exchange { compare: None }
536 ) {
537 log::error!("Float32 atomic operation {fun:?} is not supported");
538 return Err(AtomicError::InvalidOperator(*fun)
539 .with_span_handle(value, context.expressions)
540 .into_other());
541 }
542 if !matches!(pointer_space, crate::AddressSpace::Storage { .. }) {
543 log::error!(
544 "Float32 atomic operations are only supported in the Storage address space"
545 );
546 return Err(AtomicError::InvalidAddressSpace(pointer_space)
547 .with_span_handle(value, context.expressions)
548 .into_other());
549 }
550 }
551 _ => {}
552 }
553
554 match result {
556 Some(result) => {
557 let crate::Expression::AtomicResult {
559 ty: result_ty,
560 comparison,
561 } = context.expressions[result]
562 else {
563 return Err(AtomicError::InvalidResultExpression(result)
564 .with_span_handle(result, context.expressions)
565 .into_other());
566 };
567
568 if !self.needs_visit.remove(result) {
571 return Err(AtomicError::ResultAlreadyPopulated(result)
572 .with_span_handle(result, context.expressions)
573 .into_other());
574 }
575
576 if let crate::AtomicFunction::Exchange {
578 compare: Some(compare),
579 } = *fun
580 {
581 let compare_inner =
584 context.resolve_type_inner(compare, &self.valid_expression_set)?;
585 if !compare_inner.non_struct_equivalent(value_inner, context.types) {
586 log::error!(
587 "Atomic exchange comparison has a different type from the value"
588 );
589 return Err(AtomicError::InvalidOperand(compare)
590 .with_span_handle(compare, context.expressions)
591 .into_other());
592 }
593
594 let crate::TypeInner::Struct { ref members, .. } =
598 context.types[result_ty].inner
599 else {
600 return Err(AtomicError::ResultTypeMismatch(result)
601 .with_span_handle(result, context.expressions)
602 .into_other());
603 };
604 if !super::validate_atomic_compare_exchange_struct(
605 context.types,
606 members,
607 |ty: &crate::TypeInner| *ty == crate::TypeInner::Scalar(pointer_scalar),
608 ) {
609 return Err(AtomicError::ResultTypeMismatch(result)
610 .with_span_handle(result, context.expressions)
611 .into_other());
612 }
613
614 if !comparison {
616 return Err(AtomicError::ResultExpressionNotExchange(result)
617 .with_span_handle(result, context.expressions)
618 .into_other());
619 }
620 } else {
621 let result_inner = &context.types[result_ty].inner;
624 if !result_inner.non_struct_equivalent(value_inner, context.types) {
625 return Err(AtomicError::ResultTypeMismatch(result)
626 .with_span_handle(result, context.expressions)
627 .into_other());
628 }
629
630 if comparison {
632 return Err(AtomicError::ResultExpressionExchange(result)
633 .with_span_handle(result, context.expressions)
634 .into_other());
635 }
636 }
637 self.emit_expression(result, context)?;
638 }
639
640 None => {
641 if let crate::AtomicFunction::Exchange { compare: None } = *fun {
643 log::error!("Atomic exchange's value is unused");
644 return Err(AtomicError::MissingReturnValue
645 .with_span_static(span, "atomic exchange operation")
646 .into_other());
647 }
648 }
649 }
650
651 Ok(())
652 }
653 fn validate_subgroup_operation(
654 &mut self,
655 op: &crate::SubgroupOperation,
656 collective_op: &crate::CollectiveOperation,
657 argument: Handle<crate::Expression>,
658 result: Handle<crate::Expression>,
659 context: &BlockContext,
660 ) -> Result<(), WithSpan<FunctionError>> {
661 let argument_inner = context.resolve_type_inner(argument, &self.valid_expression_set)?;
662
663 let (is_scalar, scalar) = match *argument_inner {
664 crate::TypeInner::Scalar(scalar) => (true, scalar),
665 crate::TypeInner::Vector { scalar, .. } => (false, scalar),
666 _ => {
667 log::error!("Subgroup operand type {argument_inner:?}");
668 return Err(SubgroupError::InvalidOperand(argument)
669 .with_span_handle(argument, context.expressions)
670 .into_other());
671 }
672 };
673
674 use crate::ScalarKind as sk;
675 use crate::SubgroupOperation as sg;
676 match (scalar.kind, *op) {
677 (sk::Bool, sg::All | sg::Any) if is_scalar => {}
678 (sk::Sint | sk::Uint | sk::Float, sg::Add | sg::Mul | sg::Min | sg::Max) => {}
679 (sk::Sint | sk::Uint, sg::And | sg::Or | sg::Xor) if scalar.width >= 4 => {}
682
683 (_, _) => {
684 log::error!("Subgroup operand type {argument_inner:?}");
685 return Err(SubgroupError::InvalidOperand(argument)
686 .with_span_handle(argument, context.expressions)
687 .into_other());
688 }
689 };
690
691 use crate::CollectiveOperation as co;
692 match (*collective_op, *op) {
693 (
694 co::Reduce,
695 sg::All
696 | sg::Any
697 | sg::Add
698 | sg::Mul
699 | sg::Min
700 | sg::Max
701 | sg::And
702 | sg::Or
703 | sg::Xor,
704 ) => {}
705 (co::InclusiveScan | co::ExclusiveScan, sg::Add | sg::Mul) => {}
706
707 (_, _) => {
708 return Err(SubgroupError::UnknownOperation.with_span().into_other());
709 }
710 };
711
712 self.emit_expression(result, context)?;
713 match context.expressions[result] {
714 crate::Expression::SubgroupOperationResult { ty }
715 if { &context.types[ty].inner == argument_inner } => {}
716 _ => {
717 return Err(SubgroupError::ResultTypeMismatch(result)
718 .with_span_handle(result, context.expressions)
719 .into_other())
720 }
721 }
722 Ok(())
723 }
724 fn validate_subgroup_gather(
725 &mut self,
726 mode: &crate::GatherMode,
727 argument: Handle<crate::Expression>,
728 result: Handle<crate::Expression>,
729 context: &BlockContext,
730 ) -> Result<(), WithSpan<FunctionError>> {
731 match *mode {
732 crate::GatherMode::BroadcastFirst => {}
733 crate::GatherMode::Broadcast(index)
734 | crate::GatherMode::Shuffle(index)
735 | crate::GatherMode::ShuffleDown(index)
736 | crate::GatherMode::ShuffleUp(index)
737 | crate::GatherMode::ShuffleXor(index)
738 | crate::GatherMode::QuadBroadcast(index) => {
739 let index_ty = context.resolve_type_inner(index, &self.valid_expression_set)?;
740 match *index_ty {
741 crate::TypeInner::Scalar(crate::Scalar::U32) => {}
742 _ => {
743 log::error!(
744 "Subgroup gather index type {index_ty:?}, expected unsigned int"
745 );
746 return Err(SubgroupError::InvalidOperand(argument)
747 .with_span_handle(index, context.expressions)
748 .into_other());
749 }
750 }
751 }
752 crate::GatherMode::QuadSwap(_) => {}
753 }
754 match *mode {
755 crate::GatherMode::Broadcast(index) | crate::GatherMode::QuadBroadcast(index)
756 if !context.local_expr_kind.is_const(index) =>
757 {
758 return Err(SubgroupError::InvalidInvocationIdExprType(index)
759 .with_span_handle(index, context.expressions)
760 .into_other());
761 }
762 _ => {}
763 }
764 let argument_inner = context.resolve_type_inner(argument, &self.valid_expression_set)?;
765 if !matches!(*argument_inner,
766 crate::TypeInner::Scalar ( scalar, .. ) | crate::TypeInner::Vector { scalar, .. }
767 if matches!(scalar.kind, crate::ScalarKind::Uint | crate::ScalarKind::Sint | crate::ScalarKind::Float)
768 ) {
769 log::error!("Subgroup gather operand type {argument_inner:?}");
770 return Err(SubgroupError::InvalidOperand(argument)
771 .with_span_handle(argument, context.expressions)
772 .into_other());
773 }
774
775 self.emit_expression(result, context)?;
776 match context.expressions[result] {
777 crate::Expression::SubgroupOperationResult { ty }
778 if { &context.types[ty].inner == argument_inner } => {}
779 _ => {
780 return Err(SubgroupError::ResultTypeMismatch(result)
781 .with_span_handle(result, context.expressions)
782 .into_other())
783 }
784 }
785 Ok(())
786 }
787
788 #[allow(clippy::large_stack_frames)] fn validate_block_impl(
790 &mut self,
791 statements: &crate::Block,
792 context: &BlockContext,
793 ) -> Result<BlockInfo, WithSpan<FunctionError>> {
794 use crate::{AddressSpace, Statement as S, TypeInner as Ti};
795 let mut stages = super::ShaderStages::all();
796 for (statement, &span) in statements.span_iter() {
797 match *statement {
798 S::Emit(ref range) => {
799 for handle in range.clone() {
800 use crate::Expression as Ex;
801 match context.expressions[handle] {
802 Ex::Literal(_)
803 | Ex::Constant(_)
804 | Ex::Override(_)
805 | Ex::ZeroValue(_)
806 | Ex::Compose { .. }
807 | Ex::Access { .. }
808 | Ex::AccessIndex { .. }
809 | Ex::Splat { .. }
810 | Ex::Swizzle { .. }
811 | Ex::FunctionArgument(_)
812 | Ex::GlobalVariable(_)
813 | Ex::LocalVariable(_)
814 | Ex::Load { .. }
815 | Ex::ImageSample { .. }
816 | Ex::ImageLoad { .. }
817 | Ex::ImageQuery { .. }
818 | Ex::Unary { .. }
819 | Ex::Binary { .. }
820 | Ex::Select { .. }
821 | Ex::Derivative { .. }
822 | Ex::Relational { .. }
823 | Ex::Math { .. }
824 | Ex::As { .. }
825 | Ex::ArrayLength(_)
826 | Ex::RayQueryGetIntersection { .. }
827 | Ex::RayQueryVertexPositions { .. }
828 | Ex::CooperativeLoad { .. }
829 | Ex::CooperativeMultiplyAdd { .. } => {
830 self.emit_expression(handle, context)?
831 }
832 Ex::CallResult(_)
833 | Ex::AtomicResult { .. }
834 | Ex::WorkGroupUniformLoadResult { .. }
835 | Ex::RayQueryProceedResult
836 | Ex::SubgroupBallotResult
837 | Ex::SubgroupOperationResult { .. } => {
838 return Err(FunctionError::EmitResult(handle)
839 .with_span_handle(handle, context.expressions));
840 }
841 }
842 }
843 }
844 S::Block(ref block) => {
845 let info = self.validate_block(block, context)?;
846 stages &= info.stages;
847 }
848 S::If {
849 condition,
850 ref accept,
851 ref reject,
852 } => {
853 match *context.resolve_type_inner(condition, &self.valid_expression_set)? {
854 Ti::Scalar(crate::Scalar {
855 kind: crate::ScalarKind::Bool,
856 width: _,
857 }) => {}
858 _ => {
859 return Err(FunctionError::InvalidIfType(condition)
860 .with_span_handle(condition, context.expressions))
861 }
862 }
863 stages &= self.validate_block(accept, context)?.stages;
864 stages &= self.validate_block(reject, context)?.stages;
865 }
866 S::Switch {
867 selector,
868 ref cases,
869 } => {
870 let uint = match context
871 .resolve_type_inner(selector, &self.valid_expression_set)?
872 .scalar_kind()
873 {
874 Some(crate::ScalarKind::Uint) => true,
875 Some(crate::ScalarKind::Sint) => false,
876 _ => {
877 return Err(FunctionError::InvalidSwitchType(selector)
878 .with_span_handle(selector, context.expressions))
879 }
880 };
881 self.switch_values.clear();
882 for case in cases {
883 match case.value {
884 crate::SwitchValue::I32(_) if !uint => {}
885 crate::SwitchValue::U32(_) if uint => {}
886 crate::SwitchValue::Default => {}
887 _ => {
888 return Err(FunctionError::ConflictingCaseType.with_span_static(
889 case.body
890 .span_iter()
891 .next()
892 .map_or(Default::default(), |(_, s)| *s),
893 "conflicting switch arm here",
894 ));
895 }
896 };
897 if !self.switch_values.insert(case.value) {
898 return Err(match case.value {
899 crate::SwitchValue::Default => FunctionError::MultipleDefaultCases
900 .with_span_static(
901 case.body
902 .span_iter()
903 .next()
904 .map_or(Default::default(), |(_, s)| *s),
905 "duplicated switch arm here",
906 ),
907 _ => FunctionError::ConflictingSwitchCase(case.value)
908 .with_span_static(
909 case.body
910 .span_iter()
911 .next()
912 .map_or(Default::default(), |(_, s)| *s),
913 "conflicting switch arm here",
914 ),
915 });
916 }
917 }
918 if !self.switch_values.contains(&crate::SwitchValue::Default) {
919 return Err(FunctionError::MissingDefaultCase
920 .with_span_static(span, "missing default case"));
921 }
922 if let Some(case) = cases.last() {
923 if case.fall_through {
924 return Err(FunctionError::LastCaseFallTrough.with_span_static(
925 case.body
926 .span_iter()
927 .next()
928 .map_or(Default::default(), |(_, s)| *s),
929 "bad switch arm here",
930 ));
931 }
932 }
933 let pass_through_abilities = context.abilities
934 & (ControlFlowAbility::RETURN | ControlFlowAbility::CONTINUE);
935 let sub_context =
936 context.with_abilities(pass_through_abilities | ControlFlowAbility::BREAK);
937 for case in cases {
938 stages &= self.validate_block(&case.body, &sub_context)?.stages;
939 }
940 }
941 S::Loop {
942 ref body,
943 ref continuing,
944 break_if,
945 } => {
946 let base_expression_count = self.valid_expression_list.len();
949 let pass_through_abilities = context.abilities & ControlFlowAbility::RETURN;
950 stages &= self
951 .validate_block_impl(
952 body,
953 &context.with_abilities(
954 pass_through_abilities
955 | ControlFlowAbility::BREAK
956 | ControlFlowAbility::CONTINUE,
957 ),
958 )?
959 .stages;
960 stages &= self
961 .validate_block_impl(
962 continuing,
963 &context.with_abilities(ControlFlowAbility::empty()),
964 )?
965 .stages;
966
967 if let Some(condition) = break_if {
968 match *context.resolve_type_inner(condition, &self.valid_expression_set)? {
969 Ti::Scalar(crate::Scalar {
970 kind: crate::ScalarKind::Bool,
971 width: _,
972 }) => {}
973 _ => {
974 return Err(FunctionError::InvalidIfType(condition)
975 .with_span_handle(condition, context.expressions))
976 }
977 }
978 }
979
980 for handle in self.valid_expression_list.drain(base_expression_count..) {
981 self.valid_expression_set.remove(handle);
982 }
983 }
984 S::Break => {
985 if !context.abilities.contains(ControlFlowAbility::BREAK) {
986 return Err(FunctionError::BreakOutsideOfLoopOrSwitch
987 .with_span_static(span, "invalid break"));
988 }
989 }
990 S::Continue => {
991 if !context.abilities.contains(ControlFlowAbility::CONTINUE) {
992 return Err(FunctionError::ContinueOutsideOfLoop
993 .with_span_static(span, "invalid continue"));
994 }
995 }
996 S::Return { value } => {
997 if !context.abilities.contains(ControlFlowAbility::RETURN) {
998 return Err(FunctionError::InvalidReturnSpot
999 .with_span_static(span, "invalid return"));
1000 }
1001 let value_ty = value
1002 .map(|expr| context.resolve_type(expr, &self.valid_expression_set))
1003 .transpose()?;
1004 let okay = match (value_ty, context.return_type) {
1007 (None, None) => true,
1008 (Some(value_inner), Some(expected_ty)) => {
1009 context.compare_types(value_inner, &TypeResolution::Handle(expected_ty))
1010 }
1011 (_, _) => false,
1012 };
1013
1014 if !okay {
1015 log::error!(
1016 "Returning {:?} where {:?} is expected",
1017 value_ty,
1018 context.return_type,
1019 );
1020 if let Some(handle) = value {
1021 return Err(FunctionError::InvalidReturnType {
1022 expression: value,
1023 expected_ty: context.return_type,
1024 }
1025 .with_span_handle(handle, context.expressions));
1026 } else {
1027 return Err(FunctionError::InvalidReturnType {
1028 expression: value,
1029 expected_ty: context.return_type,
1030 }
1031 .with_span_static(span, "invalid return"));
1032 }
1033 }
1034 }
1035 S::Kill => {
1036 stages &= super::ShaderStages::FRAGMENT;
1037 }
1038 S::ControlBarrier(barrier) | S::MemoryBarrier(barrier) => {
1039 stages &= super::ShaderStages::COMPUTE_LIKE;
1040 if barrier.contains(crate::Barrier::SUB_GROUP) {
1041 if !self.capabilities.contains(
1042 super::Capabilities::SUBGROUP | super::Capabilities::SUBGROUP_BARRIER,
1043 ) {
1044 return Err(FunctionError::MissingCapability(
1045 super::Capabilities::SUBGROUP
1046 | super::Capabilities::SUBGROUP_BARRIER,
1047 )
1048 .with_span_static(span, "missing capability for this operation"));
1049 }
1050 if !self
1051 .subgroup_operations
1052 .contains(super::SubgroupOperationSet::BASIC)
1053 {
1054 return Err(FunctionError::InvalidSubgroup(
1055 SubgroupError::UnsupportedOperation(
1056 super::SubgroupOperationSet::BASIC,
1057 ),
1058 )
1059 .with_span_static(span, "support for this operation is not present"));
1060 }
1061 }
1062 }
1063 S::Store { pointer, value } => {
1064 let mut current = pointer;
1065 loop {
1066 match context.expressions[current] {
1067 crate::Expression::Access { base, .. }
1068 | crate::Expression::AccessIndex { base, .. } => current = base,
1069 crate::Expression::LocalVariable(_)
1070 | crate::Expression::GlobalVariable(_)
1071 | crate::Expression::FunctionArgument(_) => break,
1072 _ => {
1073 return Err(FunctionError::InvalidStorePointer(current)
1074 .with_span_handle(pointer, context.expressions))
1075 }
1076 }
1077 }
1078
1079 let value_tr = context.resolve_type(value, &self.valid_expression_set)?;
1080 let value_ty = value_tr.inner_with(context.types);
1081 match *value_ty {
1082 Ti::Image { .. } | Ti::Sampler { .. } => {
1083 return Err(FunctionError::InvalidStoreTexture {
1084 actual: value,
1085 actual_ty: value_ty.clone(),
1086 }
1087 .with_span_context((
1088 context.expressions.get_span(value),
1089 format!("this value is of type {value_ty:?}"),
1090 ))
1091 .with_span(span, "expects a texture argument"));
1092 }
1093 _ => {}
1094 }
1095
1096 let pointer_ty = context.resolve_pointer_type(pointer);
1097 let pointer_base_tr = pointer_ty.pointer_base_type();
1098 let pointer_base_ty = pointer_base_tr
1099 .as_ref()
1100 .map(|ty| ty.inner_with(context.types));
1101 let good = if let Some(&Ti::Atomic(ref scalar)) = pointer_base_ty {
1102 *value_ty == Ti::Scalar(*scalar)
1104 } else if let Some(&Ti::RayQuery { .. }) = pointer_base_ty {
1105 return Err(FunctionError::RayQueryStore(pointer)
1106 .with_span_context((
1107 context.expressions.get_span(pointer),
1108 format!("this pointer has a base type of {pointer_base_ty:?} which cannot be stored to"),
1109 ))
1110 .with_span(span, "store to a type which is not allowed to be stored to"));
1111 } else if let Some(tr) = pointer_base_tr {
1112 context.compare_types(value_tr, &tr)
1113 } else {
1114 false
1115 };
1116
1117 if !good {
1118 return Err(FunctionError::InvalidStoreTypes { pointer, value }
1119 .with_span()
1120 .with_handle(pointer, context.expressions)
1121 .with_handle(value, context.expressions));
1122 }
1123
1124 if let Some(space) = pointer_ty.pointer_space() {
1125 if !space.access().contains(crate::StorageAccess::STORE) {
1126 return Err(FunctionError::InvalidStorePointer(pointer)
1127 .with_span_static(
1128 context.expressions.get_span(pointer),
1129 "writing to this location is not permitted",
1130 ));
1131 }
1132 }
1133 }
1134 S::ImageStore {
1135 image,
1136 coordinate,
1137 array_index,
1138 value,
1139 } => {
1140 let global_var;
1143 let image_ty;
1144 match *context.get_expression(image) {
1145 crate::Expression::GlobalVariable(var_handle) => {
1146 global_var = &context.global_vars[var_handle];
1147 image_ty = global_var.ty;
1148 }
1149 crate::Expression::Access { base, .. }
1153 | crate::Expression::AccessIndex { base, .. } => {
1154 let crate::Expression::GlobalVariable(var_handle) =
1155 *context.get_expression(base)
1156 else {
1157 return Err(FunctionError::InvalidImageStore(
1158 ExpressionError::ExpectedGlobalVariable,
1159 )
1160 .with_span_handle(image, context.expressions));
1161 };
1162 global_var = &context.global_vars[var_handle];
1163
1164 let Ti::BindingArray { base, .. } = context.types[global_var.ty].inner
1166 else {
1167 return Err(FunctionError::InvalidImageStore(
1168 ExpressionError::ExpectedBindingArrayType(global_var.ty),
1169 )
1170 .with_span_handle(global_var.ty, context.types));
1171 };
1172
1173 image_ty = base;
1174 }
1175 _ => {
1176 return Err(FunctionError::InvalidImageStore(
1177 ExpressionError::ExpectedGlobalVariable,
1178 )
1179 .with_span_handle(image, context.expressions))
1180 }
1181 };
1182
1183 let Ti::Image {
1185 class,
1186 arrayed,
1187 dim,
1188 } = context.types[image_ty].inner
1189 else {
1190 return Err(FunctionError::InvalidImageStore(
1191 ExpressionError::ExpectedImageType(global_var.ty),
1192 )
1193 .with_span()
1194 .with_handle(global_var.ty, context.types)
1195 .with_handle(image, context.expressions));
1196 };
1197
1198 let crate::ImageClass::Storage { format, .. } = class else {
1200 return Err(FunctionError::InvalidImageStore(
1201 ExpressionError::InvalidImageClass(class),
1202 )
1203 .with_span_handle(image, context.expressions));
1204 };
1205
1206 if context
1208 .resolve_type_inner(coordinate, &self.valid_expression_set)?
1209 .image_storage_coordinates()
1210 .is_none_or(|coord_dim| coord_dim != dim)
1211 {
1212 return Err(FunctionError::InvalidImageStore(
1213 ExpressionError::InvalidImageCoordinateType(dim, coordinate),
1214 )
1215 .with_span_handle(coordinate, context.expressions));
1216 }
1217
1218 if arrayed != array_index.is_some() {
1221 return Err(FunctionError::InvalidImageStore(
1222 ExpressionError::InvalidImageArrayIndex,
1223 )
1224 .with_span_handle(coordinate, context.expressions));
1225 }
1226
1227 if let Some(expr) = array_index {
1229 if !matches!(
1230 *context.resolve_type_inner(expr, &self.valid_expression_set)?,
1231 Ti::Scalar(crate::Scalar {
1232 kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
1233 width: _,
1234 })
1235 ) {
1236 return Err(FunctionError::InvalidImageStore(
1237 ExpressionError::InvalidImageArrayIndexType(expr),
1238 )
1239 .with_span_handle(expr, context.expressions));
1240 }
1241 }
1242
1243 let value_ty = crate::TypeInner::Vector {
1244 size: crate::VectorSize::Quad,
1245 scalar: format.into(),
1246 };
1247
1248 let actual_value_ty =
1251 context.resolve_type_inner(value, &self.valid_expression_set)?;
1252 if actual_value_ty != &value_ty {
1253 return Err(FunctionError::InvalidStoreValue {
1254 actual: value,
1255 actual_ty: actual_value_ty.clone(),
1256 expected_ty: value_ty.clone(),
1257 }
1258 .with_span_context((
1259 context.expressions.get_span(value),
1260 format!("this value is of type {actual_value_ty:?}"),
1261 ))
1262 .with_span(
1263 span,
1264 format!("expects a value argument of type {value_ty:?}"),
1265 ));
1266 }
1267 }
1268 S::Call {
1269 function,
1270 ref arguments,
1271 result,
1272 } => match self.validate_call(function, arguments, result, context) {
1273 Ok(callee_stages) => stages &= callee_stages,
1274 Err(error) => {
1275 return Err(error.and_then(|error| {
1276 FunctionError::InvalidCall { function, error }
1277 .with_span_static(span, "invalid function call")
1278 }))
1279 }
1280 },
1281 S::Atomic {
1282 pointer,
1283 ref fun,
1284 value,
1285 result,
1286 } => {
1287 self.validate_atomic(pointer, fun, value, result, span, context)?;
1288 }
1289 S::ImageAtomic {
1290 image,
1291 coordinate,
1292 array_index,
1293 fun,
1294 value,
1295 } => {
1296 let var = match *context.get_expression(image) {
1297 crate::Expression::GlobalVariable(var_handle) => {
1298 &context.global_vars[var_handle]
1299 }
1300 crate::Expression::Access { base, .. }
1302 | crate::Expression::AccessIndex { base, .. } => {
1303 match *context.get_expression(base) {
1304 crate::Expression::GlobalVariable(var_handle) => {
1305 &context.global_vars[var_handle]
1306 }
1307 _ => {
1308 return Err(FunctionError::InvalidImageAtomic(
1309 ExpressionError::ExpectedGlobalVariable,
1310 )
1311 .with_span_handle(image, context.expressions))
1312 }
1313 }
1314 }
1315 _ => {
1316 return Err(FunctionError::InvalidImageAtomic(
1317 ExpressionError::ExpectedGlobalVariable,
1318 )
1319 .with_span_handle(image, context.expressions))
1320 }
1321 };
1322
1323 let global_ty = match context.types[var.ty].inner {
1325 Ti::BindingArray { base, .. } => &context.types[base].inner,
1326 ref inner => inner,
1327 };
1328
1329 let value_ty = match *global_ty {
1330 Ti::Image {
1331 class,
1332 arrayed,
1333 dim,
1334 } => {
1335 match context
1336 .resolve_type_inner(coordinate, &self.valid_expression_set)?
1337 .image_storage_coordinates()
1338 {
1339 Some(coord_dim) if coord_dim == dim => {}
1340 _ => {
1341 return Err(FunctionError::InvalidImageAtomic(
1342 ExpressionError::InvalidImageCoordinateType(
1343 dim, coordinate,
1344 ),
1345 )
1346 .with_span_handle(coordinate, context.expressions));
1347 }
1348 };
1349 if arrayed != array_index.is_some() {
1350 return Err(FunctionError::InvalidImageAtomic(
1351 ExpressionError::InvalidImageArrayIndex,
1352 )
1353 .with_span_handle(coordinate, context.expressions));
1354 }
1355 if let Some(expr) = array_index {
1356 match *context
1357 .resolve_type_inner(expr, &self.valid_expression_set)?
1358 {
1359 Ti::Scalar(crate::Scalar {
1360 kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
1361 width: _,
1362 }) => {}
1363 _ => {
1364 return Err(FunctionError::InvalidImageAtomic(
1365 ExpressionError::InvalidImageArrayIndexType(expr),
1366 )
1367 .with_span_handle(expr, context.expressions));
1368 }
1369 }
1370 }
1371 match class {
1372 crate::ImageClass::Storage { format, access } => {
1373 if !access.contains(crate::StorageAccess::ATOMIC) {
1374 return Err(FunctionError::InvalidImageAtomic(
1375 ExpressionError::InvalidImageStorageAccess(access),
1376 )
1377 .with_span_handle(image, context.expressions));
1378 }
1379 match format {
1380 crate::StorageFormat::R64Uint => {
1381 if !self.capabilities.intersects(
1382 super::Capabilities::TEXTURE_INT64_ATOMIC,
1383 ) {
1384 return Err(FunctionError::MissingCapability(
1385 super::Capabilities::TEXTURE_INT64_ATOMIC,
1386 )
1387 .with_span_static(
1388 span,
1389 "missing capability for this operation",
1390 ));
1391 }
1392 match fun {
1393 crate::AtomicFunction::Min
1394 | crate::AtomicFunction::Max => {}
1395 _ => {
1396 return Err(
1397 FunctionError::InvalidImageAtomicFunction(
1398 fun,
1399 )
1400 .with_span_handle(
1401 image,
1402 context.expressions,
1403 ),
1404 );
1405 }
1406 }
1407 }
1408 crate::StorageFormat::R32Sint
1409 | crate::StorageFormat::R32Uint => {
1410 if !self
1411 .capabilities
1412 .intersects(super::Capabilities::TEXTURE_ATOMIC)
1413 {
1414 return Err(FunctionError::MissingCapability(
1415 super::Capabilities::TEXTURE_ATOMIC,
1416 )
1417 .with_span_static(
1418 span,
1419 "missing capability for this operation",
1420 ));
1421 }
1422 match fun {
1423 crate::AtomicFunction::Add
1424 | crate::AtomicFunction::And
1425 | crate::AtomicFunction::ExclusiveOr
1426 | crate::AtomicFunction::InclusiveOr
1427 | crate::AtomicFunction::Min
1428 | crate::AtomicFunction::Max => {}
1429 _ => {
1430 return Err(
1431 FunctionError::InvalidImageAtomicFunction(
1432 fun,
1433 )
1434 .with_span_handle(
1435 image,
1436 context.expressions,
1437 ),
1438 );
1439 }
1440 }
1441 }
1442 _ => {
1443 return Err(FunctionError::InvalidImageAtomic(
1444 ExpressionError::InvalidImageFormat(format),
1445 )
1446 .with_span_handle(image, context.expressions));
1447 }
1448 }
1449 crate::TypeInner::Scalar(format.into())
1450 }
1451 _ => {
1452 return Err(FunctionError::InvalidImageAtomic(
1453 ExpressionError::InvalidImageClass(class),
1454 )
1455 .with_span_handle(image, context.expressions));
1456 }
1457 }
1458 }
1459 _ => {
1460 return Err(FunctionError::InvalidImageAtomic(
1461 ExpressionError::ExpectedImageType(var.ty),
1462 )
1463 .with_span()
1464 .with_handle(var.ty, context.types)
1465 .with_handle(image, context.expressions))
1466 }
1467 };
1468
1469 if *context.resolve_type_inner(value, &self.valid_expression_set)? != value_ty {
1470 return Err(FunctionError::InvalidImageAtomicValue(value)
1471 .with_span_handle(value, context.expressions));
1472 }
1473 }
1474 S::WorkGroupUniformLoad { pointer, result } => {
1475 stages &= super::ShaderStages::COMPUTE_LIKE;
1476 let pointer_inner =
1477 context.resolve_type_inner(pointer, &self.valid_expression_set)?;
1478 match *pointer_inner {
1479 Ti::Pointer {
1480 space: AddressSpace::WorkGroup,
1481 ..
1482 } => {}
1483 Ti::ValuePointer {
1484 space: AddressSpace::WorkGroup,
1485 ..
1486 } => {}
1487 _ => {
1488 return Err(FunctionError::WorkgroupUniformLoadInvalidPointer(pointer)
1489 .with_span_static(span, "WorkGroupUniformLoad"))
1490 }
1491 }
1492 self.emit_expression(result, context)?;
1493 let ty = match &context.expressions[result] {
1494 &crate::Expression::WorkGroupUniformLoadResult { ty } => ty,
1495 _ => {
1496 return Err(FunctionError::WorkgroupUniformLoadExpressionMismatch(
1497 result,
1498 )
1499 .with_span_static(span, "WorkGroupUniformLoad"));
1500 }
1501 };
1502 let expected_pointer_inner = Ti::Pointer {
1503 base: ty,
1504 space: AddressSpace::WorkGroup,
1505 };
1506 let atomic_specialization_ok = match *pointer_inner {
1509 Ti::Pointer {
1510 base: pointer_base,
1511 space: AddressSpace::WorkGroup,
1512 } => match (&context.types[pointer_base].inner, &context.types[ty].inner) {
1513 (&Ti::Atomic(pointer_scalar), &Ti::Scalar(result_scalar)) => {
1514 pointer_scalar == result_scalar
1515 }
1516 _ => false,
1517 },
1518 _ => false,
1519 };
1520 if !expected_pointer_inner.non_struct_equivalent(pointer_inner, context.types)
1521 && !atomic_specialization_ok
1522 {
1523 return Err(FunctionError::WorkgroupUniformLoadInvalidPointer(pointer)
1524 .with_span_static(span, "WorkGroupUniformLoad"));
1525 }
1526 }
1527 S::RayQuery { query, ref fun } => {
1528 let query_var = match *context.get_expression(query) {
1529 crate::Expression::LocalVariable(var) => &context.local_vars[var],
1530 ref other => {
1531 log::error!("Unexpected ray query expression {other:?}");
1532 return Err(FunctionError::InvalidRayQueryExpression(query)
1533 .with_span_static(span, "invalid query expression"));
1534 }
1535 };
1536 let rq_vertex_return = match context.types[query_var.ty].inner {
1537 Ti::RayQuery { vertex_return } => vertex_return,
1538 ref other => {
1539 log::error!("Unexpected ray query type {other:?}");
1540 return Err(FunctionError::InvalidRayQueryType(query_var.ty)
1541 .with_span_static(span, "invalid query type"));
1542 }
1543 };
1544 match *fun {
1545 crate::RayQueryFunction::Initialize {
1546 acceleration_structure,
1547 descriptor,
1548 } => {
1549 match *context.resolve_type_inner(
1550 acceleration_structure,
1551 &self.valid_expression_set,
1552 )? {
1553 Ti::AccelerationStructure { vertex_return } => {
1554 if (!vertex_return) && rq_vertex_return {
1555 return Err(FunctionError::MissingAccelerationStructureVertexReturn(acceleration_structure, query).with_span_static(span, "invalid acceleration structure"));
1556 }
1557 }
1558 _ => {
1559 return Err(FunctionError::InvalidAccelerationStructure(
1560 acceleration_structure,
1561 )
1562 .with_span_static(span, "invalid acceleration structure"))
1563 }
1564 }
1565 let desc_ty_given = context
1566 .resolve_type_inner(descriptor, &self.valid_expression_set)?;
1567 let desc_ty_expected = context
1568 .special_types
1569 .ray_desc
1570 .map(|handle| &context.types[handle].inner);
1571 if Some(desc_ty_given) != desc_ty_expected {
1572 return Err(FunctionError::InvalidRayDescriptor(descriptor)
1573 .with_span_static(span, "invalid ray descriptor"));
1574 }
1575 }
1576 crate::RayQueryFunction::Proceed { result } => {
1577 self.emit_expression(result, context)?;
1578 }
1579 crate::RayQueryFunction::GenerateIntersection { hit_t } => {
1580 match *context.resolve_type_inner(hit_t, &self.valid_expression_set)? {
1581 Ti::Scalar(crate::Scalar {
1582 kind: crate::ScalarKind::Float,
1583 width: _,
1584 }) => {}
1585 _ => {
1586 return Err(FunctionError::InvalidHitDistanceType(hit_t)
1587 .with_span_static(span, "invalid hit_t"))
1588 }
1589 }
1590 }
1591 crate::RayQueryFunction::ConfirmIntersection => {}
1592 crate::RayQueryFunction::Terminate => {}
1593 crate::RayQueryFunction::Begin => {}
1594 }
1595 }
1596 S::SubgroupBallot { result, predicate } => {
1597 stages &= self.subgroup_stages;
1598 if !self.capabilities.contains(super::Capabilities::SUBGROUP) {
1599 return Err(FunctionError::MissingCapability(
1600 super::Capabilities::SUBGROUP,
1601 )
1602 .with_span_static(span, "missing capability for this operation"));
1603 }
1604 if !self
1605 .subgroup_operations
1606 .contains(super::SubgroupOperationSet::BALLOT)
1607 {
1608 return Err(FunctionError::InvalidSubgroup(
1609 SubgroupError::UnsupportedOperation(
1610 super::SubgroupOperationSet::BALLOT,
1611 ),
1612 )
1613 .with_span_static(span, "support for this operation is not present"));
1614 }
1615 if let Some(predicate) = predicate {
1616 let predicate_inner =
1617 context.resolve_type_inner(predicate, &self.valid_expression_set)?;
1618 if !matches!(
1619 *predicate_inner,
1620 crate::TypeInner::Scalar(crate::Scalar::BOOL,)
1621 ) {
1622 log::error!(
1623 "Subgroup ballot predicate type {predicate_inner:?} expected bool"
1624 );
1625 return Err(SubgroupError::InvalidOperand(predicate)
1626 .with_span_handle(predicate, context.expressions)
1627 .into_other());
1628 }
1629 }
1630 self.emit_expression(result, context)?;
1631 }
1632 S::SubgroupCollectiveOperation {
1633 ref op,
1634 ref collective_op,
1635 argument,
1636 result,
1637 } => {
1638 stages &= self.subgroup_stages;
1639 if !self.capabilities.contains(super::Capabilities::SUBGROUP) {
1640 return Err(FunctionError::MissingCapability(
1641 super::Capabilities::SUBGROUP,
1642 )
1643 .with_span_static(span, "missing capability for this operation"));
1644 }
1645 let operation = op.required_operations();
1646 if !self.subgroup_operations.contains(operation) {
1647 return Err(FunctionError::InvalidSubgroup(
1648 SubgroupError::UnsupportedOperation(operation),
1649 )
1650 .with_span_static(span, "support for this operation is not present"));
1651 }
1652 self.validate_subgroup_operation(op, collective_op, argument, result, context)?;
1653 }
1654 S::SubgroupGather {
1655 ref mode,
1656 argument,
1657 result,
1658 } => {
1659 stages &= self.subgroup_stages;
1660 if !self.capabilities.contains(super::Capabilities::SUBGROUP) {
1661 return Err(FunctionError::MissingCapability(
1662 super::Capabilities::SUBGROUP,
1663 )
1664 .with_span_static(span, "missing capability for this operation"));
1665 }
1666 let operation = mode.required_operations();
1667 if !self.subgroup_operations.contains(operation) {
1668 return Err(FunctionError::InvalidSubgroup(
1669 SubgroupError::UnsupportedOperation(operation),
1670 )
1671 .with_span_static(span, "support for this operation is not present"));
1672 }
1673 self.validate_subgroup_gather(mode, argument, result, context)?;
1674 }
1675 S::CooperativeStore { target, ref data } => {
1676 stages &= super::ShaderStages::COMPUTE;
1677
1678 let target_scalar =
1679 match *context.resolve_type_inner(target, &self.valid_expression_set)? {
1680 Ti::CooperativeMatrix { scalar, .. } => scalar,
1681 ref other => {
1682 log::error!("Target operand type: {other:?}");
1683 return Err(FunctionError::InvalidCooperativeStoreTarget(target)
1684 .with_span_handle(target, context.expressions));
1685 }
1686 };
1687
1688 let ptr_ty = context.resolve_pointer_type(data.pointer);
1689 let ptr_scalar = ptr_ty
1690 .pointer_base_type()
1691 .and_then(|tr| tr.inner_with(context.types).scalar());
1692 if ptr_scalar != Some(target_scalar) {
1693 return Err(FunctionError::InvalidCooperativeDataPointer(data.pointer)
1694 .with_span_handle(data.pointer, context.expressions));
1695 }
1696
1697 let ptr_space = ptr_ty.pointer_space().unwrap_or(AddressSpace::Handle);
1698 if !ptr_space.access().contains(crate::StorageAccess::STORE) {
1699 return Err(FunctionError::InvalidStorePointer(data.pointer)
1700 .with_span_static(
1701 context.expressions.get_span(data.pointer),
1702 "writing to this location is not permitted",
1703 ));
1704 }
1705 }
1706 S::RayPipelineFunction(ref fun) => match *fun {
1707 crate::RayPipelineFunction::TraceRay {
1708 acceleration_structure,
1709 descriptor,
1710 payload,
1711 } => {
1712 match *context.resolve_type_inner(
1713 acceleration_structure,
1714 &self.valid_expression_set,
1715 )? {
1716 crate::TypeInner::AccelerationStructure { vertex_return } => {
1717 if !vertex_return {
1718 self.trace_rays_vertex_return =
1719 super::TraceRayVertexReturnState::NoVertexReturn(span);
1720 } else if let super::TraceRayVertexReturnState::NoTraceRays =
1721 self.trace_rays_vertex_return
1722 {
1723 self.trace_rays_vertex_return =
1724 super::TraceRayVertexReturnState::VertexReturn;
1725 }
1726 }
1727 _ => {
1728 return Err(FunctionError::InvalidAccelerationStructure(
1729 acceleration_structure,
1730 )
1731 .with_span_handle(acceleration_structure, context.expressions))
1732 }
1733 }
1734
1735 let current_payload_ty = match *context
1736 .resolve_type_inner(payload, &self.valid_expression_set)?
1737 {
1738 crate::TypeInner::Pointer { base, space } => {
1739 match space {
1740 AddressSpace::RayPayload | AddressSpace::IncomingRayPayload => {
1741 }
1742 space => {
1743 return Err(FunctionError::InvalidPayloadAddressSpace(
1744 space,
1745 )
1746 .with_span_handle(payload, context.expressions))
1747 }
1748 }
1749 base
1750 }
1751 _ => {
1752 return Err(FunctionError::InvalidPayloadType
1753 .with_span_handle(payload, context.expressions))
1754 }
1755 };
1756
1757 let crate::Expression::GlobalVariable(_) = context.expressions[payload]
1759 else {
1760 return Err(FunctionError::PayloadPointerNotGlobal
1761 .with_span_handle(payload, context.expressions));
1762 };
1763
1764 let ty = *self
1765 .trace_rays_payload_type
1766 .get_or_insert(current_payload_ty);
1767
1768 if ty != current_payload_ty {
1769 return Err(FunctionError::MismatchedPayloadType(
1770 current_payload_ty,
1771 ty,
1772 )
1773 .with_span_handle(ty, context.types));
1774 }
1775
1776 let desc_ty_given =
1777 context.resolve_type_inner(descriptor, &self.valid_expression_set)?;
1778 let desc_ty_expected = context
1779 .special_types
1780 .ray_desc
1781 .map(|handle| &context.types[handle].inner);
1782 if Some(desc_ty_given) != desc_ty_expected {
1783 return Err(FunctionError::InvalidRayDescriptor(descriptor)
1784 .with_span_static(span, "invalid ray descriptor"));
1785 }
1786 }
1787 },
1788
1789 S::DebugPrintf {
1793 format: _,
1794 ref arguments,
1795 } => {
1796 if !self
1797 .capabilities
1798 .contains(super::Capabilities::DEBUG_PRINTF)
1799 {
1800 return Err(FunctionError::MissingCapability(
1801 super::Capabilities::DEBUG_PRINTF,
1802 )
1803 .with_span_static(
1804 span,
1805 "`debugPrintf` requires the DEBUG_PRINTF capability",
1806 ));
1807 }
1808
1809 for &argument in arguments {
1810 let ty =
1811 context.resolve_type_inner(argument, &self.valid_expression_set)?;
1812 match *ty {
1813 Ti::Scalar(_) => {}
1817 _ => {
1818 return Err(FunctionError::InvalidDebugPrintfArgument(argument)
1819 .with_span_handle(argument, context.expressions));
1820 }
1821 }
1822 }
1823 }
1824 }
1825 }
1826 Ok(BlockInfo { stages })
1827 }
1828
1829 fn validate_block(
1830 &mut self,
1831 statements: &crate::Block,
1832 context: &BlockContext,
1833 ) -> Result<BlockInfo, WithSpan<FunctionError>> {
1834 let base_expression_count = self.valid_expression_list.len();
1835 let info = self.validate_block_impl(statements, context)?;
1836 for handle in self.valid_expression_list.drain(base_expression_count..) {
1837 self.valid_expression_set.remove(handle);
1838 }
1839 Ok(info)
1840 }
1841
1842 fn validate_local_var(
1843 &self,
1844 var: &crate::LocalVariable,
1845 gctx: crate::proc::GlobalCtx,
1846 fun_info: &FunctionInfo,
1847 local_expr_kind: &crate::proc::ExpressionKindTracker,
1848 ) -> Result<(), LocalVariableError> {
1849 log::debug!("var {var:?}");
1850 let type_info = self
1851 .types
1852 .get(var.ty.index())
1853 .ok_or(LocalVariableError::InvalidType(var.ty))?;
1854 if !type_info.flags.contains(super::TypeFlags::CONSTRUCTIBLE) {
1855 return Err(LocalVariableError::InvalidType(var.ty));
1856 }
1857
1858 if let Some(init) = var.init {
1859 if !gctx.compare_types(&TypeResolution::Handle(var.ty), &fun_info[init].ty) {
1860 return Err(LocalVariableError::InitializerType);
1861 }
1862
1863 if !local_expr_kind.is_const_or_override(init) {
1864 return Err(LocalVariableError::NonConstOrOverrideInitializer);
1865 }
1866
1867 if matches!(gctx.types[var.ty].inner, crate::TypeInner::RayQuery { .. }) {
1868 return Err(LocalVariableError::RayQueryWithInitializeExpression);
1869 }
1870 }
1871
1872 Ok(())
1873 }
1874
1875 pub(super) fn validate_function(
1876 &mut self,
1877 fun: &crate::Function,
1878 module: &crate::Module,
1879 mod_info: &ModuleInfo,
1880 entry_point: bool,
1881 ) -> Result<FunctionInfo, WithSpan<FunctionError>> {
1882 let mut info = mod_info.process_function(fun, module, self.flags, self.capabilities)?;
1883
1884 let local_expr_kind = crate::proc::ExpressionKindTracker::from_arena(&fun.expressions);
1885
1886 for (var_handle, var) in fun.local_variables.iter() {
1887 self.validate_local_var(var, module.to_ctx(), &info, &local_expr_kind)
1888 .map_err(|source| {
1889 FunctionError::LocalVariable {
1890 handle: var_handle,
1891 name: var.name.clone().unwrap_or_default(),
1892 source,
1893 }
1894 .with_span_handle(var.ty, &module.types)
1895 .with_handle(var_handle, &fun.local_variables)
1896 })?;
1897 }
1898
1899 for (index, argument) in fun.arguments.iter().enumerate() {
1900 match module.types[argument.ty].inner.pointer_space() {
1901 Some(crate::AddressSpace::Private | crate::AddressSpace::Function) | None => {}
1902 Some(other) => {
1903 return Err(FunctionError::InvalidArgumentPointerSpace {
1904 index,
1905 name: argument.name.clone().unwrap_or_default(),
1906 space: other,
1907 }
1908 .with_span_handle(argument.ty, &module.types))
1909 }
1910 }
1911 if !self.types[argument.ty.index()]
1913 .flags
1914 .contains(super::TypeFlags::ARGUMENT)
1915 {
1916 return Err(FunctionError::InvalidArgumentType {
1917 index,
1918 name: argument.name.clone().unwrap_or_default(),
1919 }
1920 .with_span_handle(argument.ty, &module.types));
1921 }
1922
1923 if !entry_point && argument.binding.is_some() {
1924 return Err(FunctionError::PipelineInputRegularFunction {
1925 name: argument.name.clone().unwrap_or_default(),
1926 }
1927 .with_span_handle(argument.ty, &module.types));
1928 }
1929 }
1930
1931 if let Some(ref result) = fun.result {
1932 if !self.types[result.ty.index()]
1933 .flags
1934 .contains(super::TypeFlags::CONSTRUCTIBLE)
1935 {
1936 return Err(FunctionError::NonConstructibleReturnType
1937 .with_span_handle(result.ty, &module.types));
1938 }
1939
1940 if !entry_point && result.binding.is_some() {
1941 return Err(FunctionError::PipelineOutputRegularFunction
1942 .with_span_handle(result.ty, &module.types));
1943 }
1944 }
1945
1946 self.valid_expression_set.clear_for_arena(&fun.expressions);
1947 self.valid_expression_list.clear();
1948 self.needs_visit.clear_for_arena(&fun.expressions);
1949 for (handle, expr) in fun.expressions.iter() {
1950 if expr.needs_pre_emit() {
1951 self.valid_expression_set.insert(handle);
1952 }
1953 if self.flags.contains(super::ValidationFlags::EXPRESSIONS) {
1954 if let crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } =
1957 *expr
1958 {
1959 self.needs_visit.insert(handle);
1960 }
1961
1962 match self.validate_expression(
1963 handle,
1964 expr,
1965 fun,
1966 module,
1967 &info,
1968 mod_info,
1969 &local_expr_kind,
1970 ) {
1971 Ok(stages) => info.available_stages &= stages,
1972 Err(source) => {
1973 return Err(FunctionError::Expression { handle, source }
1974 .with_span_handle(handle, &fun.expressions))
1975 }
1976 }
1977 }
1978 }
1979
1980 if self.flags.contains(super::ValidationFlags::BLOCKS) {
1981 let stages = self
1982 .validate_block(
1983 &fun.body,
1984 &BlockContext::new(fun, module, &info, &mod_info.functions, &local_expr_kind),
1985 )?
1986 .stages;
1987 info.available_stages &= stages;
1988
1989 if self.flags.contains(super::ValidationFlags::EXPRESSIONS) {
1990 if let Some(handle) = self.needs_visit.iter().next() {
1991 return Err(FunctionError::UnvisitedExpression(handle)
1992 .with_span_handle(handle, &fun.expressions));
1993 }
1994 }
1995 }
1996 Ok(info)
1997 }
1998}