1use super::{compose::validate_compose, FunctionInfo, ModuleInfo, ShaderStages, TypeFlags};
2use crate::arena::UniqueArena;
3use crate::{
4 arena::Handle,
5 proc::OverloadSet as _,
6 proc::{IndexableLengthError, ResolveError},
7};
8
9#[derive(Clone, Debug, thiserror::Error)]
10#[cfg_attr(test, derive(PartialEq))]
11pub enum ExpressionError {
12 #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")]
13 NotInScope,
14 #[error("Base type {0:?} is not compatible with this expression")]
15 InvalidBaseType(Handle<crate::Expression>),
16 #[error("Accessing with index {0:?} can't be done")]
17 InvalidIndexType(Handle<crate::Expression>),
18 #[error("Accessing {0:?} via a negative index is invalid")]
19 NegativeIndex(Handle<crate::Expression>),
20 #[error("Accessing index {1} is out of {0:?} bounds")]
21 IndexOutOfBounds(Handle<crate::Expression>, u32),
22 #[error("Function argument {0:?} doesn't exist")]
23 FunctionArgumentDoesntExist(u32),
24 #[error("Loading of {0:?} can't be done")]
25 InvalidPointerType(Handle<crate::Expression>),
26 #[error("Array length of {0:?} can't be done")]
27 InvalidArrayType(Handle<crate::Expression>),
28 #[error("Get intersection of {0:?} can't be done")]
29 InvalidRayQueryType(Handle<crate::Expression>),
30 #[error("Splatting {0:?} can't be done")]
31 InvalidSplatType(Handle<crate::Expression>),
32 #[error("Swizzling {0:?} can't be done")]
33 InvalidVectorType(Handle<crate::Expression>),
34 #[error("Swizzle component {0:?} is outside of vector size {1:?}")]
35 InvalidSwizzleComponent(crate::SwizzleComponent, crate::VectorSize),
36 #[error(transparent)]
37 Compose(#[from] super::ComposeError),
38 #[error(transparent)]
39 IndexableLength(#[from] IndexableLengthError),
40 #[error("Operation {0:?} can't work with {1:?}")]
41 InvalidUnaryOperandType(crate::UnaryOperator, Handle<crate::Expression>),
42 #[error(
43 "Operation {:?} can't work with {:?} (of type {:?}) and {:?} (of type {:?})",
44 op,
45 lhs_expr,
46 lhs_type,
47 rhs_expr,
48 rhs_type
49 )]
50 InvalidBinaryOperandTypes {
51 op: crate::BinaryOperator,
52 lhs_expr: Handle<crate::Expression>,
53 lhs_type: crate::TypeInner,
54 rhs_expr: Handle<crate::Expression>,
55 rhs_type: crate::TypeInner,
56 },
57 #[error("Expected selection argument types to match, but reject value of type {reject:?} does not match accept value of value {accept:?}")]
58 SelectValuesTypeMismatch {
59 accept: crate::TypeInner,
60 reject: crate::TypeInner,
61 },
62 #[error("Expected selection condition to be a boolean value, got {actual:?}")]
63 SelectConditionNotABool { actual: crate::TypeInner },
64 #[error("Relational argument {0:?} is not a boolean vector")]
65 InvalidBooleanVector(Handle<crate::Expression>),
66 #[error("Relational argument {0:?} is not a float")]
67 InvalidFloatArgument(Handle<crate::Expression>),
68 #[error("Type resolution failed")]
69 Type(#[from] ResolveError),
70 #[error("Not a global variable")]
71 ExpectedGlobalVariable,
72 #[error("Not a global variable or a function argument")]
73 ExpectedGlobalOrArgument,
74 #[error("Needs to be an binding array instead of {0:?}")]
75 ExpectedBindingArrayType(Handle<crate::Type>),
76 #[error("Needs to be an image instead of {0:?}")]
77 ExpectedImageType(Handle<crate::Type>),
78 #[error("Needs to be an image instead of {0:?}")]
79 ExpectedSamplerType(Handle<crate::Type>),
80 #[error("Unable to operate on image class {0:?}")]
81 InvalidImageClass(crate::ImageClass),
82 #[error("Image atomics are not supported for storage format {0:?}")]
83 InvalidImageFormat(crate::StorageFormat),
84 #[error("Image atomics require atomic storage access, {0:?} is insufficient")]
85 InvalidImageStorageAccess(crate::StorageAccess),
86 #[error("Derivatives can only be taken from scalar and vector floats")]
87 InvalidDerivative,
88 #[error("Image array index parameter is misplaced")]
89 InvalidImageArrayIndex,
90 #[error("Inappropriate sample or level-of-detail index for texel access")]
91 InvalidImageOtherIndex,
92 #[error("Image array index type of {0:?} is not an integer scalar")]
93 InvalidImageArrayIndexType(Handle<crate::Expression>),
94 #[error("Image sample or level-of-detail index's type of {0:?} is not an integer scalar")]
95 InvalidImageOtherIndexType(Handle<crate::Expression>),
96 #[error("Image coordinate type of {1:?} does not match dimension {0:?}")]
97 InvalidImageCoordinateType(crate::ImageDimension, Handle<crate::Expression>),
98 #[error("Comparison sampling mismatch: image has class {image:?}, but the sampler is comparison={sampler}, and the reference was provided={has_ref}")]
99 ComparisonSamplingMismatch {
100 image: crate::ImageClass,
101 sampler: bool,
102 has_ref: bool,
103 },
104 #[error("Sample offset must be a const-expression")]
105 InvalidSampleOffsetExprType,
106 #[error("Sample offset constant {1:?} doesn't match the image dimension {0:?}")]
107 InvalidSampleOffset(crate::ImageDimension, Handle<crate::Expression>),
108 #[error("Depth reference {0:?} is not a scalar float")]
109 InvalidDepthReference(Handle<crate::Expression>),
110 #[error("Depth sample level can only be Auto or Zero")]
111 InvalidDepthSampleLevel,
112 #[error("Gather level can only be Zero")]
113 InvalidGatherLevel,
114 #[error("Gather component {0:?} doesn't exist in the image")]
115 InvalidGatherComponent(crate::SwizzleComponent),
116 #[error("Gather can't be done for image dimension {0:?}")]
117 InvalidGatherDimension(crate::ImageDimension),
118 #[error("Sample level (exact) type {0:?} has an invalid type")]
119 InvalidSampleLevelExactType(Handle<crate::Expression>),
120 #[error("Sample level (bias) type {0:?} is not a scalar float")]
121 InvalidSampleLevelBiasType(Handle<crate::Expression>),
122 #[error("Bias can't be done for image dimension {0:?}")]
123 InvalidSampleLevelBiasDimension(crate::ImageDimension),
124 #[error("Sample level (gradient) of {1:?} doesn't match the image dimension {0:?}")]
125 InvalidSampleLevelGradientType(crate::ImageDimension, Handle<crate::Expression>),
126 #[error("Clamping sample coordinate to edge is not supported with {0}")]
127 InvalidSampleClampCoordinateToEdge(alloc::string::String),
128 #[error("Unable to cast")]
129 InvalidCastArgument,
130 #[error("Invalid argument count for {0:?}")]
131 WrongArgumentCount(crate::MathFunction),
132 #[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")]
133 InvalidArgumentType(crate::MathFunction, u32, Handle<crate::Expression>),
134 #[error(
135 "workgroupUniformLoad result type can't be {0:?}. It can only be a constructible type."
136 )]
137 InvalidWorkGroupUniformLoadResultType(Handle<crate::Type>),
138 #[error("Shader requires capability {0:?}")]
139 MissingCapabilities(super::Capabilities),
140 #[error(transparent)]
141 Literal(#[from] LiteralError),
142 #[error("{0:?} is not supported for Width {2} {1:?} arguments yet, see https://github.com/gfx-rs/wgpu/issues/5276")]
143 UnsupportedWidth(crate::MathFunction, crate::ScalarKind, crate::Bytes),
144}
145
146#[derive(Clone, Debug, thiserror::Error)]
147#[cfg_attr(test, derive(PartialEq))]
148pub enum ConstExpressionError {
149 #[error("The expression is not a constant or override expression")]
150 NonConstOrOverride,
151 #[error("The expression is not a fully evaluated constant expression")]
152 NonFullyEvaluatedConst,
153 #[error(transparent)]
154 Compose(#[from] super::ComposeError),
155 #[error("Splatting {0:?} can't be done")]
156 InvalidSplatType(Handle<crate::Expression>),
157 #[error("Type resolution failed")]
158 Type(#[from] ResolveError),
159 #[error(transparent)]
160 Literal(#[from] LiteralError),
161 #[error(transparent)]
162 Width(#[from] super::r#type::WidthError),
163}
164
165#[derive(Clone, Debug, thiserror::Error)]
166#[cfg_attr(test, derive(PartialEq))]
167pub enum LiteralError {
168 #[error("Float literal is NaN")]
169 NaN,
170 #[error("Float literal is infinite")]
171 Infinity,
172 #[error(transparent)]
173 Width(#[from] super::r#type::WidthError),
174}
175
176struct ExpressionTypeResolver<'a> {
177 root: Handle<crate::Expression>,
178 types: &'a UniqueArena<crate::Type>,
179 info: &'a FunctionInfo,
180}
181
182impl core::ops::Index<Handle<crate::Expression>> for ExpressionTypeResolver<'_> {
183 type Output = crate::TypeInner;
184
185 #[allow(clippy::panic)]
186 fn index(&self, handle: Handle<crate::Expression>) -> &Self::Output {
187 if handle < self.root {
188 self.info[handle].ty.inner_with(self.types)
189 } else {
190 panic!(
192 "Depends on {:?}, which has not been processed yet",
193 self.root
194 )
195 }
196 }
197}
198
199impl super::Validator {
200 pub(super) fn validate_const_expression(
201 &self,
202 handle: Handle<crate::Expression>,
203 gctx: crate::proc::GlobalCtx,
204 mod_info: &ModuleInfo,
205 global_expr_kind: &crate::proc::ExpressionKindTracker,
206 ) -> Result<(), ConstExpressionError> {
207 use crate::Expression as E;
208
209 if !global_expr_kind.is_const_or_override(handle) {
210 return Err(ConstExpressionError::NonConstOrOverride);
211 }
212
213 match gctx.global_expressions[handle] {
214 E::Literal(literal) => {
215 self.validate_literal(literal)?;
216 }
217 E::Constant(_) | E::ZeroValue(_) => {}
218 E::Compose { ref components, ty } => {
219 validate_compose(
220 ty,
221 gctx,
222 components.iter().map(|&handle| mod_info[handle].clone()),
223 )?;
224 }
225 E::Splat { value, .. } => match *mod_info[value].inner_with(gctx.types) {
226 crate::TypeInner::Scalar { .. } => {}
227 _ => return Err(ConstExpressionError::InvalidSplatType(value)),
228 },
229 _ if global_expr_kind.is_const(handle) || self.overrides_resolved => {
230 return Err(ConstExpressionError::NonFullyEvaluatedConst)
231 }
232 _ => {}
234 }
235
236 Ok(())
237 }
238
239 #[allow(clippy::too_many_arguments)]
240 pub(super) fn validate_expression(
241 &self,
242 root: Handle<crate::Expression>,
243 expression: &crate::Expression,
244 function: &crate::Function,
245 module: &crate::Module,
246 info: &FunctionInfo,
247 mod_info: &ModuleInfo,
248 expr_kind: &crate::proc::ExpressionKindTracker,
249 ) -> Result<ShaderStages, ExpressionError> {
250 use crate::{Expression as E, Scalar as Sc, ScalarKind as Sk, TypeInner as Ti};
251
252 let resolver = ExpressionTypeResolver {
253 root,
254 types: &module.types,
255 info,
256 };
257
258 let stages = match *expression {
259 E::Access { base, index } => {
260 let base_type = &resolver[base];
261 match *base_type {
262 Ti::Matrix { .. }
263 | Ti::Vector { .. }
264 | Ti::Array { .. }
265 | Ti::Pointer { .. }
266 | Ti::ValuePointer { size: Some(_), .. }
267 | Ti::BindingArray { .. } => {}
268 ref other => {
269 log::error!("Indexing of {:?}", other);
270 return Err(ExpressionError::InvalidBaseType(base));
271 }
272 };
273 match resolver[index] {
274 Ti::Scalar(Sc {
276 kind: Sk::Sint | Sk::Uint,
277 ..
278 }) => {}
279 ref other => {
280 log::error!("Indexing by {:?}", other);
281 return Err(ExpressionError::InvalidIndexType(index));
282 }
283 }
284
285 match module
287 .to_ctx()
288 .eval_expr_to_u32_from(index, &function.expressions)
289 {
290 Ok(value) => {
291 let length = if self.overrides_resolved {
292 base_type.indexable_length_resolved(module)
293 } else {
294 base_type.indexable_length_pending(module)
295 }?;
296 if let crate::proc::IndexableLength::Known(known_length) = length {
299 if value >= known_length {
300 return Err(ExpressionError::IndexOutOfBounds(base, value));
301 }
302 }
303 }
304 Err(crate::proc::U32EvalError::Negative) => {
305 return Err(ExpressionError::NegativeIndex(base))
306 }
307 Err(crate::proc::U32EvalError::NonConst) => {}
308 }
309
310 ShaderStages::all()
311 }
312 E::AccessIndex { base, index } => {
313 fn resolve_index_limit(
314 module: &crate::Module,
315 top: Handle<crate::Expression>,
316 ty: &crate::TypeInner,
317 top_level: bool,
318 ) -> Result<u32, ExpressionError> {
319 let limit = match *ty {
320 Ti::Vector { size, .. }
321 | Ti::ValuePointer {
322 size: Some(size), ..
323 } => size as u32,
324 Ti::Matrix { columns, .. } => columns as u32,
325 Ti::Array {
326 size: crate::ArraySize::Constant(len),
327 ..
328 } => len.get(),
329 Ti::Array { .. } | Ti::BindingArray { .. } => u32::MAX, Ti::Pointer { base, .. } if top_level => {
331 resolve_index_limit(module, top, &module.types[base].inner, false)?
332 }
333 Ti::Struct { ref members, .. } => members.len() as u32,
334 ref other => {
335 log::error!("Indexing of {:?}", other);
336 return Err(ExpressionError::InvalidBaseType(top));
337 }
338 };
339 Ok(limit)
340 }
341
342 let limit = resolve_index_limit(module, base, &resolver[base], true)?;
343 if index >= limit {
344 return Err(ExpressionError::IndexOutOfBounds(base, limit));
345 }
346 ShaderStages::all()
347 }
348 E::Splat { size: _, value } => match resolver[value] {
349 Ti::Scalar { .. } => ShaderStages::all(),
350 ref other => {
351 log::error!("Splat scalar type {:?}", other);
352 return Err(ExpressionError::InvalidSplatType(value));
353 }
354 },
355 E::Swizzle {
356 size,
357 vector,
358 pattern,
359 } => {
360 let vec_size = match resolver[vector] {
361 Ti::Vector { size: vec_size, .. } => vec_size,
362 ref other => {
363 log::error!("Swizzle vector type {:?}", other);
364 return Err(ExpressionError::InvalidVectorType(vector));
365 }
366 };
367 for &sc in pattern[..size as usize].iter() {
368 if sc as u8 >= vec_size as u8 {
369 return Err(ExpressionError::InvalidSwizzleComponent(sc, vec_size));
370 }
371 }
372 ShaderStages::all()
373 }
374 E::Literal(literal) => {
375 self.validate_literal(literal)?;
376 ShaderStages::all()
377 }
378 E::Constant(_) | E::Override(_) | E::ZeroValue(_) => ShaderStages::all(),
379 E::Compose { ref components, ty } => {
380 validate_compose(
381 ty,
382 module.to_ctx(),
383 components.iter().map(|&handle| info[handle].ty.clone()),
384 )?;
385 ShaderStages::all()
386 }
387 E::FunctionArgument(index) => {
388 if index >= function.arguments.len() as u32 {
389 return Err(ExpressionError::FunctionArgumentDoesntExist(index));
390 }
391 ShaderStages::all()
392 }
393 E::GlobalVariable(_handle) => ShaderStages::all(),
394 E::LocalVariable(_handle) => ShaderStages::all(),
395 E::Load { pointer } => {
396 match resolver[pointer] {
397 Ti::Pointer { base, .. }
398 if self.types[base.index()]
399 .flags
400 .contains(TypeFlags::SIZED | TypeFlags::DATA) => {}
401 Ti::ValuePointer { .. } => {}
402 ref other => {
403 log::error!("Loading {:?}", other);
404 return Err(ExpressionError::InvalidPointerType(pointer));
405 }
406 }
407 ShaderStages::all()
408 }
409 E::ImageSample {
410 image,
411 sampler,
412 gather,
413 coordinate,
414 array_index,
415 offset,
416 level,
417 depth_ref,
418 clamp_to_edge,
419 } => {
420 let image_ty = Self::global_var_ty(module, function, image)?;
422 let sampler_ty = Self::global_var_ty(module, function, sampler)?;
423
424 let comparison = match module.types[sampler_ty].inner {
425 Ti::Sampler { comparison } => comparison,
426 _ => return Err(ExpressionError::ExpectedSamplerType(sampler_ty)),
427 };
428
429 let (class, dim) = match module.types[image_ty].inner {
430 Ti::Image {
431 class,
432 arrayed,
433 dim,
434 } => {
435 if arrayed != array_index.is_some() {
437 return Err(ExpressionError::InvalidImageArrayIndex);
438 }
439 if let Some(expr) = array_index {
440 match resolver[expr] {
441 Ti::Scalar(Sc {
442 kind: Sk::Sint | Sk::Uint,
443 ..
444 }) => {}
445 _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)),
446 }
447 }
448 (class, dim)
449 }
450 _ => return Err(ExpressionError::ExpectedImageType(image_ty)),
451 };
452
453 let image_depth = match class {
455 crate::ImageClass::Sampled {
456 kind: crate::ScalarKind::Float,
457 multi: false,
458 } => false,
459 crate::ImageClass::Sampled {
460 kind: crate::ScalarKind::Uint | crate::ScalarKind::Sint,
461 multi: false,
462 } if gather.is_some() => false,
463 crate::ImageClass::Depth { multi: false } => true,
464 _ => return Err(ExpressionError::InvalidImageClass(class)),
465 };
466 if comparison != depth_ref.is_some() || (comparison && !image_depth) {
467 return Err(ExpressionError::ComparisonSamplingMismatch {
468 image: class,
469 sampler: comparison,
470 has_ref: depth_ref.is_some(),
471 });
472 }
473
474 let num_components = match dim {
476 crate::ImageDimension::D1 => 1,
477 crate::ImageDimension::D2 => 2,
478 crate::ImageDimension::D3 | crate::ImageDimension::Cube => 3,
479 };
480 match resolver[coordinate] {
481 Ti::Scalar(Sc {
482 kind: Sk::Float, ..
483 }) if num_components == 1 => {}
484 Ti::Vector {
485 size,
486 scalar:
487 Sc {
488 kind: Sk::Float, ..
489 },
490 } if size as u32 == num_components => {}
491 _ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)),
492 }
493
494 if let Some(const_expr) = offset {
496 if !expr_kind.is_const(const_expr) {
497 return Err(ExpressionError::InvalidSampleOffsetExprType);
498 }
499
500 match resolver[const_expr] {
501 Ti::Scalar(Sc { kind: Sk::Sint, .. }) if num_components == 1 => {}
502 Ti::Vector {
503 size,
504 scalar: Sc { kind: Sk::Sint, .. },
505 } if size as u32 == num_components => {}
506 _ => {
507 return Err(ExpressionError::InvalidSampleOffset(dim, const_expr));
508 }
509 }
510 }
511
512 if let Some(expr) = depth_ref {
514 match resolver[expr] {
515 Ti::Scalar(Sc {
516 kind: Sk::Float, ..
517 }) => {}
518 _ => return Err(ExpressionError::InvalidDepthReference(expr)),
519 }
520 match level {
521 crate::SampleLevel::Auto | crate::SampleLevel::Zero => {}
522 _ => return Err(ExpressionError::InvalidDepthSampleLevel),
523 }
524 }
525
526 if let Some(component) = gather {
527 match dim {
528 crate::ImageDimension::D2 | crate::ImageDimension::Cube => {}
529 crate::ImageDimension::D1 | crate::ImageDimension::D3 => {
530 return Err(ExpressionError::InvalidGatherDimension(dim))
531 }
532 };
533 let max_component = match class {
534 crate::ImageClass::Depth { .. } => crate::SwizzleComponent::X,
535 _ => crate::SwizzleComponent::W,
536 };
537 if component > max_component {
538 return Err(ExpressionError::InvalidGatherComponent(component));
539 }
540 match level {
541 crate::SampleLevel::Zero => {}
542 _ => return Err(ExpressionError::InvalidGatherLevel),
543 }
544 }
545
546 if clamp_to_edge {
549 if !matches!(
550 class,
551 crate::ImageClass::Sampled {
552 kind: crate::ScalarKind::Float,
553 multi: false
554 }
555 ) {
556 return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
557 alloc::format!("image class `{class:?}`"),
558 ));
559 }
560 if dim != crate::ImageDimension::D2 {
561 return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
562 alloc::format!("image dimension `{dim:?}`"),
563 ));
564 }
565 if gather.is_some() {
566 return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
567 "gather".into(),
568 ));
569 }
570 if array_index.is_some() {
571 return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
572 "array index".into(),
573 ));
574 }
575 if offset.is_some() {
576 return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
577 "offset".into(),
578 ));
579 }
580 if level != crate::SampleLevel::Zero {
581 return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
582 "non-zero level".into(),
583 ));
584 }
585 if depth_ref.is_some() {
586 return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
587 "depth comparison".into(),
588 ));
589 }
590 }
591
592 match level {
594 crate::SampleLevel::Auto => ShaderStages::FRAGMENT,
595 crate::SampleLevel::Zero => ShaderStages::all(),
596 crate::SampleLevel::Exact(expr) => {
597 match class {
598 crate::ImageClass::Depth { .. } => match resolver[expr] {
599 Ti::Scalar(Sc {
600 kind: Sk::Sint | Sk::Uint,
601 ..
602 }) => {}
603 _ => {
604 return Err(ExpressionError::InvalidSampleLevelExactType(expr))
605 }
606 },
607 _ => match resolver[expr] {
608 Ti::Scalar(Sc {
609 kind: Sk::Float, ..
610 }) => {}
611 _ => {
612 return Err(ExpressionError::InvalidSampleLevelExactType(expr))
613 }
614 },
615 }
616 ShaderStages::all()
617 }
618 crate::SampleLevel::Bias(expr) => {
619 match resolver[expr] {
620 Ti::Scalar(Sc {
621 kind: Sk::Float, ..
622 }) => {}
623 _ => return Err(ExpressionError::InvalidSampleLevelBiasType(expr)),
624 }
625 match class {
626 crate::ImageClass::Sampled {
627 kind: Sk::Float,
628 multi: false,
629 } => {
630 if dim == crate::ImageDimension::D1 {
631 return Err(ExpressionError::InvalidSampleLevelBiasDimension(
632 dim,
633 ));
634 }
635 }
636 _ => return Err(ExpressionError::InvalidImageClass(class)),
637 }
638 ShaderStages::FRAGMENT
639 }
640 crate::SampleLevel::Gradient { x, y } => {
641 match resolver[x] {
642 Ti::Scalar(Sc {
643 kind: Sk::Float, ..
644 }) if num_components == 1 => {}
645 Ti::Vector {
646 size,
647 scalar:
648 Sc {
649 kind: Sk::Float, ..
650 },
651 } if size as u32 == num_components => {}
652 _ => {
653 return Err(ExpressionError::InvalidSampleLevelGradientType(dim, x))
654 }
655 }
656 match resolver[y] {
657 Ti::Scalar(Sc {
658 kind: Sk::Float, ..
659 }) if num_components == 1 => {}
660 Ti::Vector {
661 size,
662 scalar:
663 Sc {
664 kind: Sk::Float, ..
665 },
666 } if size as u32 == num_components => {}
667 _ => {
668 return Err(ExpressionError::InvalidSampleLevelGradientType(dim, y))
669 }
670 }
671 ShaderStages::all()
672 }
673 }
674 }
675 E::ImageLoad {
676 image,
677 coordinate,
678 array_index,
679 sample,
680 level,
681 } => {
682 let ty = Self::global_var_ty(module, function, image)?;
683 let Ti::Image {
684 class,
685 arrayed,
686 dim,
687 } = module.types[ty].inner
688 else {
689 return Err(ExpressionError::ExpectedImageType(ty));
690 };
691
692 match resolver[coordinate].image_storage_coordinates() {
693 Some(coord_dim) if coord_dim == dim => {}
694 _ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)),
695 };
696 if arrayed != array_index.is_some() {
697 return Err(ExpressionError::InvalidImageArrayIndex);
698 }
699 if let Some(expr) = array_index {
700 if !matches!(resolver[expr], Ti::Scalar(Sc::I32 | Sc::U32)) {
701 return Err(ExpressionError::InvalidImageArrayIndexType(expr));
702 }
703 }
704
705 match (sample, class.is_multisampled()) {
706 (None, false) => {}
707 (Some(sample), true) => {
708 if !matches!(resolver[sample], Ti::Scalar(Sc::I32 | Sc::U32)) {
709 return Err(ExpressionError::InvalidImageOtherIndexType(sample));
710 }
711 }
712 _ => {
713 return Err(ExpressionError::InvalidImageOtherIndex);
714 }
715 }
716
717 match (level, class.is_mipmapped()) {
718 (None, false) => {}
719 (Some(level), true) => match resolver[level] {
720 Ti::Scalar(Sc {
721 kind: Sk::Sint | Sk::Uint,
722 width: _,
723 }) => {}
724 _ => return Err(ExpressionError::InvalidImageArrayIndexType(level)),
725 },
726 _ => {
727 return Err(ExpressionError::InvalidImageOtherIndex);
728 }
729 }
730 ShaderStages::all()
731 }
732 E::ImageQuery { image, query } => {
733 let ty = Self::global_var_ty(module, function, image)?;
734 match module.types[ty].inner {
735 Ti::Image { class, arrayed, .. } => {
736 let good = match query {
737 crate::ImageQuery::NumLayers => arrayed,
738 crate::ImageQuery::Size { level: None } => true,
739 crate::ImageQuery::Size { level: Some(level) } => {
740 match resolver[level] {
741 Ti::Scalar(Sc::I32 | Sc::U32) => {}
742 _ => {
743 return Err(ExpressionError::InvalidImageOtherIndexType(
744 level,
745 ))
746 }
747 }
748 class.is_mipmapped()
749 }
750 crate::ImageQuery::NumLevels => class.is_mipmapped(),
751 crate::ImageQuery::NumSamples => class.is_multisampled(),
752 };
753 if !good {
754 return Err(ExpressionError::InvalidImageClass(class));
755 }
756 }
757 _ => return Err(ExpressionError::ExpectedImageType(ty)),
758 }
759 ShaderStages::all()
760 }
761 E::Unary { op, expr } => {
762 use crate::UnaryOperator as Uo;
763 let inner = &resolver[expr];
764 match (op, inner.scalar_kind()) {
765 (Uo::Negate, Some(Sk::Float | Sk::Sint))
766 | (Uo::LogicalNot, Some(Sk::Bool))
767 | (Uo::BitwiseNot, Some(Sk::Sint | Sk::Uint)) => {}
768 other => {
769 log::error!("Op {:?} kind {:?}", op, other);
770 return Err(ExpressionError::InvalidUnaryOperandType(op, expr));
771 }
772 }
773 ShaderStages::all()
774 }
775 E::Binary { op, left, right } => {
776 use crate::BinaryOperator as Bo;
777 let left_inner = &resolver[left];
778 let right_inner = &resolver[right];
779 let good = match op {
780 Bo::Add | Bo::Subtract => match *left_inner {
781 Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
782 Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
783 Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat => false,
784 },
785 Ti::Matrix { .. } => left_inner == right_inner,
786 _ => false,
787 },
788 Bo::Divide | Bo::Modulo => match *left_inner {
789 Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
790 Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
791 Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat => false,
792 },
793 _ => false,
794 },
795 Bo::Multiply => {
796 let kind_allowed = match left_inner.scalar_kind() {
797 Some(Sk::Uint | Sk::Sint | Sk::Float) => true,
798 Some(Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat) | None => false,
799 };
800 let types_match = match (left_inner, right_inner) {
801 (&Ti::Scalar(scalar1), &Ti::Scalar(scalar2))
803 | (
804 &Ti::Vector {
805 scalar: scalar1, ..
806 },
807 &Ti::Scalar(scalar2),
808 )
809 | (
810 &Ti::Scalar(scalar1),
811 &Ti::Vector {
812 scalar: scalar2, ..
813 },
814 ) => scalar1 == scalar2,
815 (
817 &Ti::Scalar(Sc {
818 kind: Sk::Float, ..
819 }),
820 &Ti::Matrix { .. },
821 )
822 | (
823 &Ti::Matrix { .. },
824 &Ti::Scalar(Sc {
825 kind: Sk::Float, ..
826 }),
827 ) => true,
828 (
830 &Ti::Vector {
831 size: size1,
832 scalar: scalar1,
833 },
834 &Ti::Vector {
835 size: size2,
836 scalar: scalar2,
837 },
838 ) => scalar1 == scalar2 && size1 == size2,
839 (
841 &Ti::Matrix { columns, .. },
842 &Ti::Vector {
843 size,
844 scalar:
845 Sc {
846 kind: Sk::Float, ..
847 },
848 },
849 ) => columns == size,
850 (
852 &Ti::Vector {
853 size,
854 scalar:
855 Sc {
856 kind: Sk::Float, ..
857 },
858 },
859 &Ti::Matrix { rows, .. },
860 ) => size == rows,
861 (&Ti::Matrix { columns, .. }, &Ti::Matrix { rows, .. }) => {
862 columns == rows
863 }
864 _ => false,
865 };
866 let left_width = left_inner.scalar_width().unwrap_or(0);
867 let right_width = right_inner.scalar_width().unwrap_or(0);
868 kind_allowed && types_match && left_width == right_width
869 }
870 Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner,
871 Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => {
872 match *left_inner {
873 Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
874 Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
875 Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat => false,
876 },
877 ref other => {
878 log::error!("Op {:?} left type {:?}", op, other);
879 false
880 }
881 }
882 }
883 Bo::LogicalAnd | Bo::LogicalOr => match *left_inner {
884 Ti::Scalar(Sc { kind: Sk::Bool, .. })
885 | Ti::Vector {
886 scalar: Sc { kind: Sk::Bool, .. },
887 ..
888 } => left_inner == right_inner,
889 ref other => {
890 log::error!("Op {:?} left type {:?}", op, other);
891 false
892 }
893 },
894 Bo::And | Bo::InclusiveOr => match *left_inner {
895 Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
896 Sk::Bool | Sk::Sint | Sk::Uint => left_inner == right_inner,
897 Sk::Float | Sk::AbstractInt | Sk::AbstractFloat => false,
898 },
899 ref other => {
900 log::error!("Op {:?} left type {:?}", op, other);
901 false
902 }
903 },
904 Bo::ExclusiveOr => match *left_inner {
905 Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
906 Sk::Sint | Sk::Uint => left_inner == right_inner,
907 Sk::Bool | Sk::Float | Sk::AbstractInt | Sk::AbstractFloat => false,
908 },
909 ref other => {
910 log::error!("Op {:?} left type {:?}", op, other);
911 false
912 }
913 },
914 Bo::ShiftLeft | Bo::ShiftRight => {
915 let (base_size, base_scalar) = match *left_inner {
916 Ti::Scalar(scalar) => (Ok(None), scalar),
917 Ti::Vector { size, scalar } => (Ok(Some(size)), scalar),
918 ref other => {
919 log::error!("Op {:?} base type {:?}", op, other);
920 (Err(()), Sc::BOOL)
921 }
922 };
923 let shift_size = match *right_inner {
924 Ti::Scalar(Sc { kind: Sk::Uint, .. }) => Ok(None),
925 Ti::Vector {
926 size,
927 scalar: Sc { kind: Sk::Uint, .. },
928 } => Ok(Some(size)),
929 ref other => {
930 log::error!("Op {:?} shift type {:?}", op, other);
931 Err(())
932 }
933 };
934 match base_scalar.kind {
935 Sk::Sint | Sk::Uint => base_size.is_ok() && base_size == shift_size,
936 Sk::Float | Sk::AbstractInt | Sk::AbstractFloat | Sk::Bool => false,
937 }
938 }
939 };
940 if !good {
941 log::error!(
942 "Left: {:?} of type {:?}",
943 function.expressions[left],
944 left_inner
945 );
946 log::error!(
947 "Right: {:?} of type {:?}",
948 function.expressions[right],
949 right_inner
950 );
951 return Err(ExpressionError::InvalidBinaryOperandTypes {
952 op,
953 lhs_expr: left,
954 lhs_type: left_inner.clone(),
955 rhs_expr: right,
956 rhs_type: right_inner.clone(),
957 });
958 }
959 ShaderStages::all()
960 }
961 E::Select {
962 condition,
963 accept,
964 reject,
965 } => {
966 let accept_inner = &resolver[accept];
967 let reject_inner = &resolver[reject];
968 let condition_ty = &resolver[condition];
969 let condition_good = match *condition_ty {
970 Ti::Scalar(Sc {
971 kind: Sk::Bool,
972 width: _,
973 }) => {
974 match *accept_inner {
977 Ti::Scalar { .. } | Ti::Vector { .. } => true,
978 _ => false,
979 }
980 }
981 Ti::Vector {
982 size,
983 scalar:
984 Sc {
985 kind: Sk::Bool,
986 width: _,
987 },
988 } => match *accept_inner {
989 Ti::Vector {
990 size: other_size, ..
991 } => size == other_size,
992 _ => false,
993 },
994 _ => false,
995 };
996 if accept_inner != reject_inner {
997 return Err(ExpressionError::SelectValuesTypeMismatch {
998 accept: accept_inner.clone(),
999 reject: reject_inner.clone(),
1000 });
1001 }
1002 if !condition_good {
1003 return Err(ExpressionError::SelectConditionNotABool {
1004 actual: condition_ty.clone(),
1005 });
1006 }
1007 ShaderStages::all()
1008 }
1009 E::Derivative { expr, .. } => {
1010 match resolver[expr] {
1011 Ti::Scalar(Sc {
1012 kind: Sk::Float, ..
1013 })
1014 | Ti::Vector {
1015 scalar:
1016 Sc {
1017 kind: Sk::Float, ..
1018 },
1019 ..
1020 } => {}
1021 _ => return Err(ExpressionError::InvalidDerivative),
1022 }
1023 ShaderStages::FRAGMENT
1024 }
1025 E::Relational { fun, argument } => {
1026 use crate::RelationalFunction as Rf;
1027 let argument_inner = &resolver[argument];
1028 match fun {
1029 Rf::All | Rf::Any => match *argument_inner {
1030 Ti::Vector {
1031 scalar: Sc { kind: Sk::Bool, .. },
1032 ..
1033 } => {}
1034 ref other => {
1035 log::error!("All/Any of type {:?}", other);
1036 return Err(ExpressionError::InvalidBooleanVector(argument));
1037 }
1038 },
1039 Rf::IsNan | Rf::IsInf => match *argument_inner {
1040 Ti::Scalar(scalar) | Ti::Vector { scalar, .. }
1041 if scalar.kind == Sk::Float => {}
1042 ref other => {
1043 log::error!("Float test of type {:?}", other);
1044 return Err(ExpressionError::InvalidFloatArgument(argument));
1045 }
1046 },
1047 }
1048 ShaderStages::all()
1049 }
1050 E::Math {
1051 fun,
1052 arg,
1053 arg1,
1054 arg2,
1055 arg3,
1056 } => {
1057 let actuals: &[_] = match (arg1, arg2, arg3) {
1058 (None, None, None) => &[arg],
1059 (Some(arg1), None, None) => &[arg, arg1],
1060 (Some(arg1), Some(arg2), None) => &[arg, arg1, arg2],
1061 (Some(arg1), Some(arg2), Some(arg3)) => &[arg, arg1, arg2, arg3],
1062 _ => return Err(ExpressionError::WrongArgumentCount(fun)),
1063 };
1064
1065 let resolve = |arg| &resolver[arg];
1066 let actual_types: &[_] = match *actuals {
1067 [arg0] => &[resolve(arg0)],
1068 [arg0, arg1] => &[resolve(arg0), resolve(arg1)],
1069 [arg0, arg1, arg2] => &[resolve(arg0), resolve(arg1), resolve(arg2)],
1070 [arg0, arg1, arg2, arg3] => {
1071 &[resolve(arg0), resolve(arg1), resolve(arg2), resolve(arg3)]
1072 }
1073 _ => unreachable!(),
1074 };
1075
1076 let mut overloads = fun.overloads();
1078 log::debug!(
1079 "initial overloads for {:?}: {:#?}",
1080 fun,
1081 overloads.for_debug(&module.types)
1082 );
1083
1084 for (i, (&expr, &ty)) in actuals.iter().zip(actual_types).enumerate() {
1092 overloads = overloads.arg(i, ty, &module.types);
1095 log::debug!(
1096 "overloads after arg {i}: {:#?}",
1097 overloads.for_debug(&module.types)
1098 );
1099
1100 if overloads.is_empty() {
1101 log::debug!("all overloads eliminated");
1102 return Err(ExpressionError::InvalidArgumentType(fun, i as u32, expr));
1103 }
1104 }
1105
1106 if actuals.len() < overloads.min_arguments() {
1107 return Err(ExpressionError::WrongArgumentCount(fun));
1108 }
1109
1110 ShaderStages::all()
1111 }
1112 E::As {
1113 expr,
1114 kind,
1115 convert,
1116 } => {
1117 let mut base_scalar = match resolver[expr] {
1118 crate::TypeInner::Scalar(scalar) | crate::TypeInner::Vector { scalar, .. } => {
1119 scalar
1120 }
1121 crate::TypeInner::Matrix { scalar, .. } => scalar,
1122 _ => return Err(ExpressionError::InvalidCastArgument),
1123 };
1124 base_scalar.kind = kind;
1125 if let Some(width) = convert {
1126 base_scalar.width = width;
1127 }
1128 if self.check_width(base_scalar).is_err() {
1129 return Err(ExpressionError::InvalidCastArgument);
1130 }
1131 ShaderStages::all()
1132 }
1133 E::CallResult(function) => mod_info.functions[function.index()].available_stages,
1134 E::AtomicResult { .. } => {
1135 ShaderStages::all()
1140 }
1141 E::WorkGroupUniformLoadResult { ty } => {
1142 if self.types[ty.index()]
1143 .flags
1144 .contains(TypeFlags::SIZED | TypeFlags::CONSTRUCTIBLE)
1147 {
1148 ShaderStages::COMPUTE
1149 } else {
1150 return Err(ExpressionError::InvalidWorkGroupUniformLoadResultType(ty));
1151 }
1152 }
1153 E::ArrayLength(expr) => match resolver[expr] {
1154 Ti::Pointer { base, .. } => {
1155 let base_ty = &resolver.types[base];
1156 if let Ti::Array {
1157 size: crate::ArraySize::Dynamic,
1158 ..
1159 } = base_ty.inner
1160 {
1161 ShaderStages::all()
1162 } else {
1163 return Err(ExpressionError::InvalidArrayType(expr));
1164 }
1165 }
1166 ref other => {
1167 log::error!("Array length of {:?}", other);
1168 return Err(ExpressionError::InvalidArrayType(expr));
1169 }
1170 },
1171 E::RayQueryProceedResult => ShaderStages::all(),
1172 E::RayQueryGetIntersection {
1173 query,
1174 committed: _,
1175 } => match resolver[query] {
1176 Ti::Pointer {
1177 base,
1178 space: crate::AddressSpace::Function,
1179 } => match resolver.types[base].inner {
1180 Ti::RayQuery { .. } => ShaderStages::all(),
1181 ref other => {
1182 log::error!("Intersection result of a pointer to {:?}", other);
1183 return Err(ExpressionError::InvalidRayQueryType(query));
1184 }
1185 },
1186 ref other => {
1187 log::error!("Intersection result of {:?}", other);
1188 return Err(ExpressionError::InvalidRayQueryType(query));
1189 }
1190 },
1191 E::RayQueryVertexPositions {
1192 query,
1193 committed: _,
1194 } => match resolver[query] {
1195 Ti::Pointer {
1196 base,
1197 space: crate::AddressSpace::Function,
1198 } => match resolver.types[base].inner {
1199 Ti::RayQuery {
1200 vertex_return: true,
1201 } => ShaderStages::all(),
1202 ref other => {
1203 log::error!("Intersection result of a pointer to {:?}", other);
1204 return Err(ExpressionError::InvalidRayQueryType(query));
1205 }
1206 },
1207 ref other => {
1208 log::error!("Intersection result of {:?}", other);
1209 return Err(ExpressionError::InvalidRayQueryType(query));
1210 }
1211 },
1212 E::SubgroupBallotResult | E::SubgroupOperationResult { .. } => self.subgroup_stages,
1213 };
1214 Ok(stages)
1215 }
1216
1217 fn global_var_ty(
1218 module: &crate::Module,
1219 function: &crate::Function,
1220 expr: Handle<crate::Expression>,
1221 ) -> Result<Handle<crate::Type>, ExpressionError> {
1222 use crate::Expression as Ex;
1223
1224 match function.expressions[expr] {
1225 Ex::GlobalVariable(var_handle) => Ok(module.global_variables[var_handle].ty),
1226 Ex::FunctionArgument(i) => Ok(function.arguments[i as usize].ty),
1227 Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => {
1228 match function.expressions[base] {
1229 Ex::GlobalVariable(var_handle) => {
1230 let array_ty = module.global_variables[var_handle].ty;
1231
1232 match module.types[array_ty].inner {
1233 crate::TypeInner::BindingArray { base, .. } => Ok(base),
1234 _ => Err(ExpressionError::ExpectedBindingArrayType(array_ty)),
1235 }
1236 }
1237 _ => Err(ExpressionError::ExpectedGlobalVariable),
1238 }
1239 }
1240 _ => Err(ExpressionError::ExpectedGlobalVariable),
1241 }
1242 }
1243
1244 pub fn validate_literal(&self, literal: crate::Literal) -> Result<(), LiteralError> {
1245 let _ = self.check_width(literal.scalar())?;
1246 check_literal_value(literal)?;
1247
1248 Ok(())
1249 }
1250}
1251
1252pub fn check_literal_value(literal: crate::Literal) -> Result<(), LiteralError> {
1253 let is_nan = match literal {
1254 crate::Literal::F64(v) => v.is_nan(),
1255 crate::Literal::F32(v) => v.is_nan(),
1256 _ => false,
1257 };
1258 if is_nan {
1259 return Err(LiteralError::NaN);
1260 }
1261
1262 let is_infinite = match literal {
1263 crate::Literal::F64(v) => v.is_infinite(),
1264 crate::Literal::F32(v) => v.is_infinite(),
1265 _ => false,
1266 };
1267 if is_infinite {
1268 return Err(LiteralError::Infinity);
1269 }
1270
1271 Ok(())
1272}
1273
1274#[cfg(test)]
1275fn validate_with_expression(
1277 expr: crate::Expression,
1278 caps: super::Capabilities,
1279) -> Result<ModuleInfo, crate::span::WithSpan<super::ValidationError>> {
1280 use crate::span::Span;
1281
1282 let mut function = crate::Function::default();
1283 function.expressions.append(expr, Span::default());
1284 function.body.push(
1285 crate::Statement::Emit(function.expressions.range_from(0)),
1286 Span::default(),
1287 );
1288
1289 let mut module = crate::Module::default();
1290 module.functions.append(function, Span::default());
1291
1292 let mut validator = super::Validator::new(super::ValidationFlags::EXPRESSIONS, caps);
1293
1294 validator.validate(&module)
1295}
1296
1297#[cfg(test)]
1298fn validate_with_const_expression(
1300 expr: crate::Expression,
1301 caps: super::Capabilities,
1302) -> Result<ModuleInfo, crate::span::WithSpan<super::ValidationError>> {
1303 use crate::span::Span;
1304
1305 let mut module = crate::Module::default();
1306 module.global_expressions.append(expr, Span::default());
1307
1308 let mut validator = super::Validator::new(super::ValidationFlags::CONSTANTS, caps);
1309
1310 validator.validate(&module)
1311}
1312
1313#[test]
1315fn f64_runtime_literals() {
1316 let result = validate_with_expression(
1317 crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1318 super::Capabilities::default(),
1319 );
1320 let error = result.unwrap_err().into_inner();
1321 assert!(matches!(
1322 error,
1323 crate::valid::ValidationError::Function {
1324 source: super::FunctionError::Expression {
1325 source: ExpressionError::Literal(LiteralError::Width(
1326 super::r#type::WidthError::MissingCapability {
1327 name: "f64",
1328 flag: "FLOAT64",
1329 }
1330 ),),
1331 ..
1332 },
1333 ..
1334 }
1335 ));
1336
1337 let result = validate_with_expression(
1338 crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1339 super::Capabilities::default() | super::Capabilities::FLOAT64,
1340 );
1341 assert!(result.is_ok());
1342}
1343
1344#[test]
1346fn f64_const_literals() {
1347 let result = validate_with_const_expression(
1348 crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1349 super::Capabilities::default(),
1350 );
1351 let error = result.unwrap_err().into_inner();
1352 assert!(matches!(
1353 error,
1354 crate::valid::ValidationError::ConstExpression {
1355 source: ConstExpressionError::Literal(LiteralError::Width(
1356 super::r#type::WidthError::MissingCapability {
1357 name: "f64",
1358 flag: "FLOAT64",
1359 }
1360 )),
1361 ..
1362 }
1363 ));
1364
1365 let result = validate_with_const_expression(
1366 crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1367 super::Capabilities::default() | super::Capabilities::FLOAT64,
1368 );
1369 assert!(result.is_ok());
1370}